@aikaara/chat-sdk 1.5.9 → 1.5.11

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(Me){"use strict";class Bo{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 sn{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 Bo(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 gr{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 Ic=1e3,Tc=10,Cc=400,Pc=600,Do="#6366f1",Oc=12,Mc="system-ui, -apple-system, sans-serif",Fo="Type a message...",Rc="bottom-right",Lc="light",Nc={x:20,y:20},an="aikaara_conversation_id";class $o extends gr{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 sn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}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??Tc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Ic)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new sn(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 qo{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 a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(s,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const o=await n.json();if(o&&typeof o=="object"&&"success"in o){if(!o.success)throw new Error(`API error: ${o.message||"Request failed"}`);return o.data}return o}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 Ho{_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=Wo(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=Wo(t,r);if(s){const n=yr(s),o=yr(r);!n&&o&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function Wo(i,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const o=yr(e),a=zo(e),l=Vo(e);if(!o&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=i.length-1;u>=0;u--){const d=i[u],p=d.attachments&&d.attachments[0],y=(d.metadata??{}).attributes;if(!(!!p||!!(y&&y.fileMessage)))continue;const g=(d.content||"").trim().toLowerCase();if(g==="file_uploaded"||g==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const b=yr(d);if(o&&b&&o===b)return d;const w=zo(d);if(a&&w&&a===w)return d;const m=Vo(d);if(l&&m&&l===m)return d}return null}function zo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Ko(i);if(t)return t}function Vo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(i.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=i.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function yr(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(i.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Ko(i);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function Ko(i){const e=i.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Go{_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(an)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(an)}catch{return null}}saveToStorage(e){try{localStorage.setItem(an,e)}catch{}}}var ln=Object.defineProperty,jc=Object.getOwnPropertyDescriptor,Uc=Object.getOwnPropertyNames,Bc=Object.prototype.hasOwnProperty,Ye=(i,e)=>()=>(i&&(e=i(i=0)),e),pe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),$t=(i,e)=>{for(var t in e)ln(i,t,{get:e[t],enumerable:!0})},Dc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Uc(e))!Bc.call(i,s)&&s!==t&&ln(i,s,{get:()=>e[s],enumerable:!(r=jc(e,s))||r.enumerable});return i},Ne=i=>Dc(ln({},"__esModule",{value:!0}),i),le=Ye(()=>{}),je={};$t(je,{_debugEnd:()=>Hn,_debugProcess:()=>qn,_events:()=>oi,_eventsCount:()=>si,_exiting:()=>Tn,_fatalExceptions:()=>Dn,_getActiveHandles:()=>ts,_getActiveRequests:()=>es,_kill:()=>On,_linkedBinding:()=>Xo,_maxListeners:()=>ii,_preload_modules:()=>ti,_rawDebug:()=>En,_startProfilerIdleNotifier:()=>Wn,_stopProfilerIdleNotifier:()=>zn,_tickCallback:()=>$n,abort:()=>Yn,addListener:()=>ai,allowedNodeEnvironmentFlags:()=>Un,arch:()=>dn,argv:()=>pn,argv0:()=>ei,assert:()=>rs,binding:()=>vn,browser:()=>Sn,chdir:()=>_n,config:()=>Cn,cpuUsage:()=>tr,cwd:()=>kn,debugPort:()=>Zn,default:()=>mi,dlopen:()=>Zo,domain:()=>In,emit:()=>hi,emitWarning:()=>bn,env:()=>fn,execArgv:()=>mn,execPath:()=>Xn,exit:()=>Nn,features:()=>Bn,hasUncaughtExceptionCaptureCallback:()=>ns,hrtime:()=>br,kill:()=>Ln,listeners:()=>os,memoryUsage:()=>Rn,moduleLoadList:()=>An,nextTick:()=>Jo,off:()=>ci,on:()=>ct,once:()=>li,openStdin:()=>jn,pid:()=>Jn,platform:()=>hn,ppid:()=>Qn,prependListener:()=>fi,prependOnceListener:()=>pi,reallyExit:()=>Pn,release:()=>xn,removeAllListeners:()=>di,removeListener:()=>ui,resourceUsage:()=>Mn,setSourceMapsEnabled:()=>ri,setUncaughtExceptionCaptureCallback:()=>Fn,stderr:()=>Kn,stdin:()=>Gn,stdout:()=>Vn,title:()=>un,umask:()=>wn,uptime:()=>is,version:()=>gn,versions:()=>yn});function cn(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Fc(){!Ct||!Pt||(Ct=!1,Pt.length?tt=Pt.concat(tt):er=-1,tt.length&&Yo())}function Yo(){if(!Ct){var i=setTimeout(Fc,0);Ct=!0;for(var e=tt.length;e;){for(Pt=tt,tt=[];++er<e;)Pt&&Pt[er].run();er=-1,e=tt.length}Pt=null,Ct=!1,clearTimeout(i)}}function Jo(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Qo(i,e)),tt.length===1&&!Ct&&setTimeout(Yo,0)}function Qo(i,e){this.fun=i,this.array=e}function He(){}function Xo(i){cn("_linkedBinding")}function Zo(i){cn("dlopen")}function es(){return[]}function ts(){return[]}function rs(i,e){if(!i)throw new Error(e||"assertion error")}function ns(){return!1}function is(){return ut.now()/1e3}function br(i){var e=Math.floor((Date.now()-ut.now())*.001),t=ut.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=vr)),[r,s]}function ct(){return mi}function os(i){return[]}var tt,Ct,Pt,er,un,dn,hn,fn,pn,mn,gn,yn,bn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Pn,On,tr,Mn,Rn,Ln,Nn,jn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ut,ni,vr,ii,oi,si,ai,li,ci,ui,di,hi,fi,pi,mi,$c=Ye(()=>{le(),ue(),ce(),tt=[],Ct=!1,er=-1,Qo.prototype.run=function(){this.fun.apply(null,this.array)},un="browser",dn="x64",hn="browser",fn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},pn=["/usr/bin/node"],mn=[],gn="v16.8.0",yn={},bn=function(i,e){console.warn((e?e+": ":"")+i)},vn=function(i){cn("binding")},wn=function(i){return 0},kn=function(){return"/"},_n=function(i){},xn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Sn=!0,En=He,An=[],In={},Tn=!1,Cn={},Pn=He,On=He,tr=function(){return{}},Mn=tr,Rn=tr,Ln=He,Nn=He,jn=He,Un={},Bn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Dn=He,Fn=He,$n=He,qn=He,Hn=He,Wn=He,zn=He,Vn=void 0,Kn=void 0,Gn=void 0,Yn=He,Jn=2,Qn=1,Xn="/bin/usr/node",Zn=9229,ei="node",ti=[],ri=He,ut={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ut.now===void 0&&(ni=Date.now(),ut.timing&&ut.timing.navigationStart&&(ni=ut.timing.navigationStart),ut.now=()=>Date.now()-ni),vr=1e9,br.bigint=function(i){var e=br(i);return typeof BigInt>"u"?e[0]*vr+e[1]:BigInt(e[0]*vr)+BigInt(e[1])},ii=10,oi={},si=0,ai=ct,li=ct,ci=ct,ui=ct,di=ct,hi=He,fi=ct,pi=ct,mi={version:gn,versions:yn,arch:dn,platform:hn,browser:Sn,release:xn,_rawDebug:En,moduleLoadList:An,binding:vn,_linkedBinding:Xo,_events:oi,_eventsCount:si,_maxListeners:ii,on:ct,addListener:ai,once:li,off:ci,removeListener:ui,removeAllListeners:di,emit:hi,prependListener:fi,prependOnceListener:pi,listeners:os,domain:In,_exiting:Tn,config:Cn,dlopen:Zo,uptime:is,_getActiveRequests:es,_getActiveHandles:ts,reallyExit:Pn,_kill:On,cpuUsage:tr,resourceUsage:Mn,memoryUsage:Rn,kill:Ln,exit:Nn,openStdin:jn,allowedNodeEnvironmentFlags:Un,assert:rs,features:Bn,_fatalExceptions:Dn,setUncaughtExceptionCaptureCallback:Fn,hasUncaughtExceptionCaptureCallback:ns,emitWarning:bn,nextTick:Jo,_tickCallback:$n,_debugProcess:qn,_debugEnd:Hn,_startProfilerIdleNotifier:Wn,_stopProfilerIdleNotifier:zn,stdout:Vn,stdin:Gn,stderr:Kn,abort:Yn,umask:wn,chdir:_n,cwd:kn,env:fn,title:un,argv:pn,execArgv:mn,pid:Jn,ppid:Qn,execPath:Xn,debugPort:Zn,hrtime:br,argv0:ei,_preload_modules:ti,setSourceMapsEnabled:ri}}),ce=Ye(()=>{$c()});function qc(){if(gi)return qt;gi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)i[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function o(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 a(y){var f=o(y),g=f[0],b=f[1];return(g+b)*3/4-b}function l(y,f,g){return(f+g)*3/4-g}function c(y){var f,g=o(y),b=g[0],w=g[1],m=new t(l(y,b,w)),k=0,x=w>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[k++]=f>>16&255,m[k++]=f>>8&255,m[k++]=f&255;return w===2&&(f=e[y.charCodeAt(v)]<<2|e[y.charCodeAt(v+1)]>>4,m[k++]=f&255),w===1&&(f=e[y.charCodeAt(v)]<<10|e[y.charCodeAt(v+1)]<<4|e[y.charCodeAt(v+2)]>>2,m[k++]=f>>8&255,m[k++]=f&255),m}function u(y){return i[y>>18&63]+i[y>>12&63]+i[y>>6&63]+i[y&63]}function d(y,f,g){for(var b,w=[],m=f;m<g;m+=3)b=(y[m]<<16&16711680)+(y[m+1]<<8&65280)+(y[m+2]&255),w.push(u(b));return w.join("")}function p(y){for(var f,g=y.length,b=g%3,w=[],m=16383,k=0,x=g-b;k<x;k+=m)w.push(d(y,k,k+m>x?x:k+m));return b===1?(f=y[g-1],w.push(i[f>>2]+i[f<<4&63]+"==")):b===2&&(f=(y[g-2]<<8)+y[g-1],w.push(i[f>>10]+i[f>>4&63]+i[f<<2&63]+"=")),w.join("")}return qt}function Hc(){return yi?rr:(yi=!0,rr.read=function(i,e,t,r,s){var n,o,a=s*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?s-1:0,p=t?-1:1,y=i[e+d];for(d+=p,n=y&(1<<-u)-1,y>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=p,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=r;u>0;o=o*256+i[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),n=n-c}return(y?-1:1)*o*Math.pow(2,n-r)},rr.write=function(i,e,t,r,s,n){var o,a,l,c=n*8-s-1,u=(1<<c)-1,d=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?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(o++,l/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(e*l-1)*Math.pow(2,s),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;i[t+y]=a&255,y+=f,a/=256,s-=8);for(o=o<<s|a,c+=s;c>0;i[t+y]=o&255,y+=f,o/=256,c-=8);i[t+y-f]|=g*128},rr)}function Wc(){if(bi)return vt;bi=!0;let i=qc(),e=Hc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;vt.Buffer=o,vt.SlowBuffer=w,vt.INSPECT_MAX_BYTES=50;let r=2147483647;vt.kMaxLength=r,o.TYPED_ARRAY_SUPPORT=s(),!o.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 h=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(h,_),h.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let _=new Uint8Array(h);return Object.setPrototypeOf(_,o.prototype),_}function o(h,_,I){if(typeof h=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,_,I)}o.poolSize=8192;function a(h,_,I){if(typeof h=="string")return d(h,_);if(ArrayBuffer.isView(h))return y(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(H(h,ArrayBuffer)||h&&H(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(h,SharedArrayBuffer)||h&&H(h.buffer,SharedArrayBuffer)))return f(h,_,I);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let F=h.valueOf&&h.valueOf();if(F!=null&&F!==h)return o.from(F,_,I);let X=g(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return o.from(h[Symbol.toPrimitive]("string"),_,I);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}o.from=function(h,_,I){return a(h,_,I)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function c(h,_,I){return l(h),h<=0?n(h):_!==void 0?typeof I=="string"?n(h).fill(_,I):n(h).fill(_):n(h)}o.alloc=function(h,_,I){return c(h,_,I)};function u(h){return l(h),n(h<0?0:b(h)|0)}o.allocUnsafe=function(h){return u(h)},o.allocUnsafeSlow=function(h){return u(h)};function d(h,_){if((typeof _!="string"||_==="")&&(_="utf8"),!o.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let I=m(h,_)|0,F=n(I),X=F.write(h,_);return X!==I&&(F=F.slice(0,X)),F}function p(h){let _=h.length<0?0:b(h.length)|0,I=n(_);for(let F=0;F<_;F+=1)I[F]=h[F]&255;return I}function y(h){if(H(h,Uint8Array)){let _=new Uint8Array(h);return f(_.buffer,_.byteOffset,_.byteLength)}return p(h)}function f(h,_,I){if(_<0||h.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<_+(I||0))throw new RangeError('"length" is outside of buffer bounds');let F;return _===void 0&&I===void 0?F=new Uint8Array(h):I===void 0?F=new Uint8Array(h,_):F=new Uint8Array(h,_,I),Object.setPrototypeOf(F,o.prototype),F}function g(h){if(o.isBuffer(h)){let _=b(h.length)|0,I=n(_);return I.length===0||h.copy(I,0,0,_),I}if(h.length!==void 0)return typeof h.length!="number"||me(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function b(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),o.alloc(+h)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,_){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),H(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),!o.isBuffer(h)||!o.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===_)return 0;let I=h.length,F=_.length;for(let X=0,de=Math.min(I,F);X<de;++X)if(h[X]!==_[X]){I=h[X],F=_[X];break}return I<F?-1:F<I?1:0},o.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(h,_){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let I;if(_===void 0)for(_=0,I=0;I<h.length;++I)_+=h[I].length;let F=o.allocUnsafe(_),X=0;for(I=0;I<h.length;++I){let de=h[I];if(H(de,Uint8Array))X+de.length>F.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(F,X)):Uint8Array.prototype.set.call(F,de,X);else if(o.isBuffer(de))de.copy(F,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return F};function m(h,_){if(o.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||H(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let I=h.length,F=arguments.length>2&&arguments[2]===!0;if(!F&&I===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return I;case"utf8":case"utf-8":return q(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I*2;case"hex":return I>>>1;case"base64":return fe(h).length;default:if(X)return F?-1:q(h).length;_=(""+_).toLowerCase(),X=!0}}o.byteLength=m;function k(h,_,I){let F=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((I===void 0||I>this.length)&&(I=this.length),I<=0)||(I>>>=0,_>>>=0,I<=_))return"";for(h||(h="utf8");;)switch(h){case"hex":return W(this,_,I);case"utf8":case"utf-8":return B(this,_,I);case"ascii":return oe(this,_,I);case"latin1":case"binary":return Y(this,_,I);case"base64":return T(this,_,I);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,I);default:if(F)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),F=!0}}o.prototype._isBuffer=!0;function x(h,_,I){let F=h[_];h[_]=h[I],h[I]=F}o.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<h;_+=2)x(this,_,_+1);return this},o.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<h;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},o.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<h;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},o.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?B(this,0,h):k.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="",_=vt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(h+=" ... "),"<Buffer "+h+">"},t&&(o.prototype[t]=o.prototype.inspect),o.prototype.compare=function(h,_,I,F,X){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(_===void 0&&(_=0),I===void 0&&(I=h?h.length:0),F===void 0&&(F=0),X===void 0&&(X=this.length),_<0||I>h.length||F<0||X>this.length)throw new RangeError("out of range index");if(F>=X&&_>=I)return 0;if(F>=X)return-1;if(_>=I)return 1;if(_>>>=0,I>>>=0,F>>>=0,X>>>=0,this===h)return 0;let de=X-F,_e=I-_,V=Math.min(de,_e),ie=this.slice(F,X),Ae=h.slice(_,I);for(let Ie=0;Ie<V;++Ie)if(ie[Ie]!==Ae[Ie]){de=ie[Ie],_e=Ae[Ie];break}return de<_e?-1:_e<de?1:0};function v(h,_,I,F,X){if(h.length===0)return-1;if(typeof I=="string"?(F=I,I=0):I>2147483647?I=2147483647:I<-2147483648&&(I=-2147483648),I=+I,me(I)&&(I=X?0:h.length-1),I<0&&(I=h.length+I),I>=h.length){if(X)return-1;I=h.length-1}else if(I<0)if(X)I=0;else return-1;if(typeof _=="string"&&(_=o.from(_,F)),o.isBuffer(_))return _.length===0?-1:E(h,_,I,F,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,_,I):Uint8Array.prototype.lastIndexOf.call(h,_,I):E(h,[_],I,F,X);throw new TypeError("val must be string, number or Buffer")}function E(h,_,I,F,X){let de=1,_e=h.length,V=_.length;if(F!==void 0&&(F=String(F).toLowerCase(),F==="ucs2"||F==="ucs-2"||F==="utf16le"||F==="utf-16le")){if(h.length<2||_.length<2)return-1;de=2,_e/=2,V/=2,I/=2}function ie(Ie,Pe){return de===1?Ie[Pe]:Ie.readUInt16BE(Pe*de)}let Ae;if(X){let Ie=-1;for(Ae=I;Ae<_e;Ae++)if(ie(h,Ae)===ie(_,Ie===-1?0:Ae-Ie)){if(Ie===-1&&(Ie=Ae),Ae-Ie+1===V)return Ie*de}else Ie!==-1&&(Ae-=Ae-Ie),Ie=-1}else for(I+V>_e&&(I=_e-V),Ae=I;Ae>=0;Ae--){let Ie=!0;for(let Pe=0;Pe<V;Pe++)if(ie(h,Ae+Pe)!==ie(_,Pe)){Ie=!1;break}if(Ie)return Ae}return-1}o.prototype.includes=function(h,_,I){return this.indexOf(h,_,I)!==-1},o.prototype.indexOf=function(h,_,I){return v(this,h,_,I,!0)},o.prototype.lastIndexOf=function(h,_,I){return v(this,h,_,I,!1)};function S(h,_,I,F){I=Number(I)||0;let X=h.length-I;F?(F=Number(F),F>X&&(F=X)):F=X;let de=_.length;F>de/2&&(F=de/2);let _e;for(_e=0;_e<F;++_e){let V=parseInt(_.substr(_e*2,2),16);if(me(V))return _e;h[I+_e]=V}return _e}function A(h,_,I,F){return be(q(_,h.length-I),h,I,F)}function C(h,_,I,F){return be(ee(_),h,I,F)}function O(h,_,I,F){return be(fe(_),h,I,F)}function j(h,_,I,F){return be(he(_,h.length-I),h,I,F)}o.prototype.write=function(h,_,I,F){if(_===void 0)F="utf8",I=this.length,_=0;else if(I===void 0&&typeof _=="string")F=_,I=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(I)?(I=I>>>0,F===void 0&&(F="utf8")):(F=I,I=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-_;if((I===void 0||I>X)&&(I=X),h.length>0&&(I<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");F||(F="utf8");let de=!1;for(;;)switch(F){case"hex":return S(this,h,_,I);case"utf8":case"utf-8":return A(this,h,_,I);case"ascii":case"latin1":case"binary":return C(this,h,_,I);case"base64":return O(this,h,_,I);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,_,I);default:if(de)throw new TypeError("Unknown encoding: "+F);F=(""+F).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,_,I){return _===0&&I===h.length?i.fromByteArray(h):i.fromByteArray(h.slice(_,I))}function B(h,_,I){I=Math.min(h.length,I);let F=[],X=_;for(;X<I;){let de=h[X],_e=null,V=de>239?4:de>223?3:de>191?2:1;if(X+V<=I){let ie,Ae,Ie,Pe;switch(V){case 1:de<128&&(_e=de);break;case 2:ie=h[X+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(_e=Pe));break;case 3:ie=h[X+1],Ae=h[X+2],(ie&192)===128&&(Ae&192)===128&&(Pe=(de&15)<<12|(ie&63)<<6|Ae&63,Pe>2047&&(Pe<55296||Pe>57343)&&(_e=Pe));break;case 4:ie=h[X+1],Ae=h[X+2],Ie=h[X+3],(ie&192)===128&&(Ae&192)===128&&(Ie&192)===128&&(Pe=(de&15)<<18|(ie&63)<<12|(Ae&63)<<6|Ie&63,Pe>65535&&Pe<1114112&&(_e=Pe))}}_e===null?(_e=65533,V=1):_e>65535&&(_e-=65536,F.push(_e>>>10&1023|55296),_e=56320|_e&1023),F.push(_e),X+=V}return U(F)}let D=4096;function U(h){let _=h.length;if(_<=D)return String.fromCharCode.apply(String,h);let I="",F=0;for(;F<_;)I+=String.fromCharCode.apply(String,h.slice(F,F+=D));return I}function oe(h,_,I){let F="";I=Math.min(h.length,I);for(let X=_;X<I;++X)F+=String.fromCharCode(h[X]&127);return F}function Y(h,_,I){let F="";I=Math.min(h.length,I);for(let X=_;X<I;++X)F+=String.fromCharCode(h[X]);return F}function W(h,_,I){let F=h.length;(!_||_<0)&&(_=0),(!I||I<0||I>F)&&(I=F);let X="";for(let de=_;de<I;++de)X+=ve[h[de]];return X}function re(h,_,I){let F=h.slice(_,I),X="";for(let de=0;de<F.length-1;de+=2)X+=String.fromCharCode(F[de]+F[de+1]*256);return X}o.prototype.slice=function(h,_){let I=this.length;h=~~h,_=_===void 0?I:~~_,h<0?(h+=I,h<0&&(h=0)):h>I&&(h=I),_<0?(_+=I,_<0&&(_=0)):_>I&&(_=I),_<h&&(_=h);let F=this.subarray(h,_);return Object.setPrototypeOf(F,o.prototype),F};function $(h,_,I){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+_>I)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,_,I){h=h>>>0,_=_>>>0,I||$(h,_,this.length);let F=this[h],X=1,de=0;for(;++de<_&&(X*=256);)F+=this[h+de]*X;return F},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,_,I){h=h>>>0,_=_>>>0,I||$(h,_,this.length);let F=this[h+--_],X=1;for(;_>0&&(X*=256);)F+=this[h+--_]*X;return F},o.prototype.readUint8=o.prototype.readUInt8=function(h,_){return h=h>>>0,_||$(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||$(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||$(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||$(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,_){return h=h>>>0,_||$(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],I=this[h+7];(_===void 0||I===void 0)&&ge(h,this.length-8);let F=_+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+I*2**24;return BigInt(F)+(BigInt(X)<<BigInt(32))}),o.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],I=this[h+7];(_===void 0||I===void 0)&&ge(h,this.length-8);let F=_*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],X=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+I;return(BigInt(F)<<BigInt(32))+BigInt(X)}),o.prototype.readIntLE=function(h,_,I){h=h>>>0,_=_>>>0,I||$(h,_,this.length);let F=this[h],X=1,de=0;for(;++de<_&&(X*=256);)F+=this[h+de]*X;return X*=128,F>=X&&(F-=Math.pow(2,8*_)),F},o.prototype.readIntBE=function(h,_,I){h=h>>>0,_=_>>>0,I||$(h,_,this.length);let F=_,X=1,de=this[h+--F];for(;F>0&&(X*=256);)de+=this[h+--F]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*_)),de},o.prototype.readInt8=function(h,_){return h=h>>>0,_||$(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,_){h=h>>>0,_||$(h,2,this.length);let I=this[h]|this[h+1]<<8;return I&32768?I|4294901760:I},o.prototype.readInt16BE=function(h,_){h=h>>>0,_||$(h,2,this.length);let I=this[h+1]|this[h]<<8;return I&32768?I|4294901760:I},o.prototype.readInt32LE=function(h,_){return h=h>>>0,_||$(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,_){return h=h>>>0,_||$(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],I=this[h+7];(_===void 0||I===void 0)&&ge(h,this.length-8);let F=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(I<<24);return(BigInt(F)<<BigInt(32))+BigInt(_+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),o.prototype.readBigInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],I=this[h+7];(_===void 0||I===void 0)&&ge(h,this.length-8);let F=(_<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(F)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+I)}),o.prototype.readFloatLE=function(h,_){return h=h>>>0,_||$(h,4,this.length),e.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,_){return h=h>>>0,_||$(h,4,this.length),e.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||$(h,8,this.length),e.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||$(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,_,I,F,X,de){if(!o.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<de)throw new RangeError('"value" argument is out of bounds');if(I+F>h.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,_,I,F){if(h=+h,_=_>>>0,I=I>>>0,!F){let _e=Math.pow(2,8*I)-1;Z(this,h,_,I,_e,0)}let X=1,de=0;for(this[_]=h&255;++de<I&&(X*=256);)this[_+de]=h/X&255;return _+I},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,_,I,F){if(h=+h,_=_>>>0,I=I>>>0,!F){let _e=Math.pow(2,8*I)-1;Z(this,h,_,I,_e,0)}let X=I-1,de=1;for(this[_+X]=h&255;--X>=0&&(de*=256);)this[_+X]=h/de&255;return _+I},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,1,255,0),this[_]=h&255,_+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,2,65535,0),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,2,65535,0),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,4,4294967295,0),this[_+3]=h>>>24,this[_+2]=h>>>16,this[_+1]=h>>>8,this[_]=h&255,_+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,4,4294967295,0),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4};function M(h,_,I,F,X){G(_,F,X,h,I,7);let de=Number(_&BigInt(4294967295));h[I++]=de,de=de>>8,h[I++]=de,de=de>>8,h[I++]=de,de=de>>8,h[I++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[I++]=_e,_e=_e>>8,h[I++]=_e,_e=_e>>8,h[I++]=_e,_e=_e>>8,h[I++]=_e,I}function Q(h,_,I,F,X){G(_,F,X,h,I,7);let de=Number(_&BigInt(4294967295));h[I+7]=de,de=de>>8,h[I+6]=de,de=de>>8,h[I+5]=de,de=de>>8,h[I+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[I+3]=_e,_e=_e>>8,h[I+2]=_e,_e=_e>>8,h[I+1]=_e,_e=_e>>8,h[I]=_e,I+8}o.prototype.writeBigUInt64LE=ae(function(h,_=0){return M(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=ae(function(h,_=0){return Q(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,_,I,F){if(h=+h,_=_>>>0,!F){let V=Math.pow(2,8*I-1);Z(this,h,_,I,V-1,-V)}let X=0,de=1,_e=0;for(this[_]=h&255;++X<I&&(de*=256);)h<0&&_e===0&&this[_+X-1]!==0&&(_e=1),this[_+X]=(h/de>>0)-_e&255;return _+I},o.prototype.writeIntBE=function(h,_,I,F){if(h=+h,_=_>>>0,!F){let V=Math.pow(2,8*I-1);Z(this,h,_,I,V-1,-V)}let X=I-1,de=1,_e=0;for(this[_+X]=h&255;--X>=0&&(de*=256);)h<0&&_e===0&&this[_+X+1]!==0&&(_e=1),this[_+X]=(h/de>>0)-_e&255;return _+I},o.prototype.writeInt8=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,1,127,-128),h<0&&(h=255+h+1),this[_]=h&255,_+1},o.prototype.writeInt16LE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,2,32767,-32768),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeInt16BE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,2,32767,-32768),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeInt32LE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,4,2147483647,-2147483648),this[_]=h&255,this[_+1]=h>>>8,this[_+2]=h>>>16,this[_+3]=h>>>24,_+4},o.prototype.writeInt32BE=function(h,_,I){return h=+h,_=_>>>0,I||Z(this,h,_,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4},o.prototype.writeBigInt64LE=ae(function(h,_=0){return M(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=ae(function(h,_=0){return Q(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ye(h,_,I,F,X,de){if(I+F>h.length)throw new RangeError("Index out of range");if(I<0)throw new RangeError("Index out of range")}function te(h,_,I,F,X){return _=+_,I=I>>>0,X||ye(h,_,I,4),e.write(h,_,I,F,23,4),I+4}o.prototype.writeFloatLE=function(h,_,I){return te(this,h,_,!0,I)},o.prototype.writeFloatBE=function(h,_,I){return te(this,h,_,!1,I)};function we(h,_,I,F,X){return _=+_,I=I>>>0,X||ye(h,_,I,8),e.write(h,_,I,F,52,8),I+8}o.prototype.writeDoubleLE=function(h,_,I){return we(this,h,_,!0,I)},o.prototype.writeDoubleBE=function(h,_,I){return we(this,h,_,!1,I)},o.prototype.copy=function(h,_,I,F){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(I||(I=0),!F&&F!==0&&(F=this.length),_>=h.length&&(_=h.length),_||(_=0),F>0&&F<I&&(F=I),F===I||h.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(I<0||I>=this.length)throw new RangeError("Index out of range");if(F<0)throw new RangeError("sourceEnd out of bounds");F>this.length&&(F=this.length),h.length-_<F-I&&(F=h.length-_+I);let X=F-I;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,I,F):Uint8Array.prototype.set.call(h,this.subarray(I,F),_),X},o.prototype.fill=function(h,_,I,F){if(typeof h=="string"){if(typeof _=="string"?(F=_,_=0,I=this.length):typeof I=="string"&&(F=I,I=this.length),F!==void 0&&typeof F!="string")throw new TypeError("encoding must be a string");if(typeof F=="string"&&!o.isEncoding(F))throw new TypeError("Unknown encoding: "+F);if(h.length===1){let de=h.charCodeAt(0);(F==="utf8"&&de<128||F==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(_<0||this.length<_||this.length<I)throw new RangeError("Out of range index");if(I<=_)return this;_=_>>>0,I=I===void 0?this.length:I>>>0,h||(h=0);let X;if(typeof h=="number")for(X=_;X<I;++X)this[X]=h;else{let de=o.isBuffer(h)?h:o.from(h,F),_e=de.length;if(_e===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<I-_;++X)this[X+_]=de[X%_e]}return this};let K={};function N(h,_,I){K[h]=class extends I{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(F){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:F,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(h,_){return`The "${h}" argument must be of type number. Received type ${typeof _}`},TypeError),N("ERR_OUT_OF_RANGE",function(h,_,I){let F=`The value of "${h}" is out of range.`,X=I;return Number.isInteger(I)&&Math.abs(I)>4294967296?X=ne(String(I)):typeof I=="bigint"&&(X=String(I),(I>BigInt(2)**BigInt(32)||I<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),F+=` It must be ${_}. Received ${X}`,F},RangeError);function ne(h){let _="",I=h.length,F=h[0]==="-"?1:0;for(;I>=F+4;I-=3)_=`_${h.slice(I-3,I)}${_}`;return`${h.slice(0,I)}${_}`}function z(h,_,I){J(_,"offset"),(h[_]===void 0||h[_+I]===void 0)&&ge(_,h.length-(I+1))}function G(h,_,I,F,X,de){if(h>I||h<_){let _e=typeof _=="bigint"?"n":"",V;throw _===0||_===BigInt(0)?V=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:V=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new K.ERR_OUT_OF_RANGE("value",V,h)}z(F,X,de)}function J(h,_){if(typeof h!="number")throw new K.ERR_INVALID_ARG_TYPE(_,"number",h)}function ge(h,_,I){throw Math.floor(h)!==h?(J(h,I),new K.ERR_OUT_OF_RANGE("offset","an integer",h)):_<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,h)}let se=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(se,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function q(h,_){_=_||1/0;let I,F=h.length,X=null,de=[];for(let _e=0;_e<F;++_e){if(I=h.charCodeAt(_e),I>55295&&I<57344){if(!X){if(I>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===F){(_-=3)>-1&&de.push(239,191,189);continue}X=I;continue}if(I<56320){(_-=3)>-1&&de.push(239,191,189),X=I;continue}I=(X-55296<<10|I-56320)+65536}else X&&(_-=3)>-1&&de.push(239,191,189);if(X=null,I<128){if((_-=1)<0)break;de.push(I)}else if(I<2048){if((_-=2)<0)break;de.push(I>>6|192,I&63|128)}else if(I<65536){if((_-=3)<0)break;de.push(I>>12|224,I>>6&63|128,I&63|128)}else if(I<1114112){if((_-=4)<0)break;de.push(I>>18|240,I>>12&63|128,I>>6&63|128,I&63|128)}else throw new Error("Invalid code point")}return de}function ee(h){let _=[];for(let I=0;I<h.length;++I)_.push(h.charCodeAt(I)&255);return _}function he(h,_){let I,F,X,de=[];for(let _e=0;_e<h.length&&!((_-=2)<0);++_e)I=h.charCodeAt(_e),F=I>>8,X=I%256,de.push(X),de.push(F);return de}function fe(h){return i.toByteArray(R(h))}function be(h,_,I,F){let X;for(X=0;X<F&&!(X+I>=_.length||X>=h.length);++X)_[X+I]=h[X];return X}function H(h,_){return h instanceof _||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===_.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",_=new Array(256);for(let I=0;I<16;++I){let F=I*16;for(let X=0;X<16;++X)_[F+X]=h[I]+h[X]}return _})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return vt}var qt,gi,rr,yi,vt,bi,zc=Ye(()=>{le(),ue(),ce(),qt={},gi=!1,rr={},yi=!1,vt={},bi=!1}),$e={};$t($e,{Buffer:()=>wr,INSPECT_MAX_BYTES:()=>ss,default:()=>dt,kMaxLength:()=>as});var dt,wr,ss,as,qe=Ye(()=>{le(),ue(),ce(),zc(),dt=Wc(),dt.Buffer,dt.SlowBuffer,dt.INSPECT_MAX_BYTES,dt.kMaxLength,wr=dt.Buffer,ss=dt.INSPECT_MAX_BYTES,as=dt.kMaxLength}),ue=Ye(()=>{qe()}),Be=pe((i,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}}),ls=pe((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,n]){let o=r.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.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"{}"}}}}),Ke=pe((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=ls(),{AggregateError:s}=Be(),n=globalThis.AggregateError||s,o=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function p(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function y(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function f(m,k,x){x||(x=Error);class v extends x{constructor(...S){super(y(m,k,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[o]=!0,u[m]=v}function g(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function b(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],A=[];for(let O of k)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?E.push(O.toLowerCase()):l.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),A.push(O));if(S.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,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 O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(S.length>0||A.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}A.length>0&&(v+=" or ")}switch(A.length){case 0:break;case 1:A[0].toLowerCase()!==A[0]&&(v+="an "),v+=`${A[0]}`;break;case 2:v+=`one of ${A[0]} or ${A[1]}`;break;default:{let O=A.pop();v+=`one of ${A.join(", ")}, or ${O}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var C;if((C=x.constructor)!==null&&C!==void 0&&C.name)v+=`. Received an instance of ${x.constructor.name}`;else{let O=r(x,{depth:-1});v+=`. Received ${O}`}}else{let O=r(x,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof x} (${O})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);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,k,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 "${k}" function but got ${E}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'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 ${k}. 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:w,aggregateTwoErrors:g(b),hideStackFrames:g,codes:u}}),nr=pe((i,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}),wt={};$t(wt,{EventEmitter:()=>cs,default:()=>Ht,defaultMaxListeners:()=>us,init:()=>ds,listenerCount:()=>hs,on:()=>fs,once:()=>ps});function Vc(){if(vi)return ir;vi=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(x,v,E){return Function.prototype.apply.call(x,v,E)},t;i&&typeof i.ownKeys=="function"?t=i.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)}ir=n,ir.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(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 o},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+".");o=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 l(x){return x._maxListeners===void 0?n.defaultMaxListeners:x._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(x){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=x==="error",A=this._events;if(A!==void 0)S=S&&A.error===void 0;else if(!S)return!1;if(S){var C;if(v.length>0&&(C=v[0]),C instanceof Error)throw C;var O=new Error("Unhandled error."+(C?" ("+C.message+")":""));throw O.context=C,O}var j=A[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,B=f(j,T),E=0;E<T;++E)e(B[E],this,v);return!0};function c(x,v,E,S){var A,C,O;if(a(E),C=x._events,C===void 0?(C=x._events=Object.create(null),x._eventsCount=0):(C.newListener!==void 0&&(x.emit("newListener",v,E.listener?E.listener:E),C=x._events),O=C[v]),O===void 0)O=C[v]=E,++x._eventsCount;else if(typeof O=="function"?O=C[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),A=l(x),A>0&&O.length>A&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=x,j.type=v,j.count=O.length,r(j)}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 d(x,v,E){var S={fired:!1,wrapFn:void 0,target:x,type:v,listener:E},A=u.bind(S);return A.listener=E,S.wrapFn=A,A}n.prototype.once=function(x,v){return a(v),this.on(x,d(this,x,v)),this},n.prototype.prependOnceListener=function(x,v){return a(v),this.prependListener(x,d(this,x,v)),this},n.prototype.removeListener=function(x,v){var E,S,A,C,O;if(a(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(A=-1,C=E.length-1;C>=0;C--)if(E[C]===v||E[C].listener===v){O=E[C].listener,A=C;break}if(A<0)return this;A===0?E.shift():g(E,A),E.length===1&&(S[x]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",x,O||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 A=Object.keys(E),C;for(S=0;S<A.length;++S)C=A[S],C!=="removeListener"&&this.removeAllListeners(C);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 A=S[v];return A===void 0?[]:typeof A=="function"?E?[A.listener||A]:[A]:E?b(A):f(A,A.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 w(x,v){return new Promise(function(E,S){function A(O){x.removeListener(v,C),S(O)}function C(){typeof x.removeListener=="function"&&x.removeListener("error",A),E([].slice.call(arguments))}k(x,v,C,{once:!0}),v!=="error"&&m(x,A,{once:!0})})}function m(x,v,E){typeof x.on=="function"&&k(x,"error",v,E)}function k(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 A(C){S.once&&x.removeEventListener(v,A),E(C)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return ir}var ir,vi,Ht,cs,us,ds,hs,fs,ps,Ot=Ye(()=>{le(),ue(),ce(),ir={},vi=!1,Ht=Vc(),Ht.once,Ht.once=function(i,e){return new Promise((t,r)=>{function s(...o){n!==void 0&&i.removeListener("error",n),t(o)}let n;e!=="error"&&(n=o=>{i.removeListener(name,s),r(o)},i.once("error",n)),i.once(e,s)})},Ht.on=function(i,e){let t=[],r=[],s=null,n=!1,o={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,d)=>r.push({resolve:u,reject:d}))},async return(){i.removeListener(e,a),i.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),o;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):s=c,o.return()}},{EventEmitter:cs,defaultMaxListeners:us,init:ds,listenerCount:hs,on:fs,once:ps}=Ht}),Je=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),{format:r,inspect:s}=ls(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:o,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||nr().AbortSignal,u=globalThis.AbortController||nr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,y=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,w)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(w,"AbortSignal",b)},g=(b,w)=>{if(typeof b!="function")throw new n(w,"Function",b)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(b){let w=!1;return function(...m){w||(w=!0,b.apply(this,m))}},createDeferredPromise:function(){let b,w;return{promise:new Promise((m,k)=>{b=m,w=k}),resolve:b,reject:w}},promisify(b){return new Promise((w,m)=>{b((k,...x)=>k?m(k):w(...x))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:y,deprecate(b,w){return b},addAbortListener:(Ot(),Ne(wt)).addAbortListener||function(b,w){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),g(w,"listener");let m;return b.aborted?queueMicrotask(()=>w()):(b.addEventListener("abort",w,{__proto__:null,once:!0,[o]:!0}),m=()=>{b.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(b){if(b.length===1)return b[0];let w=new u,m=()=>w.abort();return b.forEach(k=>{f(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{b.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),or=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:o,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:y,StringPrototypeToUpperCase:f,StringPrototypeTrim:g}=Be(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:E}=Je(),{isAsyncFunction:S,isArrayBufferView:A}=Je().types,C={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,B="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 k(me,H,B);H=u(H,8)}return Y(H,me),H}var U=b((H,me,ve=c,ae=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>ae)throw new x(me,`>= ${ve} && <= ${ae}`,H)}),oe=b((H,me,ve=-2147483648,ae=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);if(H<ve||H>ae)throw new x(me,`>= ${ve} && <= ${ae}`,H)}),Y=b((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new x(me,"an integer",H);let ae=ve?1:0,Oe=4294967295;if(H<ae||H>Oe)throw new x(me,`>= ${ae} && <= ${Oe}`,H)});function W(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,ae){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||ae!=null&&H>ae||(ve!=null||ae!=null)&&a(H))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,H)}var $=b((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+s(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:y(Oe)),", ");throw new k(me,H,ae)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!d(H,me)?ve:H[me]}var Q=b((H,me,ve=null)=>{let ae=M(ve,"allowArray",!1),Oe=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Oe||typeof H!="function"))throw new m(me,"Object",H)}),ye=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 ae=`must be longer than ${ve}`;throw new k(me,H,ae)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)W(H[ve],`${me}[${ve}]`)}function K(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)Z(H[ve],`${me}[${ve}]`)}function N(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let ae=H[ve],Oe=`${me}[${ve}]`;if(ae==null)throw new m(Oe,"AbortSignal",ae);ge(ae,Oe)}}function ne(H,me="signal"){if(W(H,me),C[H]===void 0)throw C[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var z=b((H,me="buffer")=>{if(!A(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function G(H,me){let ve=E(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new k("encoding",me,`is invalid for data of length ${ae}`)}function J(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 w(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)}),se=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)}),q=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 he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function be(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 ae=0;ae<me;ae++){let Oe=H[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:j,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:K,validateAbortSignalArray:N,validateBoolean:Z,validateBuffer:z,validateDictionary:ye,validateEncoding:G,validateFunction:se,validateInt32:oe,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:$,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:W,validateUint32:Y,validateUndefined:q,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:be}}),Mt=pe((i,e)=>{le(),ue(),ce();var t=e.exports={},r,s;function n(){throw new Error("setTimeout has not been defined")}function o(){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=o}catch{s=o}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(s===clearTimeout)return clearTimeout(w);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(w);try{return s(w)}catch{try{return s.call(null,w)}catch{return s.call(this,w)}}}var c=[],u=!1,d,p=-1;function y(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=a(y);u=!0;for(var m=c.length;m;){for(d=c,c=[];++p<m;)d&&d[p].run();p=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new g(w,m)),c.length===1&&!u&&a(f)};function g(w,m){this.fun=w,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(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),ht=pe((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=Be(),n=s("nodejs.stream.destroyed"),o=s("nodejs.stream.errored"),a=s("nodejs.stream.readable"),l=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),d=s("nodejs.webstream.controllerErrorFunction");function p(M,Q=!1){var ye;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((ye=M._readableState)===null||ye===void 0?void 0:ye.readable)!==!1)&&(!M._writableState||M._readableState))}function y(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.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 w(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 k(M){return b(M)||w(M)||m(M)}function x(M,Q){return M==null?!1:Q===!0?typeof M[t]=="function":Q===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!g(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function E(M){if(!y(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function S(M,Q){if(!y(M))return null;if(M.writableFinished===!0)return!0;let ye=M._writableState;return ye!=null&&ye.errored?!1:typeof ye?.finished!="boolean"?null:!!(ye.finished||Q===!1&&ye.ended===!0&&ye.length===0)}function A(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let Q=M._readableState;return!Q||Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function C(M,Q){if(!p(M))return null;let ye=M._readableState;return ye!=null&&ye.errored?!1:typeof ye?.endEmitted!="boolean"?null:!!(ye.endEmitted||Q===!1&&ye.ended===!0&&ye.length===0)}function O(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!C(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:y(M)&&M.writable&&!E(M)}function T(M,Q){return g(M)?v(M)?!0:!(Q?.readable!==!1&&O(M)||Q?.writable!==!1&&j(M)):null}function B(M){var Q,ye;return g(M)?M.writableErrored?M.writableErrored:(Q=(ye=M._writableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,ye;return g(M)?M.readableErrored?M.readableErrored:(Q=(ye=M._readableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!g(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,ye=M._readableState;return typeof Q?.closed=="boolean"||typeof ye?.closed=="boolean"?Q?.closed||ye?.closed:typeof M._closed=="boolean"&&oe(M)?M._closed:null}function oe(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"&&oe(M)}function W(M){var Q;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((Q=M.req)===null||Q===void 0?void 0:Q.upgradeOrConnect)===void 0}function re(M){if(!g(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!te&&Y(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function $(M){var Q;return!!(M&&((Q=M[c])!==null&&Q!==void 0?Q:M.readableDidRead||M.readableAborted))}function Z(M){var Q,ye,te,we,K,N,ne,z,G,J;return!!(M&&((Q=(ye=(te=(we=(K=(N=M[o])!==null&&N!==void 0?N:M.readableErrored)!==null&&K!==void 0?K:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&te!==void 0?te:(z=M._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&ye!==void 0?ye:(G=M._readableState)===null||G===void 0?void 0:G.errored)!==null&&Q!==void 0?Q:!((J=M._writableState)===null||J===void 0)&&J.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:$,kIsDisturbed:c,isErrored:Z,kIsErrored:o,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:A,isReadableFinished:C,isReadableErrored:D,isNodeStream:g,isWebStream:k,isWritable:j,isWritableNodeStream:y,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:B,isServerRequest:W,isServerResponse:Y,willEmitClose:re,isTransformStream:m}}),kt=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{AbortError:r,codes:s}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:o}=s,{kEmptyObject:a,once:l}=Je(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=or(),{Promise:y,PromisePrototypeThen:f,SymbolDispose:g}=Be(),{isClosed:b,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:A,isWritableFinished:C,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:B}=ht(),D;function U($){return $.setHeader&&typeof $.abort=="function"}var oe=()=>{};function Y($,Z,M){var Q,ye;if(arguments.length===2?(M=Z,Z=a):Z==null?Z=a:d(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),k($)||A($))return W($,Z,M);if(!j($))throw new n("stream",["ReadableStream","WritableStream","Stream"],$);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m($),we=(ye=Z.writable)!==null&&ye!==void 0?ye:S($),K=$._writableState,N=$._readableState,ne=()=>{$.writable||J()},z=T($)&&m($)===te&&S($)===we,G=C($,!1),J=()=>{G=!0,$.destroyed&&(z=!1),!(z&&(!$.readable||te))&&(!te||ge)&&M.call($)},ge=x($,!1),se=()=>{ge=!0,$.destroyed&&(z=!1),!(z&&(!$.writable||we))&&(!we||G)&&M.call($)},R=H=>{M.call($,H)},q=b($),ee=()=>{q=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);if(te&&!ge&&m($,!0)&&!x($,!1))return M.call($,new o);if(we&&!G&&!C($,!1))return M.call($,new o);M.call($)},he=()=>{q=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);M.call($)},fe=()=>{$.req.on("finish",J)};U($)?($.on("complete",J),z||$.on("abort",ee),$.req?fe():$.on("request",fe)):we&&!K&&($.on("end",ne),$.on("close",ne)),!z&&typeof $.aborted=="boolean"&&$.on("aborted",ee),$.on("end",se),$.on("finish",J),Z.error!==!1&&$.on("error",R),$.on("close",ee),q?t.nextTick(ee):K!=null&&K.errorEmitted||N!=null&&N.errorEmitted?z||t.nextTick(he):(!te&&(!z||w($))&&(G||E($)===!1)||!we&&(!z||E($))&&(ge||w($)===!1)||N&&$.req&&$.aborted)&&t.nextTick(he);let be=()=>{M=oe,$.removeListener("aborted",ee),$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",fe),$.req&&$.req.removeListener("finish",J),$.removeListener("end",ne),$.removeListener("close",ne),$.removeListener("finish",J),$.removeListener("end",se),$.removeListener("error",R),$.removeListener("close",ee)};if(Z.signal&&!q){let H=()=>{let me=M;be(),me.call($,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Je().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...ae)=>{me[g](),ve.apply($,ae)})}}return be}function W($,Z,M){let Q=!1,ye=oe;if(Z.signal)if(ye=()=>{Q=!0,M.call($,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(ye);else{D=D||Je().addAbortListener;let we=D(Z.signal,ye),K=M;M=l((...N)=>{we[g](),K.apply($,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply($,we))};return f($[B].promise,te,te),oe}function re($,Z){var M;let Q=!1;return Z===null&&(Z=a),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new y((ye,te)=>{let we=Y($,Z,K=>{Q&&we(),K?te(K):ye()})})}e.exports=Y,e.exports.finished=re}),Wt=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=Ke(),{Symbol:o}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=ht(),d=o("kDestroy"),p=o("kConstruct");function y(T,B,D){T&&(T.stack,B&&!B.errored&&(B.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,B){let D=this._readableState,U=this._writableState,oe=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof B=="function"&&B(),this):(y(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),oe.constructed?g(this,T,B):this.once(d,function(Y){g(this,r(Y,T),B)}),this)}function g(T,B,D){let U=!1;function oe(Y){if(U)return;U=!0;let W=T._readableState,re=T._writableState;y(Y,re,W),re&&(re.closed=!0),W&&(W.closed=!0),typeof D=="function"&&D(Y),Y?t.nextTick(b,T,Y):t.nextTick(w,T)}try{T._destroy(B||null,oe)}catch(Y){oe(Y)}}function b(T,B){m(T,B),w(T)}function w(T){let B=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),B&&(B.closeEmitted=!0),(D!=null&&D.emitClose||B!=null&&B.emitClose)&&T.emit("close")}function m(T,B){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",B))}function k(){let T=this._readableState,B=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),B&&(B.constructed=!0,B.destroyed=!1,B.closed=!1,B.closeEmitted=!1,B.errored=null,B.errorEmitted=!1,B.finalCalled=!1,B.prefinished=!1,B.ended=B.writable===!1,B.ending=B.writable===!1,B.finished=B.writable===!1)}function x(T,B,D){let U=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy(B):B&&(B.stack,oe&&!oe.errored&&(oe.errored=B),U&&!U.errored&&(U.errored=B),D?t.nextTick(m,T,B):m(T,B))}function v(T,B){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(p,B),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let B=!1;function D(U){if(B){x(T,U??new s);return}B=!0;let oe=T._readableState,Y=T._writableState,W=Y||oe;oe&&(oe.constructed=!0),Y&&(Y.constructed=!0),W.destroyed?T.emit(d,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 A(T){return T?.setHeader&&typeof T.abort=="function"}function C(T){T.emit("close")}function O(T,B){T.emit("error",B),t.nextTick(C,T)}function j(T,B){!T||l(T)||(!B&&!c(T)&&(B=new n),u(T)?(T.socket=null,T.destroy(B)):A(T)?T.abort():A(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(B):typeof T.close=="function"?T.close():B?t.nextTick(O,T,B):t.nextTick(C,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:f,undestroy:k,errorOrDestroy:x}}),wi=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:s}=(Ot(),Ne(wt));function n(a){s.call(this,a)}r(n.prototype,s.prototype),r(n,s),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",y),c.on("close",f));let p=!1;function y(){p||(p=!0,a.end())}function f(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function g(w){b(),s.listenerCount(this,"error")===0&&this.emit("error",w)}o(c,"error",g),o(a,"error",g);function b(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",y),c.removeListener("close",f),c.removeListener("error",g),a.removeListener("error",g),c.removeListener("end",b),c.removeListener("close",b),a.removeListener("close",b)}return c.on("end",b),c.on("close",b),a.on("close",b),a.emit("pipe",c),a};function o(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:o}}),kr=pe((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:s}=Ke(),{isNodeStream:n,isWebStream:o,kControllerErrorFunction:a}=ht(),l=kt(),{ERR_INVALID_ARG_TYPE:c}=s,u,d=(p,y)=>{if(typeof p!="object"||!("aborted"in p))throw new c(y,"AbortSignal",p)};e.exports.addAbortSignal=function(p,y){if(d(p,"signal"),!n(y)&&!o(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[a](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Je().addAbortListener;let g=u(p,f);l(y,g[t])}return y}}),Kc=pe((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=Be(),{Buffer:o}=(qe(),Ne($e)),{inspect:a}=Je();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return o.alloc(0);let c=o.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)s(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=o.allocUnsafe(l),u=l,d=this.head,p=0;do{let y=d.data;if(l>y.length)s(c,y,u-l),l-=y.length;else{l===y.length?(s(c,y,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(s(c,new n(y.buffer,y.byteOffset,l),u-l),this.head=d,d.data=y.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),_r=pe((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:s}=or(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,o=16*1024,a=16;function l(p,y,f){return p.highWaterMark!=null?p.highWaterMark:y?p[f]:null}function c(p){return p?a:o}function u(p,y){s(y,"value",0),p?a=y:o=y}function d(p,y,f,g){let b=l(y,g,f);if(b!=null){if(!r(b)||b<0){let w=g?`options.${f}`:"options.highWaterMark";throw new n(w,b)}return t(b)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Gc=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),r=t.Buffer;function s(o,a){for(var l in o)a[l]=o[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,i),i.Buffer=n);function n(o,a,l){return r(o,a,l)}n.prototype=Object.create(r.prototype),s(r,n),n.from=function(o,a,l){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,a,l)},n.alloc=function(o,a,l){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},n.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}}),Yc=pe(i=>{le(),ue(),ce();var e=Gc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)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(k)return;m=(""+m).toLowerCase(),k=!0}}function s(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=s(m);var k;switch(this.encoding){case"utf16le":this.text=p,this.end=y,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=f,this.end=g,k=3;break;default:this.write=b,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function o(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,x){var v=k.length-1;if(v<x)return 0;var E=o(k[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<x||E===-2?0:(E=o(k[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<x||E===-2?0:(E=o(k[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function p(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);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",k,m.length-1)}function y(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function f(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(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",k,m.length-x))}function g(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function b(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),ms=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=Be(),{Buffer:o}=(qe(),Ne($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,p){let y;if(typeof d=="string"||d instanceof o)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[s])f=!0,y=d[s]();else if(d&&d[n])f=!1,y=d[n]();else throw new a("iterable",["Iterable"],d);let g=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;g._read=function(){b||(b=!0,m())},g._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof y.throw=="function";if(x&&v){let{value:E,done:S}=await y.throw(k);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:k,done:x}=f?await y.next():y.next();if(x)g.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw b=!1,new l;if(g.push(v))continue;b=!1}}catch(k){g.destroy(k)}break}}return g}e.exports=c}),xr=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:o,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:y,Symbol:f}=Be();e.exports=ae,ae.ReadableState=ve;var{EventEmitter:g}=(Ot(),Ne(wt)),{Stream:b,prependListener:w}=wi(),{Buffer:m}=(qe(),Ne($e)),{addAbortSignal:k}=kr(),x=kt(),v=Je().debuglog("stream",P=>{v=P}),E=Kc(),S=Wt(),{getHighWaterMark:A,getDefaultHighWaterMark:C}=_r(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:B,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:oe}=Ke(),{validateObject:Y}=or(),W=f("kPaused"),{StringDecoder:re}=Yc(),$=ms();c(ae.prototype,b.prototype),c(ae,b);var Z=()=>{},{errorOrDestroy:M}=S,Q=1,ye=2,te=4,we=8,K=16,N=32,ne=64,z=128,G=256,J=512,ge=1024,se=2048,R=4096,q=8192,ee=16384,he=32768,fe=65536,be=1<<17,H=1<<18;function me(P){return{enumerable:!1,get(){return(this.state&P)!==0},set(L){L?this.state|=P:this.state&=~P}}}a(ve.prototype,{objectMode:me(Q),ended:me(ye),endEmitted:me(te),reading:me(we),constructed:me(K),sync:me(N),needReadable:me(ne),emittedReadable:me(z),readableListening:me(G),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(se),autoDestroy:me(R),destroyed:me(q),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(be),dataEmitted:me(H)});function ve(P,L,ke){typeof ke!="boolean"&&(ke=L instanceof ft()),this.state=se|R|K|N,P&&P.objectMode&&(this.state|=Q),ke&&P&&P.readableObjectMode&&(this.state|=Q),this.highWaterMark=P?A(this,P,"readableHighWaterMark",ke):C(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,P&&P.emitClose===!1&&(this.state&=~se),P&&P.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=P&&P.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,P&&P.encoding&&(this.decoder=new re(P.encoding),this.encoding=P.encoding)}function ae(P){if(!(this instanceof ae))return new ae(P);let L=this instanceof ft();this._readableState=new ve(P,this,L),P&&(typeof P.read=="function"&&(this._read=P.read),typeof P.destroy=="function"&&(this._destroy=P.destroy),typeof P.construct=="function"&&(this._construct=P.construct),P.signal&&!L&&k(P.signal,this)),b.call(this,P),S.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}ae.prototype.destroy=S.destroy,ae.prototype._undestroy=S.undestroy,ae.prototype._destroy=function(P,L){L(P)},ae.prototype[g.captureRejectionSymbol]=function(P){this.destroy(P)},ae.prototype[p]=function(){let P;return this.destroyed||(P=this.readableEnded?null:new oe,this.destroy(P)),new u((L,ke)=>x(this,xe=>xe&&xe!==P?ke(xe):L(null)))},ae.prototype.push=function(P,L){return Oe(this,P,L,!1)},ae.prototype.unshift=function(P,L){return Oe(this,P,L,!0)};function Oe(P,L,ke,xe){v("readableAddChunk",L);let Ee=P._readableState,Fe;if((Ee.state&Q)===0&&(typeof L=="string"?(ke=ke||Ee.defaultEncoding,Ee.encoding!==ke&&(xe&&Ee.encoding?L=m.from(L,ke).toString(Ee.encoding):(L=m.from(L,ke),ke=""))):L instanceof m?ke="":b._isUint8Array(L)?(L=b._uint8ArrayToBuffer(L),ke=""):L!=null&&(Fe=new j("chunk",["string","Buffer","Uint8Array"],L))),Fe)M(P,Fe);else if(L===null)Ee.state&=~we,X(P,Ee);else if((Ee.state&Q)!==0||L&&L.length>0)if(xe)if((Ee.state&te)!==0)M(P,new U);else{if(Ee.destroyed||Ee.errored)return!1;h(P,Ee,L,!0)}else if(Ee.ended)M(P,new D);else{if(Ee.destroyed||Ee.errored)return!1;Ee.state&=~we,Ee.decoder&&!ke?(L=Ee.decoder.write(L),Ee.objectMode||L.length!==0?h(P,Ee,L,!1):V(P,Ee)):h(P,Ee,L,!1)}else xe||(Ee.state&=~we,V(P,Ee));return!Ee.ended&&(Ee.length<Ee.highWaterMark||Ee.length===0)}function h(P,L,ke,xe){L.flowing&&L.length===0&&!L.sync&&P.listenerCount("data")>0?((L.state&fe)!==0?L.awaitDrainWriters.clear():L.awaitDrainWriters=null,L.dataEmitted=!0,P.emit("data",ke)):(L.length+=L.objectMode?1:ke.length,xe?L.buffer.unshift(ke):L.buffer.push(ke),(L.state&ne)!==0&&de(P)),V(P,L)}ae.prototype.isPaused=function(){let P=this._readableState;return P[W]===!0||P.flowing===!1},ae.prototype.setEncoding=function(P){let L=new re(P);this._readableState.decoder=L,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,xe="";for(let Ee of ke)xe+=L.write(Ee);return ke.clear(),xe!==""&&ke.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function I(P){if(P>_)throw new B("size","<= 1GiB",P);return P--,P|=P>>>1,P|=P>>>2,P|=P>>>4,P|=P>>>8,P|=P>>>16,P++,P}function F(P,L){return P<=0||L.length===0&&L.ended?0:(L.state&Q)!==0?1:n(P)?L.flowing&&L.length?L.buffer.first().length:L.length:P<=L.length?P:L.ended?L.length:0}ae.prototype.read=function(P){v("read",P),P===void 0?P=NaN:s(P)||(P=o(P,10));let L=this._readableState,ke=P;if(P>L.highWaterMark&&(L.highWaterMark=I(P)),P!==0&&(L.state&=~z),P===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?st(this):de(this),null;if(P=F(P,L),P===0&&L.ended)return L.length===0&&st(this),null;let xe=(L.state&ne)!==0;if(v("need readable",xe),(L.length===0||L.length-P<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|N,L.length===0&&(L.state|=ne);try{this._read(L.highWaterMark)}catch(Fe){M(this,Fe)}L.state&=~N,L.reading||(P=F(ke,L))}let Ee;return P>0?Ee=Xt(P,L):Ee=null,Ee===null?(L.needReadable=L.length<=L.highWaterMark,P=0):(L.length-=P,L.multiAwaitDrain?L.awaitDrainWriters.clear():L.awaitDrainWriters=null),L.length===0&&(L.ended||(L.needReadable=!0),ke!==P&&L.ended&&st(this)),Ee!==null&&!L.errorEmitted&&!L.closeEmitted&&(L.dataEmitted=!0,this.emit("data",Ee)),Ee};function X(P,L){if(v("onEofChunk"),!L.ended){if(L.decoder){let ke=L.decoder.end();ke&&ke.length&&(L.buffer.push(ke),L.length+=L.objectMode?1:ke.length)}L.ended=!0,L.sync?de(P):(L.needReadable=!1,L.emittedReadable=!0,_e(P))}}function de(P){let L=P._readableState;v("emitReadable",L.needReadable,L.emittedReadable),L.needReadable=!1,L.emittedReadable||(v("emitReadable",L.flowing),L.emittedReadable=!0,t.nextTick(_e,P))}function _e(P){let L=P._readableState;v("emitReadable_",L.destroyed,L.length,L.ended),!L.destroyed&&!L.errored&&(L.length||L.ended)&&(P.emit("readable"),L.emittedReadable=!1),L.needReadable=!L.flowing&&!L.ended&&L.length<=L.highWaterMark,it(P)}function V(P,L){!L.readingMore&&L.constructed&&(L.readingMore=!0,t.nextTick(ie,P,L))}function ie(P,L){for(;!L.reading&&!L.ended&&(L.length<L.highWaterMark||L.flowing&&L.length===0);){let ke=L.length;if(v("maybeReadMore read 0"),P.read(0),ke===L.length)break}L.readingMore=!1}ae.prototype._read=function(P){throw new T("_read()")},ae.prototype.pipe=function(P,L){let ke=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(P),v("pipe count=%d opts=%j",xe.pipes.length,L);let Ee=(!L||L.end!==!1)&&P!==t.stdout&&P!==t.stderr?Ge:Ft;xe.endEmitted?t.nextTick(Ee):ke.once("end",Ee),P.on("unpipe",Fe);function Fe(lt,bt){v("onunpipe"),lt===ke&&bt&&bt.hasUnpiped===!1&&(bt.hasUnpiped=!0,fr())}function Ge(){v("onend"),P.end()}let et,hr=!1;function fr(){v("cleanup"),P.removeListener("close",at),P.removeListener("finish",Tt),et&&P.removeListener("drain",et),P.removeListener("error",Dt),P.removeListener("unpipe",Fe),ke.removeListener("end",Ge),ke.removeListener("end",Ft),ke.removeListener("data",on),hr=!0,et&&xe.awaitDrainWriters&&(!P._writableState||P._writableState.needDrain)&&et()}function pr(){hr||(xe.pipes.length===1&&xe.pipes[0]===P?(v("false write response, pause",0),xe.awaitDrainWriters=P,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(P)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(P)),ke.pause()),et||(et=Ae(ke,P),P.on("drain",et))}ke.on("data",on);function on(lt){v("ondata");let bt=P.write(lt);v("dest.write",bt),bt===!1&&pr()}function Dt(lt){if(v("onerror",lt),Ft(),P.removeListener("error",Dt),P.listenerCount("error")===0){let bt=P._writableState||P._readableState;bt&&!bt.errorEmitted?M(P,lt):P.emit("error",lt)}}w(P,"error",Dt);function at(){P.removeListener("finish",Tt),Ft()}P.once("close",at);function Tt(){v("onfinish"),P.removeListener("close",at),Ft()}P.once("finish",Tt);function Ft(){v("unpipe"),ke.unpipe(P)}return P.emit("pipe",ke),P.writableNeedDrain===!0?pr():xe.flowing||(v("pipe resume"),ke.resume()),P};function Ae(P,L){return function(){let ke=P._readableState;ke.awaitDrainWriters===L?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(L)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&P.listenerCount("data")&&P.resume()}}ae.prototype.unpipe=function(P){let L=this._readableState,ke={hasUnpiped:!1};if(L.pipes.length===0)return this;if(!P){let Ee=L.pipes;L.pipes=[],this.pause();for(let Fe=0;Fe<Ee.length;Fe++)Ee[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(L.pipes,P);return xe===-1?this:(L.pipes.splice(xe,1),L.pipes.length===0&&this.pause(),P.emit("unpipe",this,ke),this)},ae.prototype.on=function(P,L){let ke=b.prototype.on.call(this,P,L),xe=this._readableState;return P==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):P==="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?de(this):xe.reading||t.nextTick(Pe,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(P,L){let ke=b.prototype.removeListener.call(this,P,L);return P==="readable"&&t.nextTick(Ie,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(P){let L=b.prototype.removeAllListeners.apply(this,arguments);return(P==="readable"||P===void 0)&&t.nextTick(Ie,this),L};function Ie(P){let L=P._readableState;L.readableListening=P.listenerCount("readable")>0,L.resumeScheduled&&L[W]===!1?L.flowing=!0:P.listenerCount("data")>0?P.resume():L.readableListening||(L.flowing=null)}function Pe(P){v("readable nexttick read 0"),P.read(0)}ae.prototype.resume=function(){let P=this._readableState;return P.flowing||(v("resume"),P.flowing=!P.readableListening,Re(this,P)),P[W]=!1,this};function Re(P,L){L.resumeScheduled||(L.resumeScheduled=!0,t.nextTick(nt,P,L))}function nt(P,L){v("resume",L.reading),L.reading||P.read(0),L.resumeScheduled=!1,P.emit("resume"),it(P),L.flowing&&!L.reading&&P.read(0)}ae.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[W]=!0,this};function it(P){let L=P._readableState;for(v("flow",L.flowing);L.flowing&&P.read()!==null;);}ae.prototype.wrap=function(P){let L=!1;P.on("data",xe=>{!this.push(xe)&&P.pause&&(L=!0,P.pause())}),P.on("end",()=>{this.push(null)}),P.on("error",xe=>{M(this,xe)}),P.on("close",()=>{this.destroy()}),P.on("destroy",()=>{this.destroy()}),this._read=()=>{L&&P.resume&&(L=!1,P.resume())};let ke=l(P);for(let xe=1;xe<ke.length;xe++){let Ee=ke[xe];this[Ee]===void 0&&typeof P[Ee]=="function"&&(this[Ee]=P[Ee].bind(P))}return this},ae.prototype[y]=function(){return Ve(this)},ae.prototype.iterator=function(P){return P!==void 0&&Y(P,"options"),Ve(this,P)};function Ve(P,L){typeof P.read!="function"&&(P=ae.wrap(P,{objectMode:!0}));let ke=ot(P,L);return ke.stream=P,ke}async function*ot(P,L){let ke=Z;function xe(Ge){this===P?(ke(),ke=Z):ke=Ge}P.on("readable",xe);let Ee,Fe=x(P,{writable:!1},Ge=>{Ee=Ge?O(Ee,Ge):null,ke(),ke=Z});try{for(;;){let Ge=P.destroyed?null:P.read();if(Ge!==null)yield Ge;else{if(Ee)throw Ee;if(Ee===null)return;await new u(xe)}}}catch(Ge){throw Ee=O(Ee,Ge),Ee}finally{(Ee||L?.destroyOnReturn!==!1)&&(Ee===void 0||P._readableState.autoDestroy)?S.destroyer(P,null):(P.off("readable",xe),Fe())}}a(ae.prototype,{readable:{__proto__:null,get(){let P=this._readableState;return!!P&&P.readable!==!1&&!P.destroyed&&!P.errorEmitted&&!P.endEmitted},set(P){this._readableState&&(this._readableState.readable=!!P)}},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(P){this._readableState&&(this._readableState.flowing=P)}},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(P){this._readableState&&(this._readableState.destroyed=P)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[W]!==!1},set(P){this[W]=!!P}}}),ae._fromList=Xt;function Xt(P,L){if(L.length===0)return null;let ke;return L.objectMode?ke=L.buffer.shift():!P||P>=L.length?(L.decoder?ke=L.buffer.join(""):L.buffer.length===1?ke=L.buffer.first():ke=L.buffer.concat(L.length),L.buffer.clear()):ke=L.buffer.consume(P,L.decoder),ke}function st(P){let L=P._readableState;v("endReadable",L.endEmitted),L.endEmitted||(L.ended=!0,t.nextTick(Ze,L,P))}function Ze(P,L){if(v("endReadableNT",P.endEmitted,P.length),!P.errored&&!P.closeEmitted&&!P.endEmitted&&P.length===0){if(P.endEmitted=!0,L.emit("end"),L.writable&&L.allowHalfOpen===!1)t.nextTick(nn,L);else if(P.autoDestroy){let ke=L._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&L.destroy()}}}function nn(P){P.writable&&!P.writableEnded&&!P.destroyed&&P.end()}ae.from=function(P,L){return $(ae,P,L)};var Zt;function dr(){return Zt===void 0&&(Zt={}),Zt}ae.fromWeb=function(P,L){return dr().newStreamReadableFromReadableStream(P,L)},ae.toWeb=function(P,L){return dr().newReadableStreamFromStreamReadable(P,L)},ae.wrap=function(P,L){var ke,xe;return new ae({objectMode:(ke=(xe=P.readableObjectMode)!==null&&xe!==void 0?xe:P.objectMode)!==null&&ke!==void 0?ke:!0,...L,destroy(Ee,Fe){S.destroyer(P,Ee),Fe(Ee)}}).wrap(P)}}),ki=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:o,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Ot(),Ne(wt)),y=wi().Stream,{Buffer:f}=(qe(),Ne($e)),g=Wt(),{addAbortSignal:b}=kr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=_r(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:A,ERR_STREAM_NULL_VALUES:C,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=g;l(Y.prototype,y.prototype),l(Y,y);function B(){}var D=u("kOnFinished");function U(R,q,ee){typeof ee!="boolean"&&(ee=q instanceof ft()),this.objectMode=!!(R&&R.objectMode),ee&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?w(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 he=!!(R&&R.decodeStrings===!1);this.decodeStrings=!he,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,q),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,oe(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 oe(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},o(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let q=this instanceof ft();if(!q&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,q),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),z(this,ee)})}o(Y,d,{__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 W(R,q,ee,he){let fe=R._writableState;if(typeof ee=="function")he=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new j(ee);typeof he!="function"&&(he=B)}if(q===null)throw new C;if(!fe.objectMode)if(typeof q=="string")fe.decodeStrings!==!1&&(q=f.from(q,ee),ee="buffer");else if(q instanceof f)ee="buffer";else if(y._isUint8Array(q))q=y._uint8ArrayToBuffer(q),ee="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],q);let be;return fe.ending?be=new O:fe.destroyed&&(be=new S("write")),be?(t.nextTick(he,be),T(R,be,!0),be):(fe.pendingcb++,re(R,fe,q,ee,he))}Y.prototype.write=function(R,q,ee){return W(this,R,q,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 j(R);return this._writableState.defaultEncoding=R,this};function re(R,q,ee,he,fe){let be=q.objectMode?1:ee.length;q.length+=be;let H=q.length<q.highWaterMark;return H||(q.needDrain=!0),q.writing||q.corked||q.errored||!q.constructed?(q.buffered.push({chunk:ee,encoding:he,callback:fe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&fe!==B&&(q.allNoop=!1)):(q.writelen=be,q.writecb=fe,q.writing=!0,q.sync=!0,R._write(ee,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function $(R,q,ee,he,fe,be,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new S("write")):ee?R._writev(fe,q.onwrite):R._write(fe,be,q.onwrite),q.sync=!1}function Z(R,q,ee,he){--q.pendingcb,he(ee),te(q),T(R,ee)}function M(R,q){let ee=R._writableState,he=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,q?(q.stack,ee.errored||(ee.errored=q),R._readableState&&!R._readableState.errored&&(R._readableState.errored=q),he?t.nextTick(Z,R,ee,q,fe):Z(R,ee,q,fe)):(ee.buffered.length>ee.bufferedIndex&&we(R,ee),he?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:R,state:ee},t.nextTick(Q,ee.afterWriteTickInfo)):ye(R,ee,1,fe))}function Q({stream:R,state:q,count:ee,cb:he}){return q.afterWriteTickInfo=null,ye(R,q,ee,he)}function ye(R,q,ee,he){for(!q.ending&&!R.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,R.emit("drain"));ee-- >0;)q.pendingcb--,he();q.destroyed&&te(q),z(R,q)}function te(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var q;let{chunk:be,callback:H}=R.buffered[fe],me=R.objectMode?1:be.length;R.length-=me,H((q=R.errored)!==null&&q!==void 0?q:new S("write"))}let ee=R[D].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=R.errored)!==null&&he!==void 0?he:new S("end"))}oe(R)}function we(R,q){if(q.corked||q.bufferProcessing||q.destroyed||!q.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=q,be=ee.length-he;if(!be)return;let H=he;if(q.bufferProcessing=!0,be>1&&R._writev){q.pendingcb-=be-1;let me=q.allNoop?B:ae=>{for(let Oe=H;Oe<ee.length;++Oe)ee[Oe].callback(ae)},ve=q.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=q.allBuffers,$(R,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=ee[H];ee[H++]=null;let Oe=fe?1:me.length;$(R,q,!1,Oe,me,ve,ae)}while(H<ee.length&&!q.writing);H===ee.length?oe(q):H>256?(ee.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}Y.prototype._write=function(R,q,ee){if(this._writev)this._writev([{chunk:R,encoding:q}],ee);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,q,ee){let he=this._writableState;typeof R=="function"?(ee=R,R=null,q=null):typeof q=="function"&&(ee=q,q=null);let fe;if(R!=null){let be=W(this,R,q);be instanceof s&&(fe=be)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,z(this,he,!0),he.ended=!0):he.finished?fe=new A("end"):he.destroyed&&(fe=new S("end"))),typeof ee=="function"&&(fe||he.finished?t.nextTick(ee,fe):he[D].push(ee)),this};function K(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 N(R,q){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,q.pendingcb--,fe){let be=q[D].splice(0);for(let H=0;H<be.length;H++)be[H](fe);T(R,fe,q.sync)}else K(q)&&(q.prefinished=!0,R.emit("prefinish"),q.pendingcb++,t.nextTick(G,R,q))}q.sync=!0,q.pendingcb++;try{R._final(he)}catch(fe){he(fe)}q.sync=!1}function ne(R,q){!q.prefinished&&!q.finalCalled&&(typeof R._final=="function"&&!q.destroyed?(q.finalCalled=!0,N(R,q)):(q.prefinished=!0,R.emit("prefinish")))}function z(R,q,ee){K(q)&&(ne(R,q),q.pendingcb===0&&(ee?(q.pendingcb++,t.nextTick((he,fe)=>{K(fe)?G(he,fe):fe.pendingcb--},R,q)):K(q)&&(q.pendingcb++,G(R,q))))}function G(R,q){q.pendingcb--,q.finished=!0;let ee=q[D].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(R.emit("finish"),q.autoDestroy){let he=R._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&R.destroy()}}a(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 J=g.destroy;Y.prototype.destroy=function(R,q){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[D].length)&&t.nextTick(te,ee),J.call(this,R,q),this},Y.prototype._undestroy=g.undestroy,Y.prototype._destroy=function(R,q){q(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function se(){return ge===void 0&&(ge={}),ge}Y.fromWeb=function(R,q){return se().newStreamWritableFromWritableStream(R,q)},Y.toWeb=function(R){return se().newWritableStreamFromStreamWritable(R)}}),Jc=pe((i,e)=>{le(),ue(),ce();var t=Mt(),r=(qe(),Ne($e)),{isReadable:s,isWritable:n,isIterable:o,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=ht(),y=kt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:g,ERR_INVALID_RETURN_VALUE:b}}=Ke(),{destroyer:w}=Wt(),m=ft(),k=xr(),x=ki(),{createDeferredPromise:v}=Je(),E=ms(),S=globalThis.Blob||r.Blob,A=typeof S<"u"?function(D){return D instanceof S}:function(D){return!1},C=globalThis.AbortController||nr().AbortController,{FunctionPrototypeCall:O}=Be(),j=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,oe){if(u(U))return U;if(l(U))return B({readable:U});if(c(U))return B({writable:U});if(a(U))return B({writable:!1,readable:!1});if(d(U))return B({readable:k.fromWeb(U)});if(p(U))return B({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:W,write:re,final:$,destroy:Z}=T(U);if(o(W))return E(j,W,{objectMode:!0,write:re,final:$,destroy:Z});let M=W?.then;if(typeof M=="function"){let Q,ye=O(M,W,te=>{if(te!=null)throw new b("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){$(async()=>{try{await ye,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new b("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(A(U))return D(U.arrayBuffer());if(o(U))return E(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&p(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let W=U!=null&&U.readable?l(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 B({readable:W,writable:re})}let Y=U?.then;if(typeof Y=="function"){let W;return O(Y,U,re=>{re!=null&&W.push(re),W.push(null)},re=>{w(W,re)}),W=new j({objectMode:!0,writable:!1,read(){}})}throw new g(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:oe}=v(),Y=new C,W=Y.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:$,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(W.aborted)throw new f(void 0,{cause:W.reason});({promise:U,resolve:oe}=v()),yield $}})(),{signal:W}),write(re,$,Z){let M=oe;oe=null,M({chunk:re,done:!1,cb:Z})},final(re){let $=oe;oe=null,$({done:!0,cb:re})},destroy(re,$){Y.abort(),$(re)}}}function B(D){let U=D.readable&&typeof D.readable.read!="function"?k.wrap(D.readable):D.readable,oe=D.writable,Y=!!s(U),W=!!n(oe),re,$,Z,M,Q;function ye(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:Y,writable:W}),W&&(y(oe,te=>{W=!1,te&&w(U,te),ye(te)}),Q._write=function(te,we,K){oe.write(te,we)?K():re=K},Q._final=function(te){oe.end(),$=te},oe.on("drain",function(){if(re){let te=re;re=null,te()}}),oe.on("finish",function(){if($){let te=$;$=null,te()}})),Y&&(y(U,te=>{Y=!1,te&&w(U,te),ye(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){Q.push(null)}),Q._read=function(){for(;;){let te=U.read();if(te===null){Z=Q._read;return}if(!Q.push(te))return}}),Q._destroy=function(te,we){!te&&M!==null&&(te=new f),Z=null,re=null,$=null,M===null?we(te):(M=we,w(oe,te),w(U,te))},Q}}),ft=pe((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=Be();e.exports=l;var o=xr(),a=ki();n(l.prototype,o.prototype),n(l,o);{let p=s(a.prototype);for(let y=0;y<p.length;y++){let f=p[y];l.prototype[f]||(l.prototype[f]=a.prototype[f])}}function l(p){if(!(this instanceof l))return new l(p);o.call(this,p),a.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(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.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}l.fromWeb=function(p,y){return u().newStreamDuplexFromReadableWritablePair(p,y)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=Jc()),d(p,"body")}}),gs=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:s}=Ke().codes,n=ft(),{getHighWaterMark:o}=_r();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?o(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,y)=>{if(p){d?d(p):this.destroy(p);return}y!=null&&this.push(y),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,p,y){throw new s("_transform()")},l.prototype._write=function(d,p,y){let f=this._readableState,g=this._writableState,b=f.length;this._transform(d,p,(w,m)=>{if(w){y(w);return}m!=null&&this.push(m),g.ended||b===f.length||f.length<f.highWaterMark?y():this[a]=y})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),ys=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=s;var r=gs();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,o,a){a(null,n)}}),_i=pe((i,e)=>{le(),ue(),ce();var t=Mt(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:o}=Be(),a=kt(),{once:l}=Je(),c=Wt(),u=ft(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:y,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:g,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:k}=or(),{isIterable:x,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:A,isWebStream:C,isReadableStream:O,isReadableFinished:j}=ht(),T=globalThis.AbortController||nr().AbortController,B,D,U;function oe(te,we,K){let N=!1;te.on("close",()=>{N=!0});let ne=a(te,{readable:we,writable:K},z=>{N=!z});return{destroy:z=>{N||(N=!0,c.destroyer(te,z||new g("pipe")))},cleanup:ne}}function Y(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function W(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=xr()),yield*D.prototype[n].call(te)}async function $(te,we,K,{end:N}){let ne,z=null,G=se=>{if(se&&(ne=se),z){let R=z;z=null,R()}},J=()=>new s((se,R)=>{ne?R(ne):z=()=>{ne?R(ne):se()}});we.on("drain",G);let ge=a(we,{readable:!1},G);try{we.writableNeedDrain&&await J();for await(let se of te)we.write(se)||await J();N&&(we.end(),await J()),K()}catch(se){K(ne!==se?d(ne,se):se)}finally{ge(),we.off("drain",G)}}async function Z(te,we,K,{end:N}){A(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let z of te)await ne.ready,ne.write(z).catch(()=>{});await ne.ready,N&&await ne.close(),K()}catch(z){try{await ne.abort(z),K(z)}catch(G){K(G)}}}function M(...te){return Q(te,l(Y(te)))}function Q(te,we,K){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let N=new T,ne=N.signal,z=K?.signal,G=[];k(z,"options.signal");function J(){fe(new w)}U=U||Je().addAbortListener;let ge;z&&(ge=U(z,J));let se,R,q=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,ae){var Oe;if(ve&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=ve),!(!se&&!ae)){for(;q.length;)q.shift()(se);(Oe=ge)===null||Oe===void 0||Oe[o](),N.abort(),ae&&(se||G.forEach(h=>h()),t.nextTick(we,se,R))}}let be;for(let ve=0;ve<te.length;ve++){let ae=te[ve],Oe=ve<te.length-1,h=ve>0,_=Oe||K?.end!==!1,I=ve===te.length-1;if(S(ae)){let F=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(_){let{destroy:X,cleanup:de}=oe(ae,Oe,h);q.push(X),v(ae)&&I&&G.push(de)}ae.on("error",F),v(ae)&&I&&G.push(()=>{ae.removeListener("error",F)})}if(ve===0)if(typeof ae=="function"){if(be=ae({signal:ne}),!x(be))throw new y("Iterable, AsyncIterable or Stream","source",be)}else x(ae)||E(ae)||A(ae)?be=ae:be=u.from(ae);else if(typeof ae=="function"){if(A(be)){var H;be=W((H=be)===null||H===void 0?void 0:H.readable)}else be=W(be);if(be=ae(be,{signal:ne}),Oe){if(!x(be,!0))throw new y("AsyncIterable",`transform[${ve-1}]`,be)}else{var me;B||(B=ys());let F=new B({objectMode:!0}),X=(me=be)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(be,V=>{R=V,V!=null&&F.write(V),_&&F.end(),t.nextTick(he)},V=>{F.destroy(V),t.nextTick(he,V)});else if(x(be,!0))ee++,$(be,F,he,{end:_});else if(O(be)||A(be)){let V=be.readable||be;ee++,$(V,F,he,{end:_})}else throw new y("AsyncIterable or Promise","destination",be);be=F;let{destroy:de,cleanup:_e}=oe(be,!1,!0);q.push(de),I&&G.push(_e)}}else if(S(ae)){if(E(be)){ee+=2;let F=ye(be,ae,he,{end:_});v(ae)&&I&&G.push(F)}else if(A(be)||O(be)){let F=be.readable||be;ee++,$(F,ae,he,{end:_})}else if(x(be))ee++,$(be,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else if(C(ae)){if(E(be))ee++,Z(W(be),ae,he,{end:_});else if(O(be)||x(be))ee++,Z(be,ae,he,{end:_});else if(A(be))ee++,Z(be.readable,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else be=u.from(ae)}return(ne!=null&&ne.aborted||z!=null&&z.aborted)&&t.nextTick(J),be}function ye(te,we,K,{end:N}){let ne=!1;if(we.on("close",()=>{ne||K(new b)}),te.pipe(we,{end:!1}),N){let z=function(){ne=!0,we.end()};j(te)?t.nextTick(z):te.once("end",z)}else K();return a(te,{readable:!0,writable:!1},z=>{let G=te._readableState;z&&z.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?te.once("end",K).once("error",K):K(z)}),a(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:Q,pipeline:M}}),bs=pe((i,e)=>{le(),ue(),ce();var{pipeline:t}=_i(),r=ft(),{destroyer:s}=Wt(),{isNodeStream:n,isReadable:o,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=ht(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:y,ERR_MISSING_ARGS:f}}=Ke(),g=kt();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let w=[...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])&&!l(b[T]))){if(T<b.length-1&&!(o(b[T])||d(b[T])||c(b[T])))throw new y(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(b[T])||u(b[T])||c(b[T])))throw new y(`streams[${T}]`,w[T],"must be writable")}let m,k,x,v,E;function S(T){let B=v;v=null,B?B(T):T?E.destroy(T):!j&&!O&&E.destroy()}let A=b[0],C=t(b,S),O=!!(a(A)||u(A)||c(A)),j=!!(o(C)||d(C)||c(C));if(E=new r({writableObjectMode:!!(A!=null&&A.writableObjectMode),readableObjectMode:!!(C!=null&&C.readableObjectMode),writable:O,readable:j}),O){if(n(A))E._write=function(B,D,U){A.write(B,D)?U():m=U},E._final=function(B){A.end(),k=B},A.on("drain",function(){if(m){let B=m;m=null,B()}});else if(l(A)){let B=(c(A)?A.writable:A).getWriter();E._write=async function(D,U,oe){try{await B.ready,B.write(D).catch(()=>{}),oe()}catch(Y){oe(Y)}},E._final=async function(D){try{await B.ready,B.close().catch(()=>{}),k=D}catch(U){D(U)}}}let T=c(C)?C.readable:C;g(T,()=>{if(k){let B=k;k=null,B()}})}if(j){if(n(C))C.on("readable",function(){if(x){let T=x;x=null,T()}}),C.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=C.read();if(T===null){x=E._read;return}if(!E.push(T))return}};else if(l(C)){let T=(c(C)?C.readable:C).getReader();E._read=async function(){for(;;)try{let{value:B,done:D}=await T.read();if(!E.push(B))return;if(D){E.push(null);return}}catch{return}}}}return E._destroy=function(T,B){!T&&v!==null&&(T=new p),x=null,m=null,k=null,v===null?B(T):(v=B,n(C)&&s(C,T))},E}}),Qc=pe((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||nr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:o},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=or(),d=Be().Symbol("kWeak"),p=Be().Symbol("kResistStopPropagation"),{finished:y}=kt(),f=bs(),{addAbortSignalNoValidate:g}=kr(),{isWritable:b,isNodeStream:w}=ht(),{deprecate:m}=Je(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:E,NumberIsNaN:S,Promise:A,PromiseReject:C,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=Be(),B=T("kEmpty"),D=T("kEof");function U(z,G){if(G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),w(z)&&!b(z))throw new r("stream",z,"must be writable");let J=f(this,z);return G!=null&&G.signal&&g(G.signal,J),J}function oe(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal");let J=1;G?.concurrency!=null&&(J=v(G.concurrency));let ge=J-1;return G?.highWaterMark!=null&&(ge=v(G.highWaterMark)),c(J,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=J,(async function*(){let se=Je().AbortSignalAny([G?.signal].filter(x)),R=this,q=[],ee={signal:se},he,fe,be=!1,H=0;function me(){be=!0,ve()}function ve(){H-=1,ae()}function ae(){fe&&!be&&H<J&&q.length<ge&&(fe(),fe=null)}async function Oe(){try{for await(let h of R){if(be)return;if(se.aborted)throw new a;try{if(h=z(h,ee),h===B)continue;h=O(h)}catch(_){h=C(_)}H+=1,j(h,ve,me),q.push(h),he&&(he(),he=null),!be&&(q.length>=ge||H>=J)&&await new A(_=>{fe=_})}q.push(D)}catch(h){let _=C(h);j(_,ve,me),q.push(_)}finally{be=!0,he&&(he(),he=null)}}Oe();try{for(;;){for(;q.length>0;){let h=await q[0];if(h===D)return;if(se.aborted)throw new a;h!==B&&(yield h),q.shift(),ae()}await new A(h=>{he=h})}}finally{be=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(z=void 0){return z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal"),(async function*(){let G=0;for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a({cause:z.signal.reason});yield[G++,ge]}}).call(this)}async function W(z,G=void 0){for await(let J of M.call(this,z,G))return!0;return!1}async function re(z,G=void 0){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);return!await W.call(this,async(...J)=>!await z(...J),G)}async function $(z,G){for await(let J of M.call(this,z,G))return J}async function Z(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se),B}for await(let ge of oe.call(this,J,G));}function M(z,G){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se)?ge:B}return oe.call(this,J,G)}var Q=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function ye(z,G,J){var ge;if(typeof z!="function")throw new s("reducer",["Function","AsyncFunction"],z);J!=null&&u(J,"options"),J?.signal!=null&&l(J.signal,"options.signal");let se=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new a(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await y(this.destroy(fe)),fe}let R=new t,q=R.signal;if(J!=null&&J.signal){let fe={once:!0,[d]:this,[p]:!0};J.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var he;if(ee=!0,J!=null&&(he=J.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?G=await z(G,fe,{signal:q}):(G=fe,se=!0)}if(!ee&&!se)throw new Q}finally{R.abort()}return G}async function te(z){z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal");let G=[];for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a(void 0,{cause:z.signal.reason});k(G,ge)}return G}function we(z,G){let J=oe.call(this,z,G);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function K(z){if(z=E(z),S(z))return 0;if(z<0)throw new o("number",">= 0",z);return z}function N(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;z--<=0&&(yield se)}}).call(this)}function ne(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var J;if(G!=null&&(J=G.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(G!=null&&(ge=G.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;if(z-- >0&&(yield se),z<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:N,filter:M,flatMap:we,map:oe,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:ye,toArray:te,some:W,find:$}}),vs=pe((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:s,isNodeStream:n,isWebStream:o}=ht(),{pipelineImpl:a}=_i(),{finished:l}=kt();ws();function c(...u){return new r((d,p)=>{let y,f,g=u[u.length-1];if(g&&typeof g=="object"&&!n(g)&&!s(g)&&!o(g)){let b=t(u);y=b.signal,f=b.end}a(u,(b,w)=>{b?p(b):d(w)},{signal:y,end:f})})}e.exports={finished:l,pipeline:c}}),ws=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=Be(),{promisify:{custom:o}}=Je(),{streamReturningOperators:a,promiseReturningOperators:l}=Qc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=bs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=_r(),{pipeline:y}=_i(),{destroyer:f}=Wt(),g=kt(),b=vs(),w=ht(),m=e.exports=wi().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=xr();for(let x of s(a)){let v=function(...S){if(new.target)throw c();return m.Readable.from(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})}for(let x of s(l)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=l[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=ki(),m.Duplex=ft(),m.Transform=gs(),m.PassThrough=ys(),m.pipeline=y;var{addAbortSignal:k}=kr();m.addAbortSignal=k,m.finished=g,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(y,o,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(g,o,{__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)}}),Rt=pe((i,e)=>{le(),ue(),ce();var t=ws(),r=vs(),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}),Xc=pe((i,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}}}),Zc=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),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 o=0;for(let a=0;a<this._bufs.length;a++){let l=o+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-o];o=l}},s.prototype._reverseOffset=function(n){let o=n[0],a=n[1];for(let l=0;l<o;l++)a+=this._bufs[l].length;return a},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let o=this._offset(n);return this._bufs[o[0]][o[1]]},s.prototype.slice=function(n,o){return typeof n=="number"&&n<0&&(n+=this.length),typeof o=="number"&&o<0&&(o+=this.length),this.copy(null,0,n,o)},s.prototype.copy=function(n,o,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,p=d,y=c&&o||0,f=u[1];if(a===0&&l===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,o,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let g=u[0];g<this._bufs.length;g++){let b=this._bufs[g].length-f;if(p>b)this._bufs[g].copy(n,y,f),y+=b;else{this._bufs[g].copy(n,y,f,f+p),y+=b;break}p-=b,f&&(f=0)}return n.length>y?n.slice(0,y):n},s.prototype.shallowSlice=function(n,o){if(n=n||0,o=typeof o!="number"?this.length:o,n<0&&(n+=this.length),o<0&&(o+=this.length),n===o)return this._new();let a=this._offset(n),l=this._offset(o),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},s.prototype.toString=function(n,o,a){return this.slice(o,a).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 o=0;o<this._bufs.length;o++)n.append(this._bufs[o]);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,o,a){if(n==null)return this;if(n.buffer)o.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],o,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],o,a)}else typeof n=="number"&&(n=n.toString()),o.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,o,a){if(a===void 0&&typeof o=="string"&&(a=o,o=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,a):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)),o=Number(o||0),isNaN(o)&&(o=0),o<0&&(o=this.length+o),o<0&&(o=0),n.length===0)return o>this.length?this.length:o;let l=this._offset(o),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.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,o){if(this.length-n<o.length)return!1;for(let a=0;a<o.length;a++)if(this.get(n+a)!==o[a])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 o in n)(function(a){n[a]===null?s.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:s.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(o)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),eu=pe((i,e)=>{le(),ue(),ce();var t=Rt().Duplex,r=Xc(),s=Zc();function n(o){if(!(this instanceof n))return new n(o);if(typeof o=="function"){this._callback=o;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),o=null}s._init.call(this,o),t.call(this)}r(n,t),Object.assign(n.prototype,s.prototype),n.prototype._new=function(o){return new n(o)},n.prototype._write=function(o,a,l){this._appendBuffer(o),typeof l=="function"&&l()},n.prototype._read=function(o){if(!this.length)return this.push(null);o=Math.min(o,this.length),this.push(this.slice(0,o)),this.consume(o)},n.prototype.end=function(o){t.prototype.end.call(this,o),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(o,a){this._bufs.length=0,this.length=0,a(o)},n.prototype._isBufferList=function(o){return o instanceof n||o instanceof s||n.isBufferList(o)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),tu=pe((i,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}),ks=pe((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(qe(),Ne($e));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 o=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+o.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let o=t.types[n];t.codes[o]=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 o=t.properties[n];t.propertiesCodes[o]=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(o=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|o<<t.QOS_SHIFT|l,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"}}),ru=pe((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,o=n*7,a=n*365.25;e.exports=function(p,y){y=y||{};var f=typeof p;if(f==="string"&&p.length>0)return l(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 l(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*a;case"weeks":case"week":case"w":return f*o;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?d(p,y,n,"day"):y>=s?d(p,y,s,"hour"):y>=r?d(p,y,r,"minute"):y>=t?d(p,y,t,"second"):p+" ms"}function d(p,y,f,g){var b=y>=f*1.5;return Math.round(p/f)+" "+g+(b?"s":"")}}),nu=pe((i,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=ru(),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,w;function m(...k){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,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let S=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(A,C)=>{if(A==="%%")return"%";S++;let O=n.formatters[C];if(typeof O=="function"){let j=k[S];A=O.call(x,j),k.splice(S,1),S--}return A}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}return m.namespace=y,m.useColors=n.useColors(),m.color=n.selectColor(y),m.extend=o,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(b!==n.namespaces&&(b=n.namespaces,w=n.enabled(y)),w),set:k=>{g=k}}),typeof n.init=="function"&&n.init(m),m}function o(y,f){let g=n(this.namespace+(typeof f>"u"?":":f)+y);return g.log=this.log,g}function a(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 l(y,f){let g=0,b=0,w=-1,m=0;for(;g<y.length;)if(b<f.length&&(f[b]===y[g]||f[b]==="*"))f[b]==="*"?(w=b,m=g,b++):(g++,b++);else if(w!==-1)b=w+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(l(y,f))return!1;for(let f of n.names)if(l(y,f))return!0;return!1}function d(y){return y instanceof Error?y.stack||y.message:y}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),pt=pe((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=s,i.load=n,i.useColors=t,i.storage=o(),i.destroy=(()=>{let l=!1;return()=>{l||(l=!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`."))}})(),i.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 l;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&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}i.log=console.debug||console.log||(()=>{});function s(l){try{l?i.storage.setItem("debug",l):i.storage.removeItem("debug")}catch{}}function n(){let l;try{l=i.storage.getItem("debug")||i.storage.getItem("DEBUG")}catch{}return!l&&typeof je<"u"&&"env"in je&&(l=je.env.DEBUG),l}function o(){try{return localStorage}catch{}}e.exports=nu()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),iu=pe((i,e)=>{le(),ue(),ce();var t=eu(),{EventEmitter:r}=(Ot(),Ne(wt)),s=tu(),n=ks(),o=pt()("mqtt-packet:parser"),a=class jo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof jo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new jo().parser(c)}_resetState(){o("_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),o("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++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("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 d=c&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==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,o("_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)),o("_parseLength %d",c.value),!!c}_parsePayload(){o("_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 o("_parsePayload complete result: %s",c),c}_parseConnect(){o("_parseConnect");let c,u,d,p,y={},f=this.packet,g=this._parseString();if(g===null)return this._emitError(new Error("Cannot parse protocolId"));if(g!=="MQTT"&&g!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=g,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));y.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,y.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,y.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(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=w;else{if(b)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)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 k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,o("_parseConnect: packet.clientId: %s",f.clientId),y.will){if(f.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,o("_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,o("_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,o("_parseConnect: packet.username: %s",f.username)}if(y.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,o("_parseConnect: complete"),f}_parseConnack(){o("_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 d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}o("_parseConnack: complete")}_parsePublish(){o("_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),o("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){o("_parseSubscribe");let c=this.packet,u,d,p,y,f,g,b;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}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(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(g=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,y=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,y>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=g,b.rap=f,b.rh=y):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",b),c.subscriptions.push(b)}}}_parseSuback(){o("_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(){o("_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"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){o("_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 d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){o("_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}o("_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(o("_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 o("_parseDisconnect result: true"),!0}_parseAuth(){o("_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),o("_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):(o("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,o("_parseString: result: %s",p),p}_parseStringPair(){return o("_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 d=this._list.slice(this._pos,u);return this._pos+=c,o("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,o("_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,o("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){o("_parseVarByteNum");let u=4,d=0,p=1,y=0,f=!1,g,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(g=this._list.readUInt8(b+d++),y+=p*(g&n.VARBYTEINT_MASK),p*=128,(g&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=d),f?c?f={bytes:d,value:y}:f=y:f=!1,o("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",c),c}_parseByType(c){switch(o("_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(){o("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let y=n.propertiesCodes[p];if(!y)return this._emitError(new Error("Unknown property")),!1;if(y==="userProperties"){d[y]||(d[y]=Object.create(null));let f=this._parseByType(n.propertiesTypes[y]);if(d[y][f.name])if(Array.isArray(d[y][f.name]))d[y][f.name].push(f.value);else{let g=d[y][f.name];d[y][f.name]=[g],d[y][f.name].push(f.value)}else d[y][f.name]=f.value;continue}d[y]?Array.isArray(d[y])?d[y].push(this._parseByType(n.propertiesTypes[y])):(d[y]=[d[y]],d[y].push(this._parseByType(n.propertiesTypes[y]))):d[y]=this._parseByType(n.propertiesTypes[y])}return d}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_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)),o("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(c){o("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),ou=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),r=65536,s={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function o(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)s[u]=o(u)}function l(u){let d=0,p=0,y=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),y.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?y.subarray(0,p):y.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:s,generateCache:a,generateNumber:o,genBufVariableByteInt:l,generate4ByteBuffer:c}}),su=pe((i,e)=>{le(),ue(),ce(),typeof je>"u"||!je.version||je.version.indexOf("v0.")===0||je.version.indexOf("v1.")===0&&je.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=je;function t(r,s,n,o){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return je.nextTick(r);case 2:return je.nextTick(function(){r.call(null,s)});case 3:return je.nextTick(function(){r.call(null,s,n)});case 4:return je.nextTick(function(){r.call(null,s,n,o)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return je.nextTick(function(){r.apply(null,l)})}}}),_s=pe((i,e)=>{le(),ue(),ce();var t=ks(),{Buffer:r}=(qe(),Ne($e)),s=r.allocUnsafe(0),n=r.from([0]),o=ou(),a=su().nextTick,l=pt()("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,p=o.genBufVariableByteInt,y=o.generate4ByteBuffer,f=Y,g=!0;function b(K,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),g&&(g=!1,d()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,N);case"connack":return k(K,N,ne);case"publish":return x(K,N,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(K,N,ne);case"subscribe":return E(K,N,ne);case"suback":return S(K,N,ne);case"unsubscribe":return A(K,N,ne);case"unsuback":return C(K,N,ne);case"pingreq":case"pingresp":return O(K,N);case"disconnect":return j(K,N,ne);case"auth":return T(K,N,ne);default:return N.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===Y},set(K){K?((!c||Object.keys(c).length===0)&&(g=!0),f=Y):(g=!1,f=W)}});function w(K){K.uncork()}function m(K,N,ne){let z=K||{},G=z.protocolId||"MQTT",J=z.protocolVersion||4,ge=z.will,se=z.clean,R=z.keepalive||0,q=z.clientId||"",ee=z.username,he=z.password,fe=z.properties;se===void 0&&(se=!0);let be=0;if(typeof G!="string"&&!r.isBuffer(G))return N.destroy(new Error("Invalid protocolId")),!1;if(be+=G.length+2,J!==3&&J!==4&&J!==5)return N.destroy(new Error("Invalid protocol version")),!1;if(be+=1,(typeof q=="string"||r.isBuffer(q))&&(q||J>=4)&&(q||se))be+=r.byteLength(q)+2;else{if(J<4)return N.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return N.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 N.destroy(new Error("Invalid keepalive")),!1;be+=2,be+=1;let H,me;if(J===5){if(H=Z(N,fe),!H)return!1;be+=H.length}if(ge){if(typeof ge!="object")return N.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return N.destroy(new Error("Invalid will topic")),!1;if(be+=r.byteLength(ge.topic)+2,be+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?be+=r.byteLength(ge.payload):be+=ge.payload.length;else return N.destroy(new Error("Invalid will payload")),!1;if(me={},J===5){if(me=Z(N,ge.properties),!me)return!1;be+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,be+=r.byteLength(ee)+2;else return N.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return N.destroy(new Error("Username is required to use password")),!1;if(we(he))be+=te(he)+2;else return N.destroy(new Error("Invalid password")),!1}N.write(t.CONNECT_HEADER),D(N,be),$(N,G),z.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=ee!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,ae|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,ae|=ge?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,N.write(r.from([ae])),f(N,R),J===5&&H.write(),$(N,q),ge&&(J===5&&me.write(),U(N,ge.topic),$(N,ge.payload)),ee!=null&&$(N,ee),he!=null&&$(N,he),!0}function k(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=z===5?G.reasonCode:G.returnCode,ge=G.properties,se=2;if(typeof J!="number")return N.destroy(new Error("Invalid return code")),!1;let R=null;if(z===5){if(R=Z(N,ge),!R)return!1;se+=R.length}return N.write(t.CONNACK_HEADER),D(N,se),N.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),N.write(r.from([J])),R?.write(),!0}function x(K,N,ne){l("publish: packet: %o",K);let z=ne?ne.protocolVersion:4,G=K||{},J=G.qos||0,ge=G.retain?t.RETAIN_MASK:0,se=G.topic,R=G.payload||s,q=G.messageId,ee=G.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof q!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(z===5){if(fe=Z(N,ee),!fe)return!1;he+=fe.length}return N.write(t.PUBLISH_HEADER[J][G.dup?1:0][ge?1:0]),D(N,he),f(N,te(se)),N.write(se),J>0&&f(N,q),fe?.write(),l("publish: payload: %o",R),N.write(R)}function v(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.cmd||"puback",ge=G.messageId,se=G.dup&&J==="pubrel"?t.DUP_MASK:0,R=0,q=G.reasonCode,ee=G.properties,he=z===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(z===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][R][se][0]),he===3&&(he+=q!==0?1:-1),D(N,he),f(N,ge),z===5&&he!==2&&N.write(r.from([q])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function E(K,N,ne){l("subscribe: packet: ");let z=ne?ne.protocolVersion:4,G=K||{},J=G.dup?t.DUP_MASK:0,ge=G.messageId,se=G.subscriptions,R=G.properties,q=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;q+=2;let ee=null;if(z===5){if(ee=Z(N,R),!ee)return!1;q+=ee.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let be=se[fe].topic,H=se[fe].qos;if(typeof be!="string")return N.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return N.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(z===5){if(typeof(se[fe].nl||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[fe].rh||0;if(typeof me!="number"||me>2)return N.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=r.byteLength(be)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(N,q),f(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of se){let be=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;U(N,be),Oe=t.SUBSCRIBE_OPTIONS_QOS[H],z===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=N.write(r.from([Oe]))}return he}function S(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.granted,se=G.properties,R=0;if(typeof J!="number")return N.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 N.destroy(new Error("Invalid qos vector")),!1;R+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let q=null;if(z===5){if(q=M(N,se,ne,R),!q)return!1;R+=q.length}return N.write(t.SUBACK_HEADER),D(N,R),f(N,J),q!==null&&q.write(),N.write(r.from(ge))}function A(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,se=G.unsubscriptions,R=G.properties,q=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(q+=2,typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){if(typeof se[fe]!="string")return N.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return N.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(z===5){if(ee=Z(N,R),!ee)return!1;q+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(N,q),f(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(N,se[fe]);return he}function C(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.messageId,ge=G.dup?t.DUP_MASK:0,se=G.granted,R=G.properties,q=G.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(z===5)if(typeof se=="object"&&se.length)for(let be=0;be<se.length;be+=1){if(typeof se[be]!="number")return N.destroy(new Error("Invalid qos vector")),!1;he+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(z===5){if(fe=M(N,R,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[q][ee][ge][0]),D(N,he),f(N,J),fe!==null&&fe.write(),z===5&&N.write(r.from(se)),!0}function O(K,N,ne){return N.write(t.EMPTY[K.cmd])}function j(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,se=z===5?1:0,R=null;if(z===5){if(R=M(N,ge,ne,se),!R)return!1;se+=R.length}return N.write(r.from([t.codes.disconnect<<4])),D(N,se),z===5&&N.write(r.from([J])),R!==null&&R.write(),!0}function T(K,N,ne){let z=ne?ne.protocolVersion:4,G=K||{},J=G.reasonCode,ge=G.properties,se=z===5?1:0;z!==5&&N.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(N,ge,ne,se);return R?(se+=R.length,N.write(r.from([t.codes.auth<<4])),D(N,se),N.write(r.from([J])),R!==null&&R.write(),!0):!1}var B={};function D(K,N){if(N>t.VARBYTEINT_MAX)return K.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=B[N];return ne||(ne=p(N),N<16384&&(B[N]=ne)),l("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function U(K,N){let ne=r.byteLength(N);return f(K,ne),l("writeString: %s",N),K.write(N,"utf8")}function oe(K,N,ne){U(K,N),U(K,ne)}function Y(K,N){return l("writeNumberCached: number: %d",N),l("writeNumberCached: %o",c[N]),K.write(c[N])}function W(K,N){let ne=u(N);return l("writeNumberGenerated: %o",ne),K.write(ne)}function re(K,N){let ne=y(N);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,N){typeof N=="string"?U(K,N):N?(f(K,N.length),K.write(N)):f(K,0)}function Z(K,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){ye(K,{},0)}};let ne=0;function z(G,J){let ge=t.propertiesTypes[G],se=0;switch(ge){case"byte":{if(typeof J!="boolean")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=2;break}case"binary":{if(J&&J===null)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=1+r.byteLength(J)+2;break}case"int16":{if(typeof J!="number"||J<0||J>65535)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=1+r.byteLength(p(J));break}case"string":{if(typeof J!="string")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return K.destroy(new Error(`Invalid ${G}: ${J}`)),!1;se+=Object.getOwnPropertyNames(J).reduce((R,q)=>{let ee=J[q];return Array.isArray(ee)?R+=ee.reduce((he,fe)=>(he+=3+r.byteLength(q.toString())+2+r.byteLength(fe.toString()),he),0):R+=3+r.byteLength(q.toString())+2+r.byteLength(J[q].toString()),R},0);break}default:return K.destroy(new Error(`Invalid property ${G}: ${J}`)),!1}return se}if(N)for(let G in N){let J=0,ge=0,se=N[G];if(se!==void 0){if(Array.isArray(se))for(let R=0;R<se.length;R++){if(ge=z(G,se[R]),!ge)return!1;J+=ge}else{if(ge=z(G,se),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(p(ne))+ne,write(){ye(K,N,ne)}}}function M(K,N,ne,z){let G=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(K,N);if(J)for(;z+ge.length>J;){let se=G.shift();if(se&&N[se])delete N[se],ge=Z(K,N);else return!1}return ge}function Q(K,N,ne){switch(t.propertiesTypes[N]){case"byte":{K.write(r.from([t.properties[N]])),K.write(r.from([+ne]));break}case"int8":{K.write(r.from([t.properties[N]])),K.write(r.from([ne]));break}case"binary":{K.write(r.from([t.properties[N]])),$(K,ne);break}case"int16":{K.write(r.from([t.properties[N]])),f(K,ne);break}case"int32":{K.write(r.from([t.properties[N]])),re(K,ne);break}case"var":{K.write(r.from([t.properties[N]])),D(K,ne);break}case"string":{K.write(r.from([t.properties[N]])),U(K,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(z=>{let G=ne[z];Array.isArray(G)?G.forEach(J=>{K.write(r.from([t.properties[N]])),oe(K,z.toString(),J.toString())}):(K.write(r.from([t.properties[N]])),oe(K,z.toString(),G.toString()))});break}default:return K.destroy(new Error(`Invalid property ${N} value: ${ne}`)),!1}}function ye(K,N,ne){D(K,ne);for(let z in N)if(Object.prototype.hasOwnProperty.call(N,z)&&N[z]!=null){let G=N[z];if(Array.isArray(G))for(let J=0;J<G.length;J++)Q(K,z,G[J]);else Q(K,z,G)}}function te(K){return K?K instanceof r?K.length:r.byteLength(K):0}function we(K){return typeof K=="string"||K instanceof r}e.exports=b}),au=pe((i,e)=>{le(),ue(),ce();var t=_s(),{EventEmitter:r}=(Ot(),Ne(wt)),{Buffer:s}=(qe(),Ne($e));function n(a,l){let c=new o;return t(a,c,l),c.concat()}var o=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=s.byteLength(c[d]),a+=l[d];let p=s.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),lu=pe(i=>{le(),ue(),ce(),i.parser=iu().parser,i.generate=au(),i.writeToStream=_s()}),cu=pe((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof wr?wr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let o=new Map;if(o.set(Date,d=>new Date(d)),o.set(Map,(d,p)=>new Map(l(Array.from(d),p))),o.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)o.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,p){let y=Object.keys(d),f=new Array(y.length);for(let g=0;g<y.length;g++){let b=y[g],w=d[b];typeof w!="object"||w===null?f[b]=w:w.constructor!==Object&&(a=o.get(w.constructor))?f[b]=a(w,p):ArrayBuffer.isView(w)?f[b]=t(w):f[b]=p(w)}return f}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,c);let p={};for(let y in d){if(Object.hasOwnProperty.call(d,y)===!1)continue;let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[y]=a(f,c):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=c(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,u);let p={};for(let y in d){let f=d[y];typeof f!="object"||f===null?p[y]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[y]=a(f,u):ArrayBuffer.isView(f)?p[y]=t(f):p[y]=u(f)}return p}}function s(n){let o=[],a=[],l=new Map;if(l.set(Date,y=>new Date(y)),l.set(Map,(y,f)=>new Map(u(Array.from(y),f))),l.set(Set,(y,f)=>new Set(u(Array.from(y),f))),n.constructorHandlers)for(let y of n.constructorHandlers)l.set(y[0],y[1]);let c=null;return n.proto?p:d;function u(y,f){let g=Object.keys(y),b=new Array(g.length);for(let w=0;w<g.length;w++){let m=g[w],k=y[m];if(typeof k!="object"||k===null)b[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))b[m]=c(k,f);else if(ArrayBuffer.isView(k))b[m]=t(k);else{let x=o.indexOf(k);x!==-1?b[m]=a[x]:b[m]=f(k)}}return b}function d(y){if(typeof y!="object"||y===null)return y;if(Array.isArray(y))return u(y,d);if(y.constructor!==Object&&(c=l.get(y.constructor)))return c(y,d);let f={};o.push(y),a.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=l.get(b.constructor)))f[g]=c(b,d);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let w=o.indexOf(b);w!==-1?f[g]=a[w]:f[g]=d(b)}}return o.pop(),a.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=l.get(y.constructor)))return c(y,p);let f={};o.push(y),a.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=l.get(b.constructor)))f[g]=c(b,p);else if(ArrayBuffer.isView(b))f[g]=t(b);else{let w=o.indexOf(b);w!==-1?f[g]=a[w]:f[g]=p(b)}}return o.pop(),a.pop(),f}}}),uu=pe((i,e)=>{le(),ue(),ce(),e.exports=cu()()}),xs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.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}}),Ss=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Rt(),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,o){return this._inflights.set(n.messageId,n),o&&o(),this}createStream(){let n=new e.Readable(t),o=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{o.push(c)}),n._read=()=>{!a&&l<o.length?n.push(o[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,o){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),o(null,a)):o&&o(new Error("missing packet")),this}get(n,o){let a=this._inflights.get(n.messageId);return a?o(null,a):o&&o(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=s}),du=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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 o=s.topic.toString(),a=s.payload,{qos:l}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let d;if(s.properties&&(d=s.properties.topicAlias),typeof d<"u")if(o.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)o=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",o,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(o,d))r.log("handlePublish :: registered topic: %s - alias: %d",o,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",o,a,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",o,a,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),hu=pe((i,e)=>{e.exports={version:"5.15.0"}}),zt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.MQTTJS_VERSION=i.nextTick=i.ErrorWithSubackPacket=i.ErrorWithReasonCode=void 0,i.applyMixin=r;var e=class yc extends Error{code;constructor(n,o){super(n),this.code=o,Object.setPrototypeOf(this,yc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class bc extends Error{packet;constructor(n,o){super(n),this.packet=o,Object.setPrototypeOf(this,bc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(s,n,o=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(o||c!=="constructor")&&Object.defineProperty(s.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof je?.nextTick=="function"?je.nextTick:s=>{setTimeout(s,0)},i.MQTTJS_VERSION=hu().version}),Sr=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=zt();i.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,o=s.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[p]}`),c.code=p;let y=r.messageIdToTopic[n];y&&y.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),fu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=zt(),t=Sr(),r=(s,n)=>{let{options:o}=s,a=o.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(l===24)s.reconnecting=!1,s._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);s.emit("error",d)}})};i.default=r}),pu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof je=="object"&&je?je:{},s=(y,f,g,b)=>{typeof r.emitWarning=="function"?r.emitWarning(y,f,g,b):console.error(`[${g}] ${f}: ${y}`)},n=globalThis.AbortController,o=globalThis.AbortSignal;if(typeof n>"u"){o=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(g,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new o;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 a=y=>!t.has(y),l=y=>y&&y===Math.floor(y)&&y>0&&isFinite(y),c=y=>l(y)?y<=Math.pow(2,8)?Uint8Array:y<=Math.pow(2,16)?Uint16Array:y<=Math.pow(2,32)?Uint32Array:y<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(y){super(y),this.fill(0)}},d=class mr{heap;length;static#l=!1;static create(f){let g=c(f);if(!g)return[];mr.#l=!0;let b=new mr(f,g);return mr.#l=!1,b}constructor(f,g){if(!mr.#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 vc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#r;#e;#c;#h;#a;#o;#b;#s;#v;#w;#f;#k;#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.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#b,isBackgroundFetch:g=>f.#t(g),backgroundFetch:(g,b,w,m)=>f.#L(g,b,w,m),moveToTail:g=>f.#C(g),indexes:g=>f.#_(g),rindexes:g=>f.#x(g),isStale:g=>f.#p(g)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(f){let{max:g=0,ttl:b,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:A,noUpdateTTL:C,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:B,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=f;if(g!==0&&!l(g))throw new TypeError("max option must be a nonnegative integer");let $=g?c(g):Array;if(!$)throw new Error("invalid max value: "+g);if(this.#l=g,this.#d=O,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!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.#O=D,B!==void 0&&typeof B!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=B,this.#A=!!B,this.#n=new Map,this.#r=new Array(g).fill(void 0),this.#e=new Array(g).fill(void 0),this.#c=new $(g),this.#h=new $(g),this.#a=0,this.#o=0,this.#b=d.create(g),this.#i=0,this.#y=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!A,this.noUpdateTTL=!!C,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#d){let Z="LRU_CACHE_UNBOUNDED";a(Z)&&(t.add(Z),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,vc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),g=new u(this.#l);this.#f=f,this.#w=g,this.#j=(m,k,x=e.now())=>{if(g[m]=k!==0?x:0,f[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{g[m]=f[m]!==0?e.now():0},this.#E=(m,k)=>{if(f[k]){let x=f[k],v=g[k];if(!x||!v)return;m.ttl=x,m.start=v,m.now=b||w();let E=m.now-v;m.remainingTTL=x-E}};let b=0,w=()=>{let m=e.now();if(this.ttlResolution>0){b=m;let k=setTimeout(()=>b=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=f[k],v=g[k];if(!x||!v)return 1/0;let E=(b||w())-v;return x-E},this.#p=m=>{let k=g[m],x=f[m];return!!x&&!!k&&(b||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#y=0,this.#v=f,this.#T=g=>{this.#y-=f[g],f[g]=0},this.#U=(g,b,w,m)=>{if(this.#t(b))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(b,g),!l(w))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 w},this.#M=(g,b,w)=>{if(f[g]=b,this.#d){let m=this.#d-f[g];for(;this.#y>m;)this.#R(!0)}this.#y+=f[g],w&&(w.entrySize=b,w.totalCalculatedSize=this.#y)}}#T=f=>{};#M=(f,g,b)=>{};#U=(f,g,b,w)=>{if(b||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({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.#h[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.#_())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.#_()){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.#_())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.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;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.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(g,m,this.#r[b],this)}}rforEach(f,g=this){for(let b of this.#x()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;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],w=this.#t(b)?b.__staleWhileFetching:b;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[g],x=this.#w[g];if(k&&x){let v=k-(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.#_({allowStale:!0})){let b=this.#r[g],w=this.#e[g],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||b===void 0)continue;let k={value:m};if(this.#f&&this.#w){k.ttl=this.#f[g];let x=e.now()-this.#w[g];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[g]),f.unshift([b,k])}return f}load(f){this.clear();for(let[g,b]of f){if(b.start){let w=Date.now()-b.start;b.start=e.now()-w}this.set(g,b.value,b)}}set(f,g,b={}){if(g===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=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 A=this.#i===0?void 0:this.#n.get(f);if(A===void 0)A=this.#i===0?this.#o:this.#b.length!==0?this.#b.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[A]=f,this.#e[A]=g,this.#n.set(f,A),this.#c[this.#o]=A,this.#h[A]=this.#o,this.#o=A,this.#i++,this.#M(A,S,v),v&&(v.set="add"),E=!1;else{this.#C(A);let C=this.#e[A];if(g!==C){if(this.#A&&this.#t(C)){C.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=C;O!==void 0&&!k&&(this.#k&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else k||(this.#k&&this.#m?.(C,f,"set"),this.#u&&this.#s?.push([C,f,"set"]));if(this.#T(A),this.#M(A,S,v),this.#e[A]=g,v){v.set="replace";let O=C&&this.#t(C)?C.__staleWhileFetching:C;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(E||this.#j(A,w,m),v&&this.#E(v,A)),!k&&this.#u&&this.#s){let C=this.#s,O;for(;O=C?.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,b=this.#r[g],w=this.#e[g];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,b,"evict"),this.#u&&this.#s?.push([w,b,"evict"])),this.#T(g),f&&(this.#r[g]=void 0,this.#e[g]=void 0,this.#b.push(g)),this.#i===1?(this.#a=this.#o=0,this.#b.length=0):this.#a=this.#c[g],this.#n.delete(b),this.#i--,g}has(f,g={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:w}=g,m=this.#n.get(f);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return b&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,g={}){let{allowStale:b=this.allowStale}=g,w=this.#n.get(f);if(w===void 0||!b&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#L(f,g,b,w){let m=g===void 0?void 0:this.#e[g];if(this.#t(m))return m;let k=new n,{signal:x}=b;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:b,context:w},E=(T,B=!1)=>{let{aborted:D}=k.signal,U=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(D&&!B?(b.status.fetchAborted=!0,b.status.fetchError=k.signal.reason,U&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),D&&!U&&!B)return A(k.signal.reason);let oe=O;return this.#e[g]===O&&(T===void 0?oe.__staleWhileFetching?this.#e[g]=oe.__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),A(T)),A=T=>{let{aborted:B}=k.signal,D=B&&b.allowStaleOnFetchAbort,U=D||b.allowStaleOnFetchRejection,oe=U||b.noDeleteOnFetchRejection,Y=O;if(this.#e[g]===O&&(!oe||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},C=(T,B)=>{let D=this.#P?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),B),k.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};b.status&&(b.status.fetchDispatched=!0);let O=new Promise(C).then(E,S),j=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return g===void 0?(this.set(f,j,{...v.options,status:void 0}),g=this.#n.get(f)):this.#e[g]=j,j}#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:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:A=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:C=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:B=!1,status:D,signal:U}=g;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let oe={allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:A,allowStaleOnFetchRejection:C,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:D,signal:U},Y=this.#n.get(f);if(Y===void 0){D&&(D.fetch="miss");let W=this.#L(f,Y,oe,T);return W.__returned=W}else{let W=this.#e[Y];if(this.#t(W)){let M=b&&W.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?W.__staleWhileFetching:W.__returned=W}let re=this.#p(Y);if(!B&&!re)return D&&(D.fetch="hit"),this.#C(Y),w&&this.#I(Y),D&&this.#E(D,Y),W;let $=this.#L(f,Y,oe,T),Z=$.__staleWhileFetching!==void 0&&b;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?$.__staleWhileFetching:$.__returned=$}}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.#O;if(!b)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=g,x=this.get(f,k);if(!m&&x!==void 0)return x;let v=b(f,x,{options:k,context:w});return this.set(f,v,k),v}get(f,g={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=g,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],E=this.#t(v);return k&&this.#E(k,x),this.#p(x)?(k&&(k.get="stale"),E?(k&&b&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),k&&b&&(k.returnedStale=!0),b?v:void 0)):(k&&(k.get="hit"),E?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#D(f,g){this.#h[g]=f,this.#c[f]=g}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#h[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 w=this.#n.get(f);if(w!==void 0)if(b=!0,this.#i===1)this.#F(g);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,f,g),this.#u&&this.#s?.push([m,f,g])),this.#n.delete(f),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#b.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.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 w=this.#r[g];this.#k&&this.#m?.(b,w,f),this.#u&&this.#s?.push([b,w,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.#b.length=0,this.#y=0,this.#i=0,this.#u&&this.#s){let g=this.#s,b;for(;b=g?.shift();)this.#g?.(...b)}}};i.LRUCache=p}),mt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};i.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};i.Base=t;var r=class extends t{};i.Container=r}),mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=mt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(o){n.push(o)})}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;i.default=r}),gu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=mt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(o){n.push(o)})}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 o=this.i;for(let a=0;a<o;++a)this.q[a]=this.q[this.j+a];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;i.default=r}),yu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=mt(),t=class extends e.Base{constructor(s=[],n=function(a,l){return a>l?-1:a<l?1:0},o=!0){if(super(),this.v=n,Array.isArray(s))this.C=o?[...s]:s;else{this.C=[];let l=this;s.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(s){let n=this.C[s];for(;s>0;){let o=s-1>>1,a=this.C[o];if(this.v(a,n)<=0)break;this.C[s]=a,s=o}this.C[s]=n}k(s,n){let o=this.C[s];for(;s<n;){let a=s<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,o)>=0)break;this.C[s]=c,s=a}this.C[s]=o}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;i.default=r}),xi=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=mt(),t=class extends e.Container{},r=t;i.default=r}),gt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Es=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=mt(),t=gt(),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)}};i.RandomIterator=r}),bu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=Es();function r(a){return a&&a.t?a:{default:a}}var s=class wc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new wc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.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(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new s(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},o=n;i.default=o}),vu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(xi()),t=mt(),r=gt();function s(l){return l&&l.t?l:{default:l}}var n=class kc extends t.ContainerIterator{constructor(c,u,d,p){super(p),this.o=c,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new kc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let y=1;y<l;++y)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=o;i.default=a}),wu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=Es();function r(a){return a&&a.t?a:{default:a}}var s=class _c extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new _c(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,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 d=this;a.forEach(function(p){d.pushBack(p)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new 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(a){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]=a,this.i}popBack(){if(this.i===0)return;let a=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,a}pushFront(a){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]=a,this.i}popFront(){if(this.i===0)return;let a=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,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new s(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),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 l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},o=n;i.default=o}),ku=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.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}};i.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)}};i.TreeNodeEnableIndex=t}),As=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=ku(),t=mt(),r=gt(),s=class extends t.Container{constructor(o=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=o,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let y=this.he(d);if(y){let{parentNode:f,grandParent:g,curNode:b}=y;f.ie(),g.ie(),b.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)o=o.W;else if(c>0)l=o,o=o.U;else return o}return l}Z(o,a){let l=this.h;for(;o;)this.v(o.u,a)<=0?o=o.W:(l=o,o=o.U);return l}$(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)l=o,o=o.W;else if(c>0)o=o.U;else return o}return l}rr(o,a){let l=this.h;for(;o;)this.v(o.u,a)<0?(l=o,o=o.W):o=o.U;return l}ue(o){for(;;){let a=o.tt;if(a===this.h)return;if(o.ee===1){o.ee=0;return}if(o===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,o=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,o=a)}}}fe(o){if(this.i===1)return this.clear(),this.h;let a=o;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[o.u,a.u]=[a.u,o.u],[o.l,a.l]=[a.l,o.l],o=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(o,a){return o===void 0?!1:this.oe(o.U,a)||a(o)?!0:this.oe(o.W,a)}he(o){for(;;){let a=o.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.W){if(o.ee=0,o.U&&(o.U.tt=a),o.W&&(o.W.tt=l),a.W=o.U,l.U=o.W,o.U=a,o.W=l,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.U){if(o.ee=0,o.U&&(o.U.tt=l),o.W&&(o.W.tt=a),l.W=o.U,a.U=o.W,o.U=l,o.W=a,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(o,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(o,a),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,d=this.v(u.u,o);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(o,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,y=this.v(p.u,o);if(y===0){p.l=a;return}else if(y<0)p.W=new this.re(o,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let f=l.o;if(f!==this.h){let g=this.v(f.u,o);if(g===0){f.l=a;return}else if(g>0){let b=f.L(),w=this.v(b.u,o);if(w===0){b.l=a;return}else w<0&&(c=new this.re(o,a),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,o);if(f>0){if(c.U===void 0){c.U=new this.re(o,a),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(o,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(o,a){for(;o;){let l=this.v(o.u,a);if(l<0)o=o.W;else if(l>0)o=o.U;else return o}return o||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(o,a){let l=o.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return o===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(o){if(this.i===0)return!1;let a=this.I(this.Y,o);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(o){let a=o.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return o.iteratorType===0?l&&o.next():(!l||a.U===void 0)&&o.next(),this.V(a),o}forEach(o){let a=0;for(let l of this)o(l,a++,this)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===o){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let o=function(a){return a?Math.max(o(a.U),o(a.W))+1:0};return o(this.Y)}},n=s;i.default=n}),Is=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=mt(),t=gt(),r=class extends e.ContainerIterator{constructor(n,o,a){super(a),this.o=n,this.h=o,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,o=this.h.tt;if(n===this.h)return o?o.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==o;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},s=r;i.default=s}),_u=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(As()),t=s(Is()),r=gt();function s(l){return l&&l.t?l:{default:l}}var n=class xc extends t.default{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new xc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.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(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),xu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(As()),t=s(Is()),r=gt();function s(l){return l&&l.t?l:{default:l}}var n=class Sc extends t.default{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Sc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.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 l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),Ts=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Cs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=mt(),t=s(Ts()),r=gt();function s(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,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})}};i.HashContainerIterator=n;var o=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(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};i.HashContainer=o}),Su=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Cs(),t=gt(),r=class Ec extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new Ec(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(o=[]){super();let a=this;o.forEach(function(l){a.insert(l)})}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(o,a){return this.M(o,void 0,a)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=this.p;for(;o--;)a=a.B;return a.u}find(o,a){let l=this.I(o,a);return new r(l,this.h,this)}forEach(o){let a=0,l=this.p;for(;l!==this.h;)o(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield o.u,o=o.B}).bind(this)()}},n=s;i.default=n}),Eu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Cs(),t=s(Ts()),r=gt();function s(l){return l&&l.t?l:{default:l}}var n=class Ac extends e.HashContainerIterator{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,p){if(d!=="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)}},o=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.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(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=o;i.default=a}),Au=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(i,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(i,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(i,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(i,"Vector",{enumerable:!0,get:function(){return s.default}});var e=d(mu()),t=d(gu()),r=d(yu()),s=d(bu()),n=d(vu()),o=d(wu()),a=d(_u()),l=d(xu()),c=d(Su()),u=d(Eu());function d(p){return p&&p.t?p:{default:p}}}),Iu=pe((i,e)=>{le(),ue(),ce();var t=Au().OrderedSet,r=pt()("number-allocator:trace"),s=pt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function o(a,l){if(!(this instanceof o))return new o(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}o.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},o.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},o.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},o.prototype.free=function(a){if(a<this.min||a>this.max){s("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},o.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=o}),Ps=pe((i,e)=>{le(),ue(),ce();var t=Iu();e.exports.NumberAllocator=t}),Tu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=pu(),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 o=this.aliasToTopic.get(n);return o&&delete this.topicToAlias[o],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]}};i.default=r}),Cu=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(i,"__esModule",{value:!0});var t=Sr(),r=e(Tu()),s=zt(),n=(o,a)=>{o.log("_handleConnack");let{options:l}=o,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(o.connackTimer),delete o.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){o.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(o.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)o.reconnecting=!1,o._onConnect(a);else if(c>0){let u=new s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);o.emit("error",u),o.options.reconnectOnConnackError&&o._cleanUp(!0)}};i.default=n}),Pu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s:t.noop,{messageId:o}=r,a={cmd:"pubcomp",messageId:o};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,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(a,n)}))})};i.default=e}),Ou=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(du()),r=e(fu()),s=e(Cu()),n=e(Sr()),o=e(Pu()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,o.default)(l,c,u);break;case"connack":(0,s.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};i.default=a}),Os=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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(){}};i.default=e}),Mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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={}}};i.default=e}),Ru=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=void 0;var t=e((Ot(),Ne(wt))),r=zt(),s=class{};i.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),Er=pe((i,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}),Lu=pe((i,e)=>{le(),ue(),ce();var t=Er().default;function r(s,n){if(t(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,n||"default");if(t(a)!="object")return a;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}),Nu=pe((i,e)=>{le(),ue(),ce();var t=Er().default,r=Lu();function s(n){var o=r(n,"string");return t(o)=="symbol"?o:o+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),ju=pe((i,e)=>{le(),ue(),ce();var t=Nu();function r(s,n,o){return(n=t(n))in s?Object.defineProperty(s,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):s[n]=o,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Uu=pe((i,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}),Bu=pe((i,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 o,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(o=l.call(n)).done)&&(u.push(o.value),u.length!==s);d=!0);}catch(y){p=!0,a=y}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((i,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,o=Array(s);n<s;n++)o[n]=r[n];return o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((i,e)=>{le(),ue(),ce();var t=Du();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var o={}.toString.call(s).slice(8,-1);return o==="Object"&&s.constructor&&(o=s.constructor.name),o==="Map"||o==="Set"?Array.from(s):o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((i,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}),qu=pe((i,e)=>{le(),ue(),ce();var t=Uu(),r=Bu(),s=Fu(),n=$u();function o(a,l){return t(a)||r(a,l)||s(a,l)||n()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ms=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(i,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,o=536870912,a=o*2,l=function(y,f){return function(g){var b=f.get(g),w=b===void 0?g.size:b<a?b+1:0;if(!g.has(w))return y(g,w);if(g.size<o){for(;g.has(w);)w=Math.floor(Math.random()*a);return y(g,w)}if(g.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;g.has(w);)w=Math.floor(Math.random()*n);return y(g,w)}},c=new WeakMap,u=s(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Hu=pe((i,e)=>{le(),ue(),ce();function t(s,n,o,a,l,c,u){try{var d=s[c](u),p=d.value}catch(y){return void o(y)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(s){return function(){var n=this,o=arguments;return new Promise(function(a,l){var c=s.apply(n,o);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((i,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}),Ls=pe((i,e)=>{le(),ue(),ce();function t(r,s,n,o){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(y,f){t(l,y,function(g){return this._invoke(y,f,g)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ns=pe((i,e)=>{le(),ue(),ce();var t=Ls();function r(){var s,n,o=typeof Symbol=="function"?Symbol:{},a=o.iterator||"@@iterator",l=o.toStringTag||"@@toStringTag";function c(w,m,k,x){var v=m&&m.prototype instanceof d?m:d,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,A,C){var O,j,T,B=0,D=C||[],U=!1,oe={p:0,n:0,v:s,a:Y,f:Y.bind(s,4),d:function(W,re){return O=W,j=0,T=s,oe.n=re,u}};function Y(W,re){for(j=W,T=re,n=0;!U&&B&&!$&&n<D.length;n++){var $,Z=D[n],M=oe.p,Q=Z[2];W>3?($=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=s):Z[0]<=M&&(($=W<2&&M<Z[1])?(j=0,oe.v=re,oe.n=Z[1]):M<Q&&($=W<3||Z[0]>re||re>Q)&&(Z[4]=W,Z[5]=re,oe.n=Q,j=0))}if($||W>1)return u;throw U=!0,re}return function(W,re,$){if(B>1)throw TypeError("Generator is already running");for(U&&re===1&&Y(re,$),j=re,T=$;(n=j<2?s:T)||!U;){O||(j?j<3?(j>1&&(oe.n=-1),Y(j,T)):oe.n=T:oe.v=T);try{if(B=2,O){if(j||(W="next"),n=O[W]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=O.return)&&n.call(O),j<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),j=1);O=s}else if((n=(U=oe.n<0)?T:S.call(A,oe))!==u)break}catch(Z){O=s,j=1,T=Z}finally{B=1}}return{value:n,done:U}}})(w,k,x),!0),E}var u={};function d(){}function p(){}function y(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),g=y.prototype=d.prototype=Object.create(f);function b(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,y):(w.__proto__=y,t(w,l,"GeneratorFunction")),w.prototype=Object.create(g),w}return p.prototype=y,t(g,"constructor",y),t(y,"constructor",p),p.displayName="GeneratorFunction",t(y,l,"GeneratorFunction"),t(g),t(g,l,"Generator"),t(g,a,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}),js=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=Ls();function s(n,o){function a(c,u,d,p){try{var y=n[c](u),f=y.value;return f instanceof t?o.resolve(f.v).then(function(g){a("next",g,d,p)},function(g){a("throw",g,d,p)}):o.resolve(f).then(function(g){y.value=g,d(y)},function(g){return a("throw",g,d,p)})}catch(g){p(g)}}var l;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new o(function(y,f){a(c,d,y,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Us=pe((i,e)=>{le(),ue(),ce();var t=Ns(),r=js();function s(n,o,a,l,c){return new r(t().w(n,o,a,l),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((i,e)=>{le(),ue(),ce();var t=Us();function r(s,n,o,a,l){var c=t(s,n,o,a,l);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}),zu=pe((i,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var o in s)n.unshift(o);return function a(){for(;n.length;)if((o=n.pop())in s)return a.value=o,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Vu=pe((i,e)=>{le(),ue(),ce();var t=Er().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],o=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&o>=s.length&&(s=void 0),{value:s&&s[o++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ku=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=Ns(),s=Wu(),n=Us(),o=js(),a=zu(),l=Vu();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function y(b){var w=typeof b=="function"&&b.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function g(b){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,f[x],v)},delegateYield:function(x,v,E){return w.resultName=v,m(k.d,l(x),E)},finish:function(x){return m(k.f,x)}},m=function(x,v,E){k.p=w.prev,k.n=w.next;try{return x(v,E)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return b.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(b,w,m,k){return u.w(g(b),w,m,k&&k.reverse())},isGeneratorFunction:y,mark:u.m,awrap:function(b,w){return new t(b,w)},AsyncIterator:o,async:function(b,w,m,k,x){return(y(w)?n:s)(g(b),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Gu=pe((i,e)=>{le(),ue(),ce();var t=Ku()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Yu=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,ju(),qu(),Ms(),Hu(),Gu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(i,function(t,r,s,n,o,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%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 d(d({},m),{},{connect:function(k){var x=k.call;return o(a.mark(function v(){var E,S,A,C;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,A=E.port2,O.next=1,x("connect",{port:S},[S]);case 1:return C=O.sent,c.set(A,C),O.abrupt("return",A);case 2:case"end":return O.stop()}},v)}))},disconnect:function(k){var x=k.call;return(function(){var v=o(a.mark(function E(S){var A;return a.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:if(A=c.get(S),A!==void 0){C.next=1;break}throw new Error("The given port is not connected.");case 1:return C.next=2,x("disconnect",{portId:A});case 2:case"end":return C.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(k){var x=k.call;return function(){return x("isSupported")}}})};function y(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%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 k=new Map;return g.set(m,k),k},w=function(m){var k=p(m);return function(x){var v=b(x);x.addEventListener("message",function(D){var U=D.data,oe=U.id;if(oe!==null&&v.has(oe)){var Y=v.get(oe),W=Y.reject,re=Y.resolve;v.delete(oe),U.error===void 0?re(U.result):W(new Error(U.error.message))}}),l(x)&&x.start();for(var E=function(D){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:Y}),U===null?x.postMessage({id:re,method:D},oe):x.postMessage({id:re,method:D,params:U},oe)})},S=function(D,U){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},oe)},A={},C=0,O=Object.entries(k);C<O.length;C++){var j=s(O[C],2),T=j[0],B=j[1];A=f(f({},A),{},r({},T,B({call:E,notify:S})))}return f({},A)}};t.createBroker=w})}),Ju=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Er(),Yu(),Ms()):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))})(i,function(t,r,s,n){var o=new Map([[0,null]]),a=new Map([[0,null]]),l=s.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){o.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),b=2;b<f;b++)g[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(o);o.set(m,w);var k=function(){return d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=o.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,g),o.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,g=new Array(f>2?f-2:0),b=2;b<f;b++)g[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:y,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),p.apply(void 0,g))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),Qu=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Ju()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(i,function(t,r){var s=function(d,p){var y=null;return function(){if(y!==null)return y;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),g=URL.createObjectURL(f);return y=d(g),setTimeout(function(){return URL.revokeObjectURL(g)}),y}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,o=s(r.load,n),a=function(d){return o().clearInterval(d)},l=function(d){return o().clearTimeout(d)},c=function(){var d;return(d=o()).setInterval.apply(d,arguments)},u=function(){var d;return(d=o()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Ar=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.isReactNativeBrowser=i.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&je?.versions?!Object.prototype.hasOwnProperty.call(je.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();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=s}),Xu=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var y=Object.getOwnPropertyDescriptor(u,d);(!y||("get"in y?!u.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,y)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=i&&i.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=i&&i.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var y in d)Object.prototype.hasOwnProperty.call(d,y)&&(p[p.length]=y);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),y=0;y<p.length;y++)p[y]!=="default"&&e(d,u,p[y]);return t(d,u),d}})();Object.defineProperty(i,"__esModule",{value:!0});var s=Qu(),n=r(Ar()),o={set:s.setInterval,clear:s.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return o;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?o:a}};i.default=l}),Bs=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(Xu()),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)}};i.default=r}),Si=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(v,E,S,A){A===void 0&&(A=S);var C=Object.getOwnPropertyDescriptor(E,S);(!C||("get"in C?!E.__esModule:C.writable||C.configurable))&&(C={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,A,C)}:function(v,E,S,A){A===void 0&&(A=S),v[A]=E[S]}),t=i&&i.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=i&&i.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var A=[];for(var C in S)Object.prototype.hasOwnProperty.call(S,C)&&(A[A.length]=C);return A},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var A=v(E),C=0;C<A.length;C++)A[C]!=="default"&&e(S,E,A[C]);return t(S,E),S}})(),s=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=s(lu()),o=Rt(),a=s(uu()),l=s(pt()),c=r(xs()),u=s(Ss()),d=s(Ou()),p=s(Os()),y=s(Mu()),f=zt(),g=Ru(),b=s(Bs()),w=r(Ar()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,f.nextTick)(()=>{E(...v)})}),k={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 Uo 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 A in k)typeof this.options[A]>"u"?this.options[A]=k[A]:this.options[A]=S[A];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Uo.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.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:Uo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...A)=>{A[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:A}=this,C=()=>{let O=A.shift();this.log("deliver :: entry %o",O);let j=null;if(!O){this._resubscribe();return}j=O.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,B=>{O.cb&&O.cb(B),C()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),C())};this.log("connect :: sending queued packets"),C()}),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 o.Writable,S=n.default.parser(this.options),A=null,C=[];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."),C.push(D)});let O=()=>{this.log("work :: getting next packet in queue");let D=C.shift();if(D)this.log("work :: packet pulled from queue"),(0,d.default)(this,D,j);else{this.log("work :: no packets in queue");let U=A;A=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(C.length)(0,f.nextTick)(O);else{let D=A;A=null,D()}};E._write=(D,U,oe)=>{A=oe,this.log("writable stream :: parsing buffer"),S.parse(D),O()};let T=D=>{this.log("streamErrorHandler :: error",D.message),D.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",D)):this.noop(D)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(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 B={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&&(B.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(B.properties||(B.properties={}),this.topicAliasRecv&&(B.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(B),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,A,C){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof A=="function"&&(C=A,A=null),A=A||{},A={qos:0,retain:!1,dup:!1,...A};let{qos:j,retain:T,dup:B,properties:D,cbStorePut:U}=A;if(this._checkDisconnecting(C))return this;let oe=()=>{let Y=0;if((j===1||j===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:Y,dup:B};switch(O.protocolVersion===5&&(W.properties=D),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:C||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,C,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:A.cbStorePut,callback:C}),this}publishAsync(E,S,A){return new Promise((C,O)=>{this.publish(E,S,A,(j,T)=>{j?O(j):C(T)})})}subscribe(E,S,A){let C=this.options.protocolVersion;typeof S=="function"&&(A=S),A=A||this.noop;let O=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,j=Object.keys(E));let T=c.validateTopics(j);if(T!==null)return m(A,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(A))return this.log("subscribe: discconecting true"),this;let B={qos:0};C===5&&(B.nl=!1,B.rap=!1,B.rh=0),S={...B,...S};let{properties:D}=S,U=[],oe=(re,$)=>{if($=$||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<$.qos||O){let Z={topic:re,qos:$.qos};C===5&&(Z.nl=$.nl,Z.rap=$.rap,Z.rh=$.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),oe(re)}):Object.keys(E).forEach(re=>{this.log("subscribe: object topic %s, %o",re,E[re]),oe(re,E[re])}),!U.length)return A(null,[]),this;let Y=(re,$)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:$};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(ye=>{if(this.options.reconnectPeriod>0){let te={qos:ye.qos};C===5&&(te.nl=ye.nl||!1,te.rap=ye.rap||!1,te.rh=ye.rh||0,te.properties=ye.properties),this._resubscribeTopics[ye.topic]=te,Q.push(ye.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,ye)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:K}=we;for(let N=0;N<K.length;N+=1)re[N].qos=K[N]}te?ye(new f.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},W=()=>{let re=this.options.subscribeBatchSize??U.length,$=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;$.push(Y(M,Q))}return Promise.all($).then(Z=>{A(null,U,Z.at(-1))}).catch(Z=>{A(Z,U,Z.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:A}),this}subscribeAsync(E,S){return new Promise((A,C)=>{this.subscribe(E,S,(O,j)=>{O?C(O):A(j)})})}unsubscribe(E,S,A){typeof E=="string"&&(E=[E]),typeof S=="function"&&(A=S),A=A||this.noop;let C=c.validateTopics(E);if(C!==null)return m(A,new Error(`Invalid topic ${C}`)),this;if(this._checkDisconnecting(A))return this;let O=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(B=>{delete this._resubscribeTopics[B]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:A},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:A}),this}unsubscribeAsync(E,S){return new Promise((A,C)=>{this.unsubscribe(E,S,(O,j)=>{O?C(O):A(j)})})}end(E,S,A){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(A=A||S,S=E,E=!1),typeof S!="object"&&(A=A||S,S=null),this.log("end :: cb? %s",!!A),(!A||typeof A!="function")&&(A=this.noop);let C=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),A){let B=j||T;this.log("end :: closeStores: invoking callback with args"),A(B)}})}),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)(C)},S)};return this.disconnecting?(A(),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,S){return new Promise((A,C)=>{this.end(E,S,O=>{O?C(O):A()})})}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 A=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,A),A.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(A=this.topicAliasSend.getTopicByAlias(S),typeof A>"u")return new Error("Unregistered Topic Alias");E.topic=A}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,A={}){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 C={cmd:"disconnect",...A};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(C,()=>{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,A){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let C=E,O;if(C.cmd==="publish"&&(C=(0,a.default)(E),O=this._removeTopicAliasAndRecoverTopicName(C),O))return S&&S(O);this.outgoingStore.put(C,j=>{if(j)return S&&S(j);A(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let A=E.topic.toString();if(this.topicAliasSend)if(S){if(A.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",A,S),!this.topicAliasSend.put(A,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,S),new Error("Sending Topic Alias out of range")}else A.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(A),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",A,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(A,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",A,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(A),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",A,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",A,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 A=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",A),!A&&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,A,C){this.log("_sendPacket :: (%s) :: start",this.options.clientId),A=A||this.noop,S=S||this.noop;let O=this._applyTopicAlias(E);if(O){S(O);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,A);return}if(C){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,A);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,A);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,A){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),A=A||this.noop;let C=E;if(C.cmd==="publish"){C=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(C);if(j)return S&&S(j)}let O=C.qos||0;O===0&&this.queueQoSZero||C.cmd!=="publish"?this.queue.push({packet:C,cb:S}):O>0?(S=this.outgoing[C.messageId]?this.outgoing[C.messageId].cb:null,this.outgoingStore.put(C,j=>{if(j)return S&&S(j);A()})):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 A={};A[E[S]]=this._resubscribeTopics[E[S]],A.resubscribe=!0,this.subscribe(A,{properties:A[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 A=this.outgoingStore.createStream(),C=()=>{A.destroy(),A=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",C),A.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",C),this.emit("error",T)});let j=()=>{if(!A)return;let T=A.read(1),B;if(!T){A.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(B=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(D,U){B&&B(D,U),j()}},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)):A.destroy&&A.destroy()};A.on("end",()=>{let T=!0;for(let B in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[B]){T=!1;break}this.removeListener("close",C),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),j()};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},(A,C)=>{S(A,C),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};i.default=x}),Zu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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()}};i.default=t});function ed(){if(Ei)return Ir;Ei=!0;let i=2147483647,e=36,t=1,r=26,s=38,n=700,o=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},y=e-t,f=Math.floor,g=String.fromCharCode;function b(O){throw new RangeError(p[O])}function w(O,j){let T=[],B=O.length;for(;B--;)T[B]=j(O[B]);return T}function m(O,j){let T=O.split("@"),B="";T.length>1&&(B=T[0]+"@",O=T[1]),O=O.replace(d,".");let D=O.split("."),U=w(D,j).join(".");return B+U}function k(O){let j=[],T=0,B=O.length;for(;T<B;){let D=O.charCodeAt(T++);if(D>=55296&&D<=56319&&T<B){let U=O.charCodeAt(T++);(U&64512)==56320?j.push(((D&1023)<<10)+(U&1023)+65536):(j.push(D),T--)}else j.push(D)}return j}let x=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,j){return O+22+75*(O<26)-((j!=0)<<5)},S=function(O,j,T){let B=0;for(O=T?f(O/n):O>>1,O+=f(O/j);O>y*r>>1;B+=e)O=f(O/y);return f(B+(y+1)*O/(O+s))},A=function(O){let j=[],T=O.length,B=0,D=a,U=o,oe=O.lastIndexOf(l);oe<0&&(oe=0);for(let Y=0;Y<oe;++Y)O.charCodeAt(Y)>=128&&b("not-basic"),j.push(O.charCodeAt(Y));for(let Y=oe>0?oe+1:0;Y<T;){let W=B;for(let $=1,Z=e;;Z+=e){Y>=T&&b("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&b("invalid-input"),M>f((i-B)/$)&&b("overflow"),B+=M*$;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let ye=e-Q;$>f(i/ye)&&b("overflow"),$*=ye}let re=j.length+1;U=S(B-W,re,W==0),f(B/re)>i-D&&b("overflow"),D+=f(B/re),B%=re,j.splice(B++,0,D)}return String.fromCodePoint(...j)},C=function(O){let j=[];O=k(O);let T=O.length,B=a,D=0,U=o;for(let W of O)W<128&&j.push(g(W));let oe=j.length,Y=oe;for(oe&&j.push(l);Y<T;){let W=i;for(let $ of O)$>=B&&$<W&&(W=$);let re=Y+1;W-B>f((i-D)/re)&&b("overflow"),D+=(W-B)*re,B=W;for(let $ of O)if($<B&&++D>i&&b("overflow"),$===B){let Z=D;for(let M=e;;M+=e){let Q=M<=U?t:M>=U+r?r:M-U;if(Z<Q)break;let ye=Z-Q,te=e-Q;j.push(g(E(Q+ye%te,0))),Z=f(ye/te)}j.push(g(E(Z,0))),U=S(D,re,Y===oe),D=0,++Y}++D,++B}return j.join("")};return Ir={version:"2.3.1",ucs2:{decode:k,encode:x},decode:A,encode:C,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+C(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?A(j.slice(4).toLowerCase()):j})}},Ir}var Ir,Ei,_t,td=Ye(()=>{le(),ue(),ce(),Ir={},Ei=!1,_t=ed(),_t.decode,_t.encode,_t.toASCII,_t.toUnicode,_t.ucs2,_t.version});function rd(){return Ci||(Ci=!0,Ti=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var i={},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;i[e]=r;for(e in i)return!1;if(typeof Object.keys=="function"&&Object.keys(i).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(i).length!==0)return!1;var s=Object.getOwnPropertySymbols(i);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(i,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(i,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ti}function nd(){return Oi||(Oi=!0,Pi=Error),Pi}function id(){return Ri||(Ri=!0,Mi=EvalError),Mi}function od(){return Ni||(Ni=!0,Li=RangeError),Li}function sd(){return Ui||(Ui=!0,ji=ReferenceError),ji}function Ds(){return Di||(Di=!0,Bi=SyntaxError),Bi}function sr(){return $i||($i=!0,Fi=TypeError),Fi}function ad(){return Hi||(Hi=!0,qi=URIError),qi}function ld(){if(Wi)return Tr;Wi=!0;var i=typeof Symbol<"u"&&Symbol,e=rd();return Tr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Tr}function cd(){if(zi)return Cr;zi=!0;var i={__proto__:null,foo:{}},e=Object;return Cr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Cr}function ud(){if(Vi)return Pr;Vi=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},o=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Pr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(i+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var b=l.apply(this,s(c,arguments));return Object(b)===b?b:this}return l.apply(a,s(c,arguments))},p=t(0,l.length-c.length),y=[],f=0;f<p;f++)y[f]="$"+f;if(u=Function("binder","return function ("+o(y,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var g=function(){};g.prototype=l.prototype,u.prototype=new g,g.prototype=null}return u},Pr}function Ai(){if(Ki)return Or;Ki=!0;var i=ud();return Or=Function.prototype.bind||i,Or}function dd(){if(Gi)return Mr;Gi=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Ai();return Mr=t.call(i,e),Mr}function Vt(){if(Yi)return Rr;Yi=!0;var i,e=nd(),t=id(),r=od(),s=sd(),n=Ds(),o=sr(),a=ad(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new o},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,y=ld()(),f=cd()(),g=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},w=typeof Uint8Array>"u"||!g?i:g(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":y&&g?g([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?i:Atomics,"%BigInt%":typeof BigInt>"u"?i:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?i:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?i:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?i:Float32Array,"%Float64Array%":typeof Float64Array>"u"?i:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?i:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&g?g(g([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!g?i:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?i:Promise,"%Proxy%":typeof Proxy>"u"?i:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!g?i:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&g?g(""[Symbol.iterator]()):i,"%Symbol%":y?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?i:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?i:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?i:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?i:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?i:WeakMap,"%WeakRef%":typeof WeakRef>"u"?i:WeakRef,"%WeakSet%":typeof WeakSet>"u"?i:WeakSet};if(g)try{null.error}catch(Y){var k=g(g(Y));m["%Error.prototype%"]=k}var x=function Y(W){var re;if(W==="%AsyncFunction%")re=c("async function () {}");else if(W==="%GeneratorFunction%")re=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(W==="%AsyncGenerator%"){var $=Y("%AsyncGeneratorFunction%");$&&(re=$.prototype)}else if(W==="%AsyncIteratorPrototype%"){var Z=Y("%AsyncGenerator%");Z&&g&&(re=g(Z.prototype))}return m[W]=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=Ai(),S=dd(),A=E.call(Function.call,Array.prototype.concat),C=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),j=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),B=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/g,U=function(Y){var W=j(Y,0,1),re=j(Y,-1);if(W==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var $=[];return O(Y,B,function(Z,M,Q,ye){$[$.length]=Q?O(ye,D,"$1"):M||Z}),$},oe=function(Y,W){var re=Y,$;if(S(v,re)&&($=v[re],re="%"+$[0]+"%"),S(m,re)){var Z=m[re];if(Z===b&&(Z=x(re)),typeof Z>"u"&&!W)throw new o("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:$,name:re,value:Z}}throw new n("intrinsic "+Y+" does not exist!")};return Rr=function(Y,W){if(typeof Y!="string"||Y.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new o('"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),$=re.length>0?re[0]:"",Z=oe("%"+$+"%",W),M=Z.name,Q=Z.value,ye=!1,te=Z.alias;te&&($=te[0],C(re,A([0,1],te)));for(var we=1,K=!0;we<re.length;we+=1){var N=re[we],ne=j(N,0,1),z=j(N,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)throw new n("property names with quotes must have matching quotes");if((N==="constructor"||!K)&&(ye=!0),$+="."+N,M="%"+$+"%",S(m,M))Q=m[M];else if(Q!=null){if(!(N in Q)){if(!W)throw new o("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var G=u(Q,N);K=!!G,K&&"get"in G&&!("originalValue"in G.get)?Q=G.get:Q=Q[N]}else K=S(Q,N),Q=Q[N];K&&!ye&&(m[M]=Q)}}return Q},Rr}function Ii(){if(Ji)return Lr;Ji=!0;var i=Vt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Lr=e,Lr}function Fs(){if(Qi)return Nr;Qi=!0;var i=Vt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Nr=e,Nr}function hd(){if(Xi)return jr;Xi=!0;var i=Ii(),e=Ds(),t=sr(),r=Fs();return jr=function(s,n,o){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 a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(s,n);if(i)i(s,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:o,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)s[n]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},jr}function fd(){if(Zi)return Ur;Zi=!0;var i=Ii(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Ur=e,Ur}function pd(){if(eo)return Br;eo=!0;var i=Vt(),e=hd(),t=fd()(),r=Fs(),s=sr(),n=i("%Math.floor%");return Br=function(o,a){if(typeof o!="function")throw new s("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in o&&r){var d=r(o,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(o,"length",a,!0,!0):e(o,"length",a)),o},Br}function md(){if(to)return Kt;to=!0;var i=Ai(),e=Vt(),t=pd(),r=sr(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||i.call(n,s),a=Ii(),l=e("%Math.max%");Kt=function(u){if(typeof u!="function")throw new r("a function is required");var d=o(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return o(i,s,arguments)};return a?a(Kt,"apply",{value:c}):Kt.apply=c,Kt}function gd(){if(ro)return Dr;ro=!0;var i=Vt(),e=md(),t=e(i("String.prototype.indexOf"));return Dr=function(r,s){var n=i(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Dr}var Ti,Ci,Pi,Oi,Mi,Ri,Li,Ni,ji,Ui,Bi,Di,Fi,$i,qi,Hi,Tr,Wi,Cr,zi,Pr,Vi,Or,Ki,Mr,Gi,Rr,Yi,Lr,Ji,Nr,Qi,jr,Xi,Ur,Zi,Br,eo,Kt,to,Dr,ro,yd=Ye(()=>{le(),ue(),ce(),Ti={},Ci=!1,Pi={},Oi=!1,Mi={},Ri=!1,Li={},Ni=!1,ji={},Ui=!1,Bi={},Di=!1,Fi={},$i=!1,qi={},Hi=!1,Tr={},Wi=!1,Cr={},zi=!1,Pr={},Vi=!1,Or={},Ki=!1,Mr={},Gi=!1,Rr={},Yi=!1,Lr={},Ji=!1,Nr={},Qi=!1,jr={},Xi=!1,Ur={},Zi=!1,Br={},eo=!1,Kt={},to=!1,Dr={},ro=!1});function no(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function bd(){!Lt||!Nt||(Lt=!1,Nt.length?rt=Nt.concat(rt):ar=-1,rt.length&&$s())}function $s(){if(!Lt){var i=setTimeout(bd,0);Lt=!0;for(var e=rt.length;e;){for(Nt=rt,rt=[];++ar<e;)Nt&&Nt[ar].run();ar=-1,e=rt.length}Nt=null,Lt=!1,clearTimeout(i)}}function vd(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new qs(i,e)),rt.length===1&&!Lt&&setTimeout($s,0)}function qs(i,e){this.fun=i,this.array=e}function We(){}function wd(i){no("_linkedBinding")}function kd(i){no("dlopen")}function _d(){return[]}function xd(){return[]}function Sd(i,e){if(!i)throw new Error(e||"assertion error")}function Ed(){return!1}function Ad(){return yt.now()/1e3}function io(i){var e=Math.floor((Date.now()-yt.now())*.001),t=yt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=$r)),[r,s]}function xt(){return so}function Id(i){return[]}var rt,Lt,Nt,ar,Hs,Ws,zs,Vs,Ks,Gs,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,Fr,ua,da,ha,fa,pa,ma,ga,ya,ba,va,wa,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,Ma,Ra,La,yt,oo,$r,Na,ja,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,so,Va=Ye(()=>{le(),ue(),ce(),rt=[],Lt=!1,ar=-1,qs.prototype.run=function(){this.fun.apply(null,this.array)},Hs="browser",Ws="x64",zs="browser",Vs={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ks=["/usr/bin/node"],Gs=[],Ys="v16.8.0",Js={},Qs=function(i,e){console.warn((e?e+": ":"")+i)},Xs=function(i){no("binding")},Zs=function(i){return 0},ea=function(){return"/"},ta=function(i){},ra={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},na=We,ia=[],oa={},sa=!1,aa={},la=We,ca=We,Fr=function(){return{}},ua=Fr,da=Fr,ha=We,fa=We,pa=We,ma={},ga={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ya=We,ba=We,va=We,wa=We,ka=We,_a=We,xa=We,Sa=void 0,Ea=void 0,Aa=void 0,Ia=We,Ta=2,Ca=1,Pa="/bin/usr/node",Oa=9229,Ma="node",Ra=[],La=We,yt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},yt.now===void 0&&(oo=Date.now(),yt.timing&&yt.timing.navigationStart&&(oo=yt.timing.navigationStart),yt.now=()=>Date.now()-oo),$r=1e9,io.bigint=function(i){var e=io(i);return typeof BigInt>"u"?e[0]*$r+e[1]:BigInt(e[0]*$r)+BigInt(e[1])},Na=10,ja={},Ua=0,Ba=xt,Da=xt,Fa=xt,$a=xt,qa=xt,Ha=We,Wa=xt,za=xt,so={version:Ys,versions:Js,arch:Ws,platform:zs,release:ra,_rawDebug:na,moduleLoadList:ia,binding:Xs,_linkedBinding:wd,_events:ja,_eventsCount:Ua,_maxListeners:Na,on:xt,addListener:Ba,once:Da,off:Fa,removeListener:$a,removeAllListeners:qa,emit:Ha,prependListener:Wa,prependOnceListener:za,listeners:Id,domain:oa,_exiting:sa,config:aa,dlopen:kd,uptime:Ad,_getActiveRequests:_d,_getActiveHandles:xd,reallyExit:la,_kill:ca,cpuUsage:Fr,resourceUsage:ua,memoryUsage:da,kill:ha,exit:fa,openStdin:pa,allowedNodeEnvironmentFlags:ma,assert:Sd,features:ga,_fatalExceptions:ya,setUncaughtExceptionCaptureCallback:ba,hasUncaughtExceptionCaptureCallback:Ed,emitWarning:Qs,nextTick:vd,_tickCallback:va,_debugProcess:wa,_debugEnd:ka,_startProfilerIdleNotifier:_a,_stopProfilerIdleNotifier:xa,stdout:Sa,stdin:Aa,stderr:Ea,abort:Ia,umask:Zs,chdir:ta,cwd:ea,env:Vs,title:Hs,argv:Ks,execArgv:Gs,pid:Ta,ppid:Ca,execPath:Pa,debugPort:Oa,hrtime:io,argv0:Ma,_preload_modules:Ra,setSourceMapsEnabled:La}});function Td(){if(ao)return qr;ao=!0;var i=so;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,o){for(var a="",l=0,c=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var y=a.lastIndexOf("/");if(y!==a.length-1){y===-1?(a="",l=0):(a=a.slice(0,y),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}o&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,o){var a=o.dir||o.root,l=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+l:a+n+l:l}var s={resolve:function(){for(var n="",o=!1,a,l=arguments.length-1;l>=-1&&!o;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,o=c.charCodeAt(0)===47)}return n=t(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var o=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!o),n.length===0&&!o&&(n="."),n.length>0&&a&&(n+="/"),o?"/"+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,o=0;o<arguments.length;++o){var a=arguments[o];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":s.normalize(n)},relative:function(n,o){if(e(n),e(o),n===o||(n=s.resolve(n),o=s.resolve(o),n===o))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<o.length&&o.charCodeAt(u)===47;++u);for(var d=o.length,p=d-u,y=c<p?c:p,f=-1,g=0;g<=y;++g){if(g===y){if(p>y){if(o.charCodeAt(u+g)===47)return o.slice(u+g+1);if(g===0)return o.slice(u+g)}else c>y&&(n.charCodeAt(a+g)===47?f=g:g===0&&(f=0));break}var b=n.charCodeAt(a+g),w=o.charCodeAt(u+g);if(b!==w)break;b===47&&(f=g)}var m="";for(g=a+f+1;g<=l;++g)(g===l||n.charCodeAt(g)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+o.slice(u+f):(u+=f,o.charCodeAt(u)===47&&++u,o.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var o=n.charCodeAt(0),a=o===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(o=n.charCodeAt(u),o===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(o!==void 0&&o.length>0&&o.length<=n.length){if(o.length===n.length&&o===n)return"";var d=o.length-1,p=-1;for(u=n.length-1;u>=0;--u){var y=n.charCodeAt(u);if(y===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(y===o.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var o=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===46?o===-1?o=d:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||l===-1||u===0||u===1&&o===l-1&&o===a+1?"":n.slice(o,l)},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 o={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return o;var a=n.charCodeAt(0),l=a===47,c;l?(o.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,y=!0,f=n.length-1,g=0;f>=c;--f){if(a=n.charCodeAt(f),a===47){if(!y){d=f+1;break}continue}p===-1&&(y=!1,p=f+1),a===46?u===-1?u=f:g!==1&&(g=1):u!==-1&&(g=-1)}return u===-1||p===-1||g===0||g===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?o.base=o.name=n.slice(1,p):o.base=o.name=n.slice(d,p)):(d===0&&l?(o.name=n.slice(1,u),o.base=n.slice(1,p)):(o.name=n.slice(d,u),o.base=n.slice(d,p)),o.ext=n.slice(u,p)),d>0?o.dir=n.slice(0,d-1):l&&(o.dir="/"),o},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,qr=s,qr}var qr,ao,lo,Cd=Ye(()=>{le(),ue(),ce(),Va(),qr={},ao=!1,lo=Td()}),Ka={};$t(Ka,{URL:()=>il,Url:()=>Za,default:()=>ze,fileURLToPath:()=>Ya,format:()=>el,parse:()=>nl,pathToFileURL:()=>Ja,resolve:()=>tl,resolveObject:()=>rl});function Pd(){if(uo)return Hr;uo=!0;var i=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=i&&e&&typeof e.get=="function"?e.get:null,r=i&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=s&&n&&typeof n.get=="function"?n.get:null,a=s&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,y=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,g=Object.prototype.toString,b=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,A=Array.prototype.join,C=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,B=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,oe=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(V){return V.__proto__}:null);function W(V,ie){if(V===1/0||V===-1/0||V!==V||V&&V>-1e3&&V<1e3||E.call(/e/,ie))return ie;var Ae=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof V=="number"){var Ie=V<0?-O(-V):O(V);if(Ie!==V){var Pe=String(Ie),Re=m.call(ie,Pe.length+1);return k.call(Pe,Ae,"$&_")+"."+k.call(k.call(Re,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ae,"$&_")}var re=Qa,$=re.custom,Z=G($)?$:null;Hr=function V(ie,Ae,Ie,Pe){var Re=Ae||{};if(se(Re,"quoteStyle")&&Re.quoteStyle!=="single"&&Re.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Re,"maxStringLength")&&(typeof Re.maxStringLength=="number"?Re.maxStringLength<0&&Re.maxStringLength!==1/0:Re.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var nt=se(Re,"customInspect")?Re.customInspect:!0;if(typeof nt!="boolean"&&nt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Re,"indent")&&Re.indent!==null&&Re.indent!==" "&&!(parseInt(Re.indent,10)===Re.indent&&Re.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Re,"numericSeparator")&&typeof Re.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var it=Re.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 ae(ie,Re);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ve=String(ie);return it?W(ie,Ve):Ve}if(typeof ie=="bigint"){var ot=String(ie)+"n";return it?W(ie,ot):ot}var Xt=typeof Re.depth>"u"?5:Re.depth;if(typeof Ie>"u"&&(Ie=0),Ie>=Xt&&Xt>0&&typeof ie=="object")return ye(ie)?"[Array]":"[Object]";var st=X(Re,Ie);if(typeof Pe>"u")Pe=[];else if(ee(Pe,ie)>=0)return"[Circular]";function Ze(at,Tt,Ft){if(Tt&&(Pe=C.call(Pe),Pe.push(Tt)),Ft){var lt={depth:Re.depth};return se(Re,"quoteStyle")&&(lt.quoteStyle=Re.quoteStyle),V(at,lt,Ie+1,Pe)}return V(at,Re,Ie+1,Pe)}if(typeof ie=="function"&&!we(ie)){var nn=q(ie),Zt=_e(ie,Ze);return"[Function"+(nn?": "+nn:" (anonymous)")+"]"+(Zt.length>0?" { "+A.call(Zt,", ")+" }":"")}if(G(ie)){var dr=D?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):B.call(ie);return typeof ie=="object"&&!D?h(dr):dr}if(ve(ie)){for(var P="<"+v.call(String(ie.nodeName)),L=ie.attributes||[],ke=0;ke<L.length;ke++)P+=" "+L[ke].name+"="+M(Q(L[ke].value),"double",Re);return P+=">",ie.childNodes&&ie.childNodes.length&&(P+="..."),P+="</"+v.call(String(ie.nodeName))+">",P}if(ye(ie)){if(ie.length===0)return"[]";var xe=_e(ie,Ze);return st&&!F(xe)?"["+de(xe,st)+"]":"[ "+A.call(xe,", ")+" ]"}if(K(ie)){var Ee=_e(ie,Ze);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+A.call(S.call("[cause]: "+Ze(ie.cause),Ee),", ")+" }":Ee.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+A.call(Ee,", ")+" }"}if(typeof ie=="object"&&nt){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Xt-Ie});if(nt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(at,Tt){Fe.push(Ze(Tt,ie,!0)+" => "+Ze(at,ie))}),I("Map",t.call(ie),Fe,st)}if(H(ie)){var Ge=[];return a&&a.call(ie,function(at){Ge.push(Ze(at,ie))}),I("Set",o.call(ie),Ge,st)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(be(ie))return _("WeakRef");if(ne(ie))return h(Ze(Number(ie)));if(J(ie))return h(Ze(j.call(ie)));if(z(ie))return h(f.call(ie));if(N(ie))return h(Ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Wr<"u"&&ie===Wr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=_e(ie,Ze),hr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,fr=ie instanceof Object?"":"null prototype",pr=!hr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):fr?"Object":"",on=hr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Dt=on+(pr||fr?"["+A.call(S.call([],pr||[],fr||[]),": ")+"] ":"");return et.length===0?Dt+"{}":st?Dt+"{"+de(et,st)+"}":Dt+"{ "+A.call(et,", ")+" }"}return String(ie)};function M(V,ie,Ae){var Ie=(Ae.quoteStyle||ie)==="double"?'"':"'";return Ie+V+Ie}function Q(V){return k.call(String(V),/"/g,"&quot;")}function ye(V){return R(V)==="[object Array]"&&(!U||!(typeof V=="object"&&U in V))}function te(V){return R(V)==="[object Date]"&&(!U||!(typeof V=="object"&&U in V))}function we(V){return R(V)==="[object RegExp]"&&(!U||!(typeof V=="object"&&U in V))}function K(V){return R(V)==="[object Error]"&&(!U||!(typeof V=="object"&&U in V))}function N(V){return R(V)==="[object String]"&&(!U||!(typeof V=="object"&&U in V))}function ne(V){return R(V)==="[object Number]"&&(!U||!(typeof V=="object"&&U in V))}function z(V){return R(V)==="[object Boolean]"&&(!U||!(typeof V=="object"&&U in V))}function G(V){if(D)return V&&typeof V=="object"&&V instanceof Symbol;if(typeof V=="symbol")return!0;if(!V||typeof V!="object"||!B)return!1;try{return B.call(V),!0}catch{}return!1}function J(V){if(!V||typeof V!="object"||!j)return!1;try{return j.call(V),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(V){return V in(this||Wr)};function se(V,ie){return ge.call(V,ie)}function R(V){return g.call(V)}function q(V){if(V.name)return V.name;var ie=w.call(b.call(V),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(V,ie){if(V.indexOf)return V.indexOf(ie);for(var Ae=0,Ie=V.length;Ae<Ie;Ae++)if(V[Ae]===ie)return Ae;return-1}function he(V){if(!t||!V||typeof V!="object")return!1;try{t.call(V);try{o.call(V)}catch{return!0}return V instanceof Map}catch{}return!1}function fe(V){if(!c||!V||typeof V!="object")return!1;try{c.call(V,c);try{d.call(V,d)}catch{return!0}return V instanceof WeakMap}catch{}return!1}function be(V){if(!y||!V||typeof V!="object")return!1;try{return y.call(V),!0}catch{}return!1}function H(V){if(!o||!V||typeof V!="object")return!1;try{o.call(V);try{t.call(V)}catch{return!0}return V instanceof Set}catch{}return!1}function me(V){if(!d||!V||typeof V!="object")return!1;try{d.call(V,d);try{c.call(V,c)}catch{return!0}return V instanceof WeakSet}catch{}return!1}function ve(V){return!V||typeof V!="object"?!1:typeof HTMLElement<"u"&&V instanceof HTMLElement?!0:typeof V.nodeName=="string"&&typeof V.getAttribute=="function"}function ae(V,ie){if(V.length>ie.maxStringLength){var Ae=V.length-ie.maxStringLength,Ie="... "+Ae+" more character"+(Ae>1?"s":"");return ae(m.call(V,0,ie.maxStringLength),ie)+Ie}var Pe=k.call(k.call(V,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return M(Pe,"single",ie)}function Oe(V){var ie=V.charCodeAt(0),Ae={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ae?"\\"+Ae:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function h(V){return"Object("+V+")"}function _(V){return V+" { ? }"}function I(V,ie,Ae,Ie){var Pe=Ie?de(Ae,Ie):A.call(Ae,", ");return V+" ("+ie+") {"+Pe+"}"}function F(V){for(var ie=0;ie<V.length;ie++)if(ee(V[ie],`
4
- `)>=0)return!1;return!0}function X(V,ie){var Ae;if(V.indent===" ")Ae=" ";else if(typeof V.indent=="number"&&V.indent>0)Ae=A.call(Array(V.indent+1)," ");else return null;return{base:Ae,prev:A.call(Array(ie+1),Ae)}}function de(V,ie){if(V.length===0)return"";var Ae=`
5
- `+ie.prev+ie.base;return Ae+A.call(V,","+Ae)+`
6
- `+ie.prev}function _e(V,ie){var Ae=ye(V),Ie=[];if(Ae){Ie.length=V.length;for(var Pe=0;Pe<V.length;Pe++)Ie[Pe]=se(V,Pe)?ie(V[Pe],V):""}var Re=typeof T=="function"?T(V):[],nt;if(D){nt={};for(var it=0;it<Re.length;it++)nt["$"+Re[it]]=Re[it]}for(var Ve in V)se(V,Ve)&&(Ae&&String(Number(Ve))===Ve&&Ve<V.length||D&&nt["$"+Ve]instanceof Symbol||(E.call(/[^\w$]/,Ve)?Ie.push(ie(Ve,V)+": "+ie(V[Ve],V)):Ie.push(Ve+": "+ie(V[Ve],V))));if(typeof T=="function")for(var ot=0;ot<Re.length;ot++)oe.call(V,Re[ot])&&Ie.push("["+ie(Re[ot])+"]: "+ie(V[Re[ot]],V));return Ie}return Hr}function Od(){if(ho)return zr;ho=!0;var i=Vt(),e=gd(),t=Pd(),r=sr(),s=i("%WeakMap%",!0),n=i("%Map%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,w){for(var m=b,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=b.next,b.next=k,k},y=function(b,w){var m=p(b,w);return m&&m.value},f=function(b,w,m){var k=p(b,w);k?k.value=m:b.next={key:w,next:b.next,value:m}},g=function(b,w){return!!p(b,w)};return zr=function(){var b,w,m,k={assert:function(x){if(!k.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 o(b,x)}else if(n){if(w)return c(w,x)}else if(m)return y(m,x)},has:function(x){if(s&&x&&(typeof x=="object"||typeof x=="function")){if(b)return l(b,x)}else if(n){if(w)return d(w,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),a(b,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return k},zr}function co(){if(fo)return Vr;fo=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Vr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Vr}function Ga(){if(po)return Kr;po=!0;var i=co(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],w=0;w<256;++w)b.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return b})(),s=function(b){for(;b.length>1;){var w=b.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(b,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<b.length;++k)typeof b[k]<"u"&&(m[k]=b[k]);return m},o=function b(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=b(S,v,k):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=b(v[E],S,k):v[E]=S,v},x)},a=function(b,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},b)},l=function(b,w,m){var k=b.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(b,w,m,k,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 A=v.length>=c?v.slice(S,S+c):v,C=[],O=0;O<A.length;++O){var j=A.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===i.RFC1738&&(j===40||j===41)){C[C.length]=A.charAt(O);continue}if(j<128){C[C.length]=r[j];continue}if(j<2048){C[C.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){C[C.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|A.charCodeAt(O)&1023),C[C.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=C.join("")}return E},d=function(b){for(var w=[{obj:{o:b},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var A=E[S],C=v[A];typeof C=="object"&&C!==null&&m.indexOf(C)===-1&&(w.push({obj:v,prop:A}),m.push(C))}return s(w),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,w){return[].concat(b,w)},g=function(b,w){if(t(b)){for(var m=[],k=0;k<b.length;k+=1)m.push(w(b[k]));return m}return w(b)};return Kr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:o},Kr}function Md(){if(mo)return Gr;mo=!0;var i=Od(),e=Ga(),t=co(),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,o=Array.prototype.push,a=function(g,b){o.apply(g,n(b)?b:[b])},l=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 l.call(g)},skipNulls:!1,strictNullHandling:!1},d=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},y=function g(b,w,m,k,x,v,E,S,A,C,O,j,T,B,D,U,oe,Y){for(var W=b,re=Y,$=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(b);if($+=1,typeof M<"u"){if(M===$)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&($=0)}if(typeof C=="function"?W=C(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(R){return R instanceof Date?T(R):R})),W===null){if(v)return A&&!U?A(w,u.encoder,oe,"key",B):w;W=""}if(d(W)||e.isBuffer(W)){if(A){var Q=U?w:A(w,u.encoder,oe,"key",B);return[D(Q)+"="+D(A(W,u.encoder,oe,"value",B))]}return[D(w)+"="+D(String(W))]}var ye=[];if(typeof W>"u")return ye;var te;if(m==="comma"&&n(W))U&&A&&(W=e.maybeMap(W,A)),te=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(C))te=C;else{var we=Object.keys(W);te=O?we.sort(O):we}var K=S?w.replace(/\./g,"%2E"):w,N=k&&n(W)&&W.length===1?K+"[]":K;if(x&&n(W)&&W.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var z=te[ne],G=typeof z=="object"&&typeof z.value<"u"?z.value:W[z];if(!(E&&G===null)){var J=j&&S?z.replace(/\./g,"%2E"):z,ge=n(W)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(b,$);var se=i();se.set(p,Y),a(ye,g(G,ge,m,k,x,v,E,S,m==="comma"&&U&&n(W)?null:A,C,O,j,T,B,D,U,oe,se))}}return ye},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 w=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],k=u.filter;(typeof g.filter=="function"||n(g.filter))&&(k=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:k,format:w,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 Gr=function(g,b){var w=g,m=f(b),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var E=s[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var A=i(),C=0;C<k.length;++C){var O=k[C];m.skipNulls&&w[O]===null||a(v,y(w[O],O,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,A))}var j=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&"),j.length>0?T+j:""},Gr}function Rd(){if(go)return Yr;go=!0;var i=Ga(),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:i.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},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=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,w=g.split(y.delimiter,b),m=-1,k,x=y.charset;if(y.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===o&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,A,C;S===-1?(A=y.decoder(v,r.decoder,x,"key"),C=y.strictNullHandling?null:""):(A=y.decoder(v.slice(0,S),r.decoder,x,"key"),C=i.maybeMap(n(v.slice(S+1),y),function(j){return y.decoder(j,r.decoder,x,"value")})),C&&y.interpretNumericEntities&&x==="iso-8859-1"&&(C=s(C)),v.indexOf("[]=")>-1&&(C=t(C)?[C]:C);var O=e.call(f,A);O&&y.duplicates==="combine"?f[A]=i.combine(f[A],C):(!O||y.duplicates==="last")&&(f[A]=C)}return f},c=function(p,y,f,g){for(var b=g?y:n(y,f),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(E)&&k!==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,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=f.depth>0&&w.exec(b),x=k?b.slice(0,k.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&&(k=m.exec(b))!==null&&E<f.depth;){if(E+=1,!f.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(k[1])}if(k){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(k.index)+"]")}return c(v,y,f,g)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||i.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 Yr=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,f):p,b=f.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var k=w[m],x=u(k,g[k],f,typeof p=="string");b=i.merge(b,x,f)}return f.allowSparse===!0?b:i.compact(b)},Yr}function Ld(){if(yo)return Jr;yo=!0;var i=Md(),e=Rd(),t=co();return Jr={formats:t,parse:e,stringify:i},Jr}function Nd(){if(bo)return St;bo=!0;var i=_t;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
- `," "],o=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(o),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Ld();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var A=new e;return A.parse(v,E,S),A}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var A=v.indexOf("?"),C=A!==-1&&A<v.indexOf("#")?"?":"#",O=v.split(C),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(C);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var B=s.exec(T);if(B)return this.path=T,this.href=T,this.pathname=B[1],B[2]?(this.search=B[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 oe=T.substr(0,2)==="//";oe&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(oe||D&&!g[D])){for(var Y=-1,W=0;W<c.length;W++){var re=T.indexOf(c[W]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var $,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&($=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent($)),Y=-1;for(var W=0;W<l.length;W++){var re=T.indexOf(l[W]);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 Q=this.hostname.split(/\./),W=0,ye=Q.length;W<ye;W++){var te=Q[W];if(te&&!te.match(d)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(d)){var ne=Q.slice(0,W),z=Q.slice(W+1),G=te.match(p);G&&(ne.push(G[1]),z.unshift(G[2])),z.length&&(T="/"+z.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=i.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[U])for(var W=0,ye=a.length;W<ye;W++){var se=a[W];if(T.indexOf(se)!==-1){var R=encodeURIComponent(se);R===se&&(R=escape(se)),T=T.split(se).join(R)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));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 J=this.pathname||"",he=this.search||"";this.path=J+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(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||"",A=this.hash||"",C=!1,O="";this.host?C=v+this.host:this.hostname&&(C=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(C+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||O&&"?"+O||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&C!==!1?(C="//"+(C||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):C||(C=""),A&&A.charAt(0)!=="#"&&(A="#"+A),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+C+S+j+A};function k(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(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,A=Object.keys(this),C=0;C<A.length;C++){var O=A[C];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var B=j[T];B!=="protocol"&&(S[B]=v[B])}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 oe=D[U];S[oe]=v[oe]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var ye=(v.pathname||"").split("/");ye.length&&!(v.host=ye.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),ye[0]!==""&&ye.unshift(""),ye.length<2&&ye.unshift(""),S.pathname=ye.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||"",W=S.search||"";S.path=Y+W}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",$=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=$||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],ye=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(ye[0]===""?ye[0]=v.host:ye.unshift(v.host)),v.host=null),Z=Z&&(ye[0]===""||Q[0]==="")),$)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,Q=ye;else if(ye.length)Q||(Q=[]),Q.pop(),Q=Q.concat(ye),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.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(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,z=Q.length;z>=0;z--)K=Q[z],K==="."?Q.splice(z,1):K===".."?(Q.splice(z,1),ne++):ne&&(Q.splice(z,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.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&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.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)},St.parse=w,St.resolve=k,St.resolveObject=x,St.format=m,St.Url=e,St}function Ya(i){if(typeof i=="string")i=new URL(i);else if(!(i instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(i.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Qr?jd(i):Ud(i)}function jd(i){let e=i.hostname,t=i.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(cl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,s=t[2];if(r<al||r>ll||s!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Ud(i){if(i.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=i.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 Ja(i){let e=lo.resolve(i),t=i.charCodeAt(i.length-1);(t===sl||Qr&&t===ol)&&e[e.length-1]!==lo.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(ul,"%25")),!Qr&&e.includes("\\")&&(e=e.replace(dl,"%5C")),e.includes(`
8
- `)&&(e=e.replace(hl,"%0A")),e.includes("\r")&&(e=e.replace(fl,"%0D")),e.includes(" ")&&(e=e.replace(pl,"%09")),r.pathname=e,r}var Qa,Hr,uo,Wr,zr,ho,Vr,fo,Kr,po,Gr,mo,Yr,go,Jr,yo,St,bo,ze,Xa,Za,el,tl,rl,nl,il,ol,sl,al,ll,Qr,cl,ul,dl,hl,fl,pl,Bd=Ye(()=>{le(),ue(),ce(),td(),yd(),Cd(),Va(),Qa=Object.freeze(Object.create(null)),Hr={},uo=!1,Wr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,zr={},ho=!1,Vr={},fo=!1,Kr={},po=!1,Gr={},mo=!1,Yr={},go=!1,Jr={},yo=!1,St={},bo=!1,ze=Nd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Xa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Ja,ze.fileURLToPath=Ya,Za=ze.Url,el=ze.format,tl=ze.resolve,rl=ze.resolveObject,nl=ze.parse,il=ze.URL,ol=92,sl=47,al=97,ll=122,Qr=Xa==="win32",cl=/\//g,ul=/%/g,dl=/\\/g,hl=/\n/g,fl=/\r/g,pl=/\t/g}),Dd=pe((i,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")}}),vo=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=Rt(),t=(qe(),Ne($e));function r(n,o){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",o)}var s=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,a){super({objectMode:!0}),this.proxy=o,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,o,a){this.isSocketOpen?this.writeToProxy(n,o,a):this.writeQueue.push({chunk:n,encoding:o,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,a){this.proxy.write(n,o)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:a}=this.writeQueue.shift();this.writeToProxy(n,o,a)}}};i.BufferedDuplex=s}),Xr=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(i,"__esModule",{value:!0}),i.streamBuilder=i.browserStreamBuilder=void 0;var t=(qe(),Ne($e)),r=e(Dd()),s=e(pt()),n=Rt(),o=e(Ar()),a=vo(),l=(0,s.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!o.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function p(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function f(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=y(w,x,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};i.streamBuilder=g;var b=(w,m)=>{l("browserStreamBuilder");let k,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),A=O(m,U,oe);m.objectMode||(A._writev=a.writev.bind(A)),A.on("close",()=>{S.close()});let C=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=A,k.socket=S):(k=new a.BufferedDuplex(m,A,S),C?S.addEventListener("open",j):S.onopen=j),C?(S.addEventListener("close",T),S.addEventListener("error",B),S.addEventListener("message",D)):(S.onclose=T,S.onerror=B,S.onmessage=D);function O(Y,W,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=W,$._flush=re,$}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function B(Y){l("WebSocket onError",Y);let W=new Error("WebSocket error");W.event=Y,k.destroy(W)}async function D(Y){if(!A||!A.readable||!A.writable)return;let{data:W}=Y;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),A.push(W)}function U(Y,W,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,W,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function oe(Y){S.close(),Y()}return k};i.browserStreamBuilder=b}),wo={};$t(wo,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>ml,isIP:()=>Ue,isIPv4:()=>Ue,isIPv6:()=>Ue});function Ue(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var ml,gl=Ye(()=>{le(),ue(),ce(),ml={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),yl=pe((i,e)=>{le(),ue(),ce(),e.exports={}}),bl=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(i,"__esModule",{value:!0});var t=e((gl(),Ne(wo))),r=e(pt()),s=e(yl()),n=(0,r.default)("mqttjs:tcp"),o=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,s.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};i.default=o}),vl={};$t(vl,{default:()=>wl});var wl,Fd=Ye(()=>{le(),ue(),ce(),wl={}}),kl=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(i,"__esModule",{value:!0});var t=(Fd(),Ne(vl)),r=e((gl(),Ne(wo))),s=e(pt()),n=e(yl()),o=(0,s.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...y}=c;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(c)}var l=(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,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&c.emit("error",y),d.end()}return d.on("error",p),d};i.default=l}),_l=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Rt(),r=vo(),s,n,o;function a(){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 l(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(()=>{o.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(()=>{o.emit("close"),o.end(),o.destroy()}),s.onError(p=>{let y=new Error(p.errMsg);o.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";l(y);let g=c(y,p);s=wx.connectSocket({url:g,protocols:[f]}),n=a(),o=new r.BufferedDuplex(y,n,s),o._destroy=(w,m)=>{s.close({success(){m&&m(w)}})};let b=o.destroy;return o.destroy=(w,m)=>(o.destroy=b,setTimeout(()=>{s.close({fail(){o._destroy(w,m)}})},0),o),u(),o};i.default=d}),xl=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Rt(),r=vo(),s,n,o,a=!1;function l(){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 d(){a||(a=!0,s.onSocketOpen(()=>{o.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(()=>{o.end(),o.destroy()}),s.onSocketError(y=>{o.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=l(),o=new r.BufferedDuplex(f,n,s),d(),o};i.default=p}),$d=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(i,"__esModule",{value:!0}),i.connectAsync=u;var t=e(pt()),r=e((Bd(),Ne(Ka))),s=e(Si()),n=e(Ar());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function c(d,p){if(o("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(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 je<"u"&&(p.socksProxy=je.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(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=Xr().streamBuilder,a.wss=Xr().streamBuilder,a.mqtt=bl().default,a.tcp=bl().default,a.ssl=kl().default,a.tls=a.ssl,a.mqtts=kl().default):(a.ws=Xr().browserStreamBuilder,a.wss=Xr().browserStreamBuilder,a.wx=_l().default,a.wxs=_l().default,a.ali=xl().default,a.alis=xl().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,w)=>g&&w%2===0?!1:typeof a[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++),o("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let f=new s.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=c(d,p),w={connect:k=>{m(),f(b)},end:()=>{m(),f(b)},error:k=>{m(),b.end(),g(k)}};y===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{b.off(k,w[k])})}Object.keys(w).forEach(k=>{b.on(k,w[k])})})}i.default=c}),Sl=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var w=Object.getOwnPropertyDescriptor(f,g);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,w)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=i&&i.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=i&&i.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(b[b.length]=w);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),w=0;w<b.length;w++)b[w]!=="default"&&e(g,f,b[w]);return t(g,f),g}})(),s=i&&i.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=i&&i.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=i.KeepaliveManager=i.UniqueMessageIdProvider=i.DefaultMessageIdProvider=i.Store=i.MqttClient=i.connectAsync=i.connect=i.Client=void 0;var o=n(Si());i.MqttClient=o.default;var a=n(Os());i.DefaultMessageIdProvider=a.default;var l=n(Zu());i.UniqueMessageIdProvider=l.default;var c=n(Ss());i.Store=c.default;var u=r($d());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Bs());i.KeepaliveManager=d.default,i.Client=o.default,s(Si(),i),s(zt(),i),s(xs(),i);var p=Sr();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),qd=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(o,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(o,c,u)}:function(o,a,l,c){c===void 0&&(c=l),o[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(o,a){Object.defineProperty(o,"default",{enumerable:!0,value:a})}:function(o,a){o.default=a}),r=i&&i.__importStar||(function(){var o=function(a){return o=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},o(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=o(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),s=i&&i.__exportStar||function(o,a){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,o,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(Sl());i.default=n,s(Sl(),i)});const Hd=qd();const Wd={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}/#"},zd=300,Vd={templateId:"7",type:"link",isDeepLink:!0},Kd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class El{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;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={...Wd,...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,o)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>o(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Hd.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.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={...Vd,...this.config.fileTemplate??{},...Gd(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??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=zd){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??"",d=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:d,raw:s};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(s,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),a=o?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof s.message_id=="string"?s.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,l))}buildOutgoingEnvelope(e,t){const r={...Kd,...this.config.messageDefaults??{}},s=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={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:o}}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 o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=o[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Gd(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function Al(i,e){return(i.sender??"").toString()===e}function Il(i,e){const t=(i.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 ko(i){const e={raw:i},t=i.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 i.text=="string"&&i.text.trim().startsWith("{"))try{const s=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(s);typeof n.message=="string"&&(e.innerMessage=n.message);const o=n.metadata;o&&typeof o=="object"&&(typeof o.contentType=="string"&&(e.contentType=o.contentType),typeof o.templateId=="string"&&(e.templateId=o.templateId),o.payload!==void 0&&(e.payload=o.payload))}catch{}const r=i.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 Tl(i){const e=ko(i);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,o=n&&typeof n.url=="string"?n.url:void 0,a=typeof s.description=="string"?s.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!o&&!a?null:{fileName:a,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function Cl(i,e,t){const r=Il(i,t),s=ko(i),n=Tl(i);let o="";s.innerMessage?o=s.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?s.contentType!=="300"&&(o=i.text):o=i.text);const a=typeof i.message_id=="string"?i.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof i.timestamp=="number"?new Date(i.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof i.status=="number"?Yd(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:o,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return s.contentType&&(d.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:s}}function Yd(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class Pl extends gr{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 qo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Ho,this.conversationManager=new Go(e.conversationId),this.usesAikaara()&&(this.connection=new $o(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.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new El({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const 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(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const s=r.map(l=>Cl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=s.map(l=>l.message),o=this.messageStore.messages,a=[...n,...o.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of s){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}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=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const s=t.conversationId??r;if(!s)return;const n=this.config.tiledeskIdentity?.userId??"",{message:o,template:a}=Cl(e,s,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&o.role==="assistant")return;if(Al(e,n)){const u=this.messageStore.reconcileOptimistic(o);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(o);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:s,role:o.role==="tool"?"system":o.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(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{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}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 Jd extends gr{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 Ol={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 Qd(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function Xd(i,e,t){const r=Qd(i.name||"");if(r&&e&&e[r])return e[r];const s=i.type;return s&&s.trim().length>0?s:r&&Ol[r]?Ol[r]:t}function _o(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Zd(i,e){const t=e.split(".");let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function Ml(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=Xd(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),o={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=i.authHeader?await i.authHeader():void 0,l={accept:"application/json",...i.extraHeaders??{},...a?{authorization:a}:{}};let c=i.signEndpoint.includes("{")?i.signEndpoint:`${i.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=_o(c,o),d=await fetch(u,{method:i.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),y=Zd(p,e);if(!y)throw new Error(`Sign response missing path "${e}"`);const f=i.s3HostRewrite?y.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):y,g=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(_o(JSON.stringify(i.registerBody??{}),o)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?_o(i.viewerTemplate,o):y.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function xo(i){return{async upload(e,t){const r=new FormData,s=i.fieldName??"file";r.append(s,e,e.name);const n=typeof i.extraFields=="function"?i.extraFields(t):i.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 o=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:o,credentials:i.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(i.parseResponse)return i.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,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 eh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Rl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??eh;return{async fetchMessages(s,n){const o=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)),a=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,l={accept:"application/json","content-type":"application/json",...i.extraHeaders??{}};if(i.getToken){const p=await i.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(i.parseResponse&&u)return i.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const th=[{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)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],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},{id:"familyPension",type:"number",label:"Family Pension",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:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name",required:!0},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account No.",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],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:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No."}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationAmount",type:"number",label:"Donation Amount",currency:"₹",min:0},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN"},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:"^[0-9]{6}$"}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function rh(i,e){const t=i||{},r={userId:Et(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Te(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:fh()};r.us80cAmount=Se(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Se(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Se(t.us80dForParentsAmount),r.hasParentOverSixty=Zr(t.hasParentOverSixty),r.preventiveHealthCheckUp=Se(t.preventiveHealthCheckUp),r.medicalExpenditure=Se(t.medicalExpenditure),r.savingBankInterest=Se(t.savingBankInterest),r.fdInterest=Se(t.fdInterest),r.dividend=Se(t.dividend),r.anyOtherIncome=Se(t.anyOtherIncome),r.cryptoSellValue=Se(t.cryptoSellPrice),r.cryptoPurchaseAmount=Se(t.cryptoPurchasePrice),r.vdaPurchaseCost=Se(t.cryptoPurchasePrice);const s=(Se(t.bizReceiptsBank)??0)+(Se(t.bizReceiptsCash)??0),n=(Se(t.profReceiptsBank)??0)+(Se(t.profReceiptsCash)??0),o=Te(t.bizName)!==void 0||s>0;r.businessName=Te(o?t.bizName:t.profName),r.businessAnnualTurnOver=o?s||void 0:n||void 0,r.agricultureDetails={income:Se(t.agricultureIncome)},r.exemptIncomeAmount=Se(t.exemptIncome),r.exemptIncomeNature=Te(t.exemptIncomeNature),Se(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Te(t.exemptIncomeNature)??"Exempt income",value:String(Se(t.exemptIncome))}]),r.bankAccountNumber=Te(t.bankAccountNumber),r.bankIfscCode=Te(t.bankIfscCode),(Te(t.bankAccountNumber)||Te(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Te(t.bankAccountNumber),bankIfscCode:Te(t.bankIfscCode)}]);const a={description:Te(t.immovableAssetDescription),flatNo:Te(t.immovableAssetFlatNo),area:Te(t.immovableAssetArea),pinCode:Te(t.immovableAssetPincode),amount:Se(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=So(t.hpDetails,nh);l.length&&(r.hpDetails=l);const c=So(t.salaryDetails,ih);if(c.length){r.salaryIncome=c;const u=So(t.salaryDetails,p=>({grossSalary:Se(p.grossSalary),employerName:Te(p.employerName)}));u.length&&(r.salary=u);const d=en(t.salaryDetails)[0]??{};r.hraAmount=Se(d.hraReceived),r.leaveTravelAllowanceAmount=Se(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Se(d.leaveEncashment),r.anyOtherAllowanceAmount=Se(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return jt(r)}function nh(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Te(i.loanTakenFrom),bankOrInstituteName:Te(i.lenderName),loanAccountNo:Te(i.loanAccountNumber),loanSanctionDate:Nl(i.sanctionDate),totalLoanAmount:Se(i.totalLoanAmount),loanOutstandingAmount:Se(i.outstandingAmount),interest:Se(i.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Te(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:Zr(i.hasRentalIncome),homeLoanInterest:Se(i.homeLoanInterest),homeLoanPrinciple:Se(i.homeLoanPrinciple),housePropertyAddress:Te(i.housePropertyAddress),housePropertyPincode:Te(i.housePropertyPincode),rentalIncome:Se(i.rentalIncome),nameOfTenant:Te(i.nameOfTenant),propertyTax:Se(i.propertyTax),hasCoOwnedProperty:Zr(i.hasCoOwnedProperty),coOwnerName:Te(i.coOwnerName),coOwnerPan:Te(i.coOwnerPan),coOwnerShare:Te(i.coOwnerShare),loanDetails:t?[e]:void 0}}function ih(i){return{grossSalaryIncome:Se(i.grossSalary),salary:Se(i.basicSalary),employer:{employerName:Te(i.employerName),employerTan:Te(i.employerTan)},allowance:{hraAmount:Se(i.hraReceived),leaveTravelAllowanceAmount:Se(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Se(i.leaveEncashment),anyOtherAllowanceAmount:Se(i.anyOtherAllowance)}}}function oh(i,e){const t=[];for(const r of i){const s=Te(r.employerName),n=Te(r.employerTan),o=Se(r.grossSalary),a=Se(r.basicSalary),l=Se(r.totalTdsDeposited);s===void 0&&n===void 0&&o===void 0&&a===void 0&&l===void 0||t.push({grossSalary:o??0,basicSalary:a??0,employerName:s??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:Et(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function sh(i,e){const t=Te(i.aadhaarNumber),r=Te(i.bankAccountNumber),s=Te(i.bankIfscCode);return t===void 0&&r===void 0&&s===void 0?null:{userId:Et(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:s}]}}function ah(i,e){return{userId:Et(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Se(i.savingBankInterest)??0,fdInterest:Se(i.fdInterest)??0,dividend:Se(i.dividend)??0,anyOtherIncome:Se(i.anyOtherIncome)??0,familyPension:Se(i.familyPension)??0}}function lh(i,e){const t=Se(i.cryptoSellPrice),r=Se(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:Et(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function ch(i,e){const t=(s,n,o,a)=>{const l=Te(i[s]),c=Te(i[n]),u=Se(i[o]),d=Se(i[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(s=>s!==null);return r.length?{userId:Et(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function uh(i){return Te(i.lenderName)!==void 0||Te(i.loanAccountNumber)!==void 0||Se(i.totalLoanAmount)!==void 0||Se(i.outstandingAmount)!==void 0||Se(i.homeLoanInterest)!==void 0}function Ll(i){const e=Te(i.typeOfHouseProperty)?.toUpperCase();return Se(i.rentalIncome)!==void 0||Te(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function dh(i,e){const t=en(i.hpDetails).filter(uh).map(r=>{const s=jt({loanType:"HOMELOAN",bankOrInstituteName:Te(r.lenderName),loanAccountNo:Te(r.loanAccountNumber),loanSanctionDate:Nl(r.sanctionDate),totalLoanAmount:Se(r.totalLoanAmount),loanOutstandingAmount:Se(r.outstandingAmount),interest:Se(r.homeLoanInterest)});return jt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),homeLoanInterest:Se(r.homeLoanInterest),homeLoanPrinciple:Se(r.homeLoanPrinciple),propertyTax:Se(r.propertyTax),eligible80EEAAmount:Se(r.eligible80EEAAmount),eligible80EEAmount:Se(r.eligible80EEAmount),hasCoOwnedProperty:Zr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Ll(r),loanDetails:[s]})});return t.length?{userId:Et(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function hh(i,e){const t=en(i.hpDetails).filter(Ll).map(r=>jt({typeOfHouseProperty:Te(r.typeOfHouseProperty),housePropertyAddress:Te(r.housePropertyAddress),housePropertyPincode:Te(r.housePropertyPincode),rentalIncome:Se(r.rentalIncome),propertyTax:Se(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Te(r.nameOfTenant),tenantPanNumber:Te(r.tenantPanNumber),homeLoanInterest:Se(r.homeLoanInterest)}));return t.length?{userId:Et(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Et(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function Se(i){if(i==null||i==="")return;const e=typeof i=="number"?i:Number(i);return Number.isFinite(e)?e:void 0}function Te(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function Zr(i){return i===!0||i===!1?i:void 0}function fh(){const i=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}T${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${e(i.getMilliseconds(),3)}`}function Nl(i){const e=Te(i);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function en(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function So(i,e){return en(i).map(t=>jt(e(t))).filter(t=>t!==void 0)}function jt(i){if(Array.isArray(i)){const e=i.map(jt).filter(t=>t!==void 0);return e.length?e:void 0}if(i&&typeof i=="object"){const e={};for(const[t,r]of Object.entries(i)){const s=jt(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return i}function ph(i){const e=i&&typeof i=="object"?i:{},t={},r=De(e.employers),s=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(A=>{const C=Eo(A.salary),O=Eo(A.perquisites),j=Eo(A.profitsInLieuOfSalaryType),T=C+O+j,B=gh(A.allowance);return{employerName:Ce(A.employerName),employerTan:Ce(A.employerTAN),basicSalary:C||void 0,grossSalary:T||void 0,hraReceived:B.hra,leaveTravelAllowance:B.lta,leaveEncashment:B.leaveEncashment,anyOtherAllowance:B.other,totalTdsDeposited:mh(A,s,r)??Le(A.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(A=>{const C=De(A.loanDetails),O=C.length?C[0]:void 0,j=Le(A.grossAnnualRentReceived),T=C.length?C.reduce((Y,W)=>Y+(Le(W.interest)??0),0):void 0,B=De(A.tenant),D=De(A.coOwners),U=B[0],oe=D[0];return{typeOfHouseProperty:Ce(A.propertyType),loanTakenFrom:Ce(O?.loanTakenFrom),lenderName:Ce(O?.bankOrInstituteName),loanAccountNumber:Ce(O?.loanAccountNo),sanctionDate:jl(O?.loanSanctionDate),totalLoanAmount:Le(O?.totalLoanAmount),outstandingAmount:Le(O?.loanOutstandingAmount),homeLoanInterest:T,homeLoanPrinciple:void 0,housePropertyAddress:Ce(A.address),housePropertyPincode:Ce(A.pinCode),rentalIncome:j,nameOfTenant:Ce(U?.name),tenantPanNumber:Ce(U?.panNumber),eligible80EEAmount:Le(A.eligible80EEAmount),eligible80EEAAmount:Le(A.eligible80EEAAmount),propertyTax:Le(A.propertyTax),hasCoOwnedProperty:D.length>0,coOwnerName:Ce(oe?.name),coOwnerPan:Ce(oe?.panNumber),coOwnerShare:Le(oe?.share)?.toString()}}));const o=De(e.deductionUS80CDetails),a=At(o.map(A=>Le(A.amount))),l=o.find(A=>Ce(A.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=De(e.deductionUS80DDetails),u=c.find(A=>Ce(A.policyFor)?.toUpperCase()==="DEPENDANT")??De(e.insurances).find(A=>Ce(A.policyFor)?.toUpperCase()==="DEPENDANT"),d=c.find(A=>Ce(A.policyFor)?.toUpperCase()==="PARENTS")??De(e.insurances).find(A=>Ce(A.policyFor)?.toUpperCase()==="PARENTS"),p=Array.isArray(u?.bifurcation)?u.bifurcation[0]:void 0,y=Array.isArray(d?.bifurcation)?d.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Le(u?.healthInsuranceAmount??u?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(u?.insurerName??p?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(u?.policyNo??p?.accountNo),t.us80dForParentsAmount=Le(d?.healthInsuranceAmount??d?.premium),t.us80dForParentsPolicyCompany=Ce(d?.insurerName??y?.insurerName),t.us80dForParentsPolicyNumber=Ce(d?.policyNo??y?.accountNo),t.hasParentOverSixty=yh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const g=De(e.donations)[0];t.us80gDonationAmount=Le(g?.amount??g?.donationAmount),t.us80gNameOfCharity=Ce(g?.nameOfCharity??g?.donorName??g?.trustName),t.us80gCharityPan=Ce(g?.panNumber??g?.charityPan),t.us80gTrustAddress=Ce(g?.address??g?.charityAddress),t.us80gPincode=Ce(g?.pinCode??g?.pincode);const w=De(e.houseProperties?.[0]?.loanDetails)[0];t.us80eLoanTakenFrom=void 0,t.us80eBankName=void 0,t.us80eLoanAccountNumber=void 0,t.us80eLoanSanctionDate=void 0,t.us80eLoanAmount=void 0,t.us80eeLoanTakenFrom=Ce(w?.loanTakenFrom),t.us80eeBankName=Ce(w?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(w?.loanAccountNo),t.us80eeLoanSanctionDate=jl(w?.loanSanctionDate),t.us80eeLoanAmount=Le(w?.totalLoanAmount),t.us80eeOutstandingLoan=Le(w?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(w?.vehicleRegistrationNo);const m=De(e.insurances);t.preventiveHealthCheckUp=At(m.map(A=>Le(A.preventiveCheckUp))),t.medicalExpenditure=At(m.map(A=>Le(A.medicalExpenditure)));const k=De(e.incomes),x=A=>At(k.filter(C=>Ce(C.incomeType)===A).map(C=>Le(C.amount)));t.savingBankInterest=x("SAVING_INTEREST"),t.fdInterest=x("FD_RD_INTEREST"),t.anyOtherIncome=x("ANY_OTHER"),t.familyPension=x("FAMILY_PENSION"),t.dividend=At(De(e.dividendIncomes).map(A=>Le(A.income)));const v=e.business;if(v){const A=De(v.presumptiveIncomes),C=T=>{const B=De(T.incomes),D=U=>Le(B.find(oe=>Ce(oe.incomeType)===U)?.receipts)??0;return D("ANY_OTHER")>0?!0:D("BANK")>0||D("CASH")>0?!1:!!Ce(T.businessType)?.toUpperCase().includes("PROFESSION")},O=T=>A.find(B=>C(B)===T),j=(T,B)=>{if(!T)return;const D=De(T.incomes),U=Y=>Le(D.find(W=>Ce(W.incomeType)===Y)?.receipts),oe=U("BANK")||U("ANY_OTHER");t[B.name]=Ce(T.businessType),t[B.nature]=Ce(T.natureOfBusiness),t[B.bank]=oe||void 0,t[B.cash]=U("CASH")||void 0,t[B.net]=At(D.map(Y=>Le(Y.presumptiveIncome)))||void 0};j(O(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),j(O(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const E=De(e.capitalGain).filter(A=>Ce(A.assetType)?.toUpperCase()==="VDA").flatMap(A=>De(A.assetDetails));E.length&&(t.cryptoSellPrice=At(E.map(A=>Le(A.sellValue))),t.cryptoPurchasePrice=At(E.map(A=>Le(A.purchaseCost)))),t.agricultureIncome=Le(e.agriculturalDetails?.income),t.aadhaarNumber=Ce(e.aadharNumber);const S=De(e.bankDetails)[0];return S&&(t.bankAccountNumber=Ce(S.accountNumber),t.bankIfscCode=Ce(S.ifsCode)),Ul(t)}function jl(i){const e=Ce(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Eo(i){return De(i).reduce((e,t)=>e+(Le(t.taxableAmount)??0),0)}function mh(i,e,t){if(!e.length)return;const r=Ce(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Le(n.totalTdsDeposited)}const s=Ce(i.employerName)?.trim().toLowerCase();if(s){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===s)return Le(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Le(e[0].totalTdsDeposited)}function gh(i){const e=De(i);if(!e.length)return{};let t,r,s,n;for(const o of e){const a=Le(o.exemptAmount)??Le(o.allowanceAmount);switch(Ce(o.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":s=a;break;default:n=(n??0)+(Le(o.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:s,other:n}}function At(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Le(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Ce(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function yh(i){if(typeof i=="boolean")return i;if(typeof i=="string"){const e=i.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof i=="number")return i===1?!0:i===0?!1:void 0}function Ul(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(s=>s&&typeof s=="object"?Ul(s):s):e[t]=r);return e}function Ao(){if(typeof window>"u")return null;const i=window,e=i.__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=i.__aikaara_descriptor__??{},r=Ih(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const s=Th(e.slug),n=typeof s?.tenantJwt=="string"?s.tenantJwt:"",o=e.getChatJwt,a=async()=>n||await o(),l=(s&&s.userId!=null&&s.userId!==""?String(s.userId):Ph(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Ch(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Oh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function bh(i){const e=await i.getToken(),t=i.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${i.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...i.headers}});if(!r.ok){const s=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${s.slice(0,200)}`)}return ph(Io(await r.json().catch(()=>({}))))}async function vh(i,e){const t=await i.getToken(),r=i.userId,s={...rh(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(o["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const a=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(s)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Io(await a.json().catch(()=>({})))}async function wh(i,e){return Ut(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function kh(i,e){return Ut(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function _h(i,e){return Ut(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function xh(i,e){return Ut(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Sh(i,e){return Ut(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Eh(i,e){return Ut(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Ah(i,e){return Ut(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function Ut(i,e,t){const s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:s,body:JSON.stringify(t)});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${o.slice(0,200)}`)}return Io(await n.json().catch(()=>({})))}function Ih(i){const e=[i.cloud?.listEndpoint,i.cloud?.downloadEndpoint,i.upload?.signEndpoint,i.login?.pan?.basicPanEndpoint,i.login?.pan?.panDetailEndpoint,i.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function Th(i){if(!i||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${i}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function Ch(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(i))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function Ph(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function Io(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Oh(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}class Mh{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),e.chatActions!==void 0&&this.header.setActions(e.chatActions),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),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),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);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();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)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),s=r(e);return t.some(n=>typeof n=="string"&&r(n)===s)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:th,data:{}});const t=Ao();if(!(!t||!t.baseUrl))try{const r=await bh(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-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=Ao();if(!r)return;const s={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],o=oh(n,s);o&&await wh(r,o)}else if(e==="bank-details"){const n=sh(t,s);n&&await kh(r,n)}else if(e==="other-sources")await _h(r,ah(t,s));else if(e==="business-profession"){const n=ch(t,s);n&&await xh(r,n)}else if(e==="crypto-income"){const n=lh(t,s);n&&await Ah(r,n)}else if(e==="house-property"){const n=dh(t,s);n&&await Sh(r,n);const o=hh(t,s);o&&await Eh(r,o)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Ao();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await vh(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 Bl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Lc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Do,position:this.getAttribute("position")||this._config.position||Rc,width:Number(this.getAttribute("width"))||this._config.width||Cc,height:Number(this.getAttribute("height"))||this._config.height||Pc,fontFamily:this._config.fontFamily||Mc,borderRadius:this._config.borderRadius??Oc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Fo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Nc,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,o=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??s),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("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(`
1
+ var AikaaraChat=(function(Me){"use strict";class Do{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 an{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 Do(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 yr{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 Tc=1e3,Cc=10,Pc=400,Oc=600,Fo="#6366f1",Mc=12,Lc="system-ui, -apple-system, sans-serif",$o="Type a message...",Rc="bottom-right",Nc="light",jc={x:20,y:20},ln="aikaara_conversation_id";class qo extends yr{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 an(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}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??Cc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Tc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new an(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 Ho{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 a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(s,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const o=await n.json();if(o&&typeof o=="object"&&"success"in o){if(!o.success)throw new Error(`API error: ${o.message||"Request failed"}`);return o.data}return o}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 Wo{_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=zo(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=zo(t,r);if(s){const n=br(s),o=br(r);!n&&o&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function zo(i,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const o=br(e),a=Vo(e),l=Ko(e);if(!o&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=i.length-1;u>=0;u--){const d=i[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const y=(d.content||"").trim().toLowerCase();if(y==="file_uploaded"||y==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const b=br(d);if(o&&b&&o===b)return d;const w=Vo(d);if(a&&w&&a===w)return d;const m=Ko(d);if(l&&m&&l===m)return d}return null}function Vo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Go(i);if(t)return t}function Ko(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(i.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=i.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function br(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(i.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Go(i);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function Go(i){const e=i.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Yo{_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(ln)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(ln)}catch{return null}}saveToStorage(e){try{localStorage.setItem(ln,e)}catch{}}}var cn=Object.defineProperty,Uc=Object.getOwnPropertyDescriptor,Bc=Object.getOwnPropertyNames,Dc=Object.prototype.hasOwnProperty,Ye=(i,e)=>()=>(i&&(e=i(i=0)),e),pe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),$t=(i,e)=>{for(var t in e)cn(i,t,{get:e[t],enumerable:!0})},Fc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Bc(e))!Dc.call(i,s)&&s!==t&&cn(i,s,{get:()=>e[s],enumerable:!(r=Uc(e,s))||r.enumerable});return i},Ne=i=>Fc(cn({},"__esModule",{value:!0}),i),le=Ye(()=>{}),je={};$t(je,{_debugEnd:()=>Wn,_debugProcess:()=>Hn,_events:()=>si,_eventsCount:()=>ai,_exiting:()=>Cn,_fatalExceptions:()=>Fn,_getActiveHandles:()=>rs,_getActiveRequests:()=>ts,_kill:()=>Mn,_linkedBinding:()=>Zo,_maxListeners:()=>oi,_preload_modules:()=>ri,_rawDebug:()=>An,_startProfilerIdleNotifier:()=>zn,_stopProfilerIdleNotifier:()=>Vn,_tickCallback:()=>qn,abort:()=>Jn,addListener:()=>li,allowedNodeEnvironmentFlags:()=>Bn,arch:()=>hn,argv:()=>mn,argv0:()=>ti,assert:()=>ns,binding:()=>wn,browser:()=>En,chdir:()=>Sn,config:()=>Pn,cpuUsage:()=>tr,cwd:()=>_n,debugPort:()=>ei,default:()=>gi,dlopen:()=>es,domain:()=>Tn,emit:()=>fi,emitWarning:()=>vn,env:()=>pn,execArgv:()=>gn,execPath:()=>Zn,exit:()=>jn,features:()=>Dn,hasUncaughtExceptionCaptureCallback:()=>is,hrtime:()=>vr,kill:()=>Nn,listeners:()=>ss,memoryUsage:()=>Rn,moduleLoadList:()=>In,nextTick:()=>Qo,off:()=>ui,on:()=>ut,once:()=>ci,openStdin:()=>Un,pid:()=>Qn,platform:()=>fn,ppid:()=>Xn,prependListener:()=>pi,prependOnceListener:()=>mi,reallyExit:()=>On,release:()=>xn,removeAllListeners:()=>hi,removeListener:()=>di,resourceUsage:()=>Ln,setSourceMapsEnabled:()=>ni,setUncaughtExceptionCaptureCallback:()=>$n,stderr:()=>Gn,stdin:()=>Yn,stdout:()=>Kn,title:()=>dn,umask:()=>kn,uptime:()=>os,version:()=>yn,versions:()=>bn});function un(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function $c(){!Ot||!Mt||(Ot=!1,Mt.length?tt=Mt.concat(tt):er=-1,tt.length&&Jo())}function Jo(){if(!Ot){var i=setTimeout($c,0);Ot=!0;for(var e=tt.length;e;){for(Mt=tt,tt=[];++er<e;)Mt&&Mt[er].run();er=-1,e=tt.length}Mt=null,Ot=!1,clearTimeout(i)}}function Qo(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];tt.push(new Xo(i,e)),tt.length===1&&!Ot&&setTimeout(Jo,0)}function Xo(i,e){this.fun=i,this.array=e}function He(){}function Zo(i){un("_linkedBinding")}function es(i){un("dlopen")}function ts(){return[]}function rs(){return[]}function ns(i,e){if(!i)throw new Error(e||"assertion error")}function is(){return!1}function os(){return dt.now()/1e3}function vr(i){var e=Math.floor((Date.now()-dt.now())*.001),t=dt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=wr)),[r,s]}function ut(){return gi}function ss(i){return[]}var tt,Ot,Mt,er,dn,hn,fn,pn,mn,gn,yn,bn,vn,wn,kn,_n,Sn,xn,En,An,In,Tn,Cn,Pn,On,Mn,tr,Ln,Rn,Nn,jn,Un,Bn,Dn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,dt,ii,wr,oi,si,ai,li,ci,ui,di,hi,fi,pi,mi,gi,qc=Ye(()=>{le(),ue(),ce(),tt=[],Ot=!1,er=-1,Xo.prototype.run=function(){this.fun.apply(null,this.array)},dn="browser",hn="x64",fn="browser",pn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},mn=["/usr/bin/node"],gn=[],yn="v16.8.0",bn={},vn=function(i,e){console.warn((e?e+": ":"")+i)},wn=function(i){un("binding")},kn=function(i){return 0},_n=function(){return"/"},Sn=function(i){},xn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},En=!0,An=He,In=[],Tn={},Cn=!1,Pn={},On=He,Mn=He,tr=function(){return{}},Ln=tr,Rn=tr,Nn=He,jn=He,Un=He,Bn={},Dn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Fn=He,$n=He,qn=He,Hn=He,Wn=He,zn=He,Vn=He,Kn=void 0,Gn=void 0,Yn=void 0,Jn=He,Qn=2,Xn=1,Zn="/bin/usr/node",ei=9229,ti="node",ri=[],ni=He,dt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},dt.now===void 0&&(ii=Date.now(),dt.timing&&dt.timing.navigationStart&&(ii=dt.timing.navigationStart),dt.now=()=>Date.now()-ii),wr=1e9,vr.bigint=function(i){var e=vr(i);return typeof BigInt>"u"?e[0]*wr+e[1]:BigInt(e[0]*wr)+BigInt(e[1])},oi=10,si={},ai=0,li=ut,ci=ut,ui=ut,di=ut,hi=ut,fi=He,pi=ut,mi=ut,gi={version:yn,versions:bn,arch:hn,platform:fn,browser:En,release:xn,_rawDebug:An,moduleLoadList:In,binding:wn,_linkedBinding:Zo,_events:si,_eventsCount:ai,_maxListeners:oi,on:ut,addListener:li,once:ci,off:ui,removeListener:di,removeAllListeners:hi,emit:fi,prependListener:pi,prependOnceListener:mi,listeners:ss,domain:Tn,_exiting:Cn,config:Pn,dlopen:es,uptime:os,_getActiveRequests:ts,_getActiveHandles:rs,reallyExit:On,_kill:Mn,cpuUsage:tr,resourceUsage:Ln,memoryUsage:Rn,kill:Nn,exit:jn,openStdin:Un,allowedNodeEnvironmentFlags:Bn,assert:ns,features:Dn,_fatalExceptions:Fn,setUncaughtExceptionCaptureCallback:$n,hasUncaughtExceptionCaptureCallback:is,emitWarning:vn,nextTick:Qo,_tickCallback:qn,_debugProcess:Hn,_debugEnd:Wn,_startProfilerIdleNotifier:zn,_stopProfilerIdleNotifier:Vn,stdout:Kn,stdin:Yn,stderr:Gn,abort:Jn,umask:kn,chdir:Sn,cwd:_n,env:pn,title:dn,argv:mn,execArgv:gn,pid:Qn,ppid:Xn,execPath:Zn,debugPort:ei,hrtime:vr,argv0:ti,_preload_modules:ri,setSourceMapsEnabled:ni}}),ce=Ye(()=>{qc()});function Hc(){if(yi)return qt;yi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)i[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function o(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=g.indexOf("=");y===-1&&(y=f);var b=y===f?0:4-y%4;return[y,b]}function a(g){var f=o(g),y=f[0],b=f[1];return(y+b)*3/4-b}function l(g,f,y){return(f+y)*3/4-y}function c(g){var f,y=o(g),b=y[0],w=y[1],m=new t(l(g,b,w)),k=0,S=w>0?b-4:b,v;for(v=0;v<S;v+=4)f=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=f>>16&255,m[k++]=f>>8&255,m[k++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=f>>8&255,m[k++]=f&255),m}function u(g){return i[g>>18&63]+i[g>>12&63]+i[g>>6&63]+i[g&63]}function d(g,f,y){for(var b,w=[],m=f;m<y;m+=3)b=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(b));return w.join("")}function p(g){for(var f,y=g.length,b=y%3,w=[],m=16383,k=0,S=y-b;k<S;k+=m)w.push(d(g,k,k+m>S?S:k+m));return b===1?(f=g[y-1],w.push(i[f>>2]+i[f<<4&63]+"==")):b===2&&(f=(g[y-2]<<8)+g[y-1],w.push(i[f>>10]+i[f>>4&63]+i[f<<2&63]+"=")),w.join("")}return qt}function Wc(){return bi?rr:(bi=!0,rr.read=function(i,e,t,r,s){var n,o,a=s*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?s-1:0,p=t?-1:1,g=i[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=p,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=r;u>0;o=o*256+i[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(g?-1:1)*(1/0);o=o+Math.pow(2,r),n=n-c}return(g?-1:1)*o*Math.pow(2,n-r)},rr.write=function(i,e,t,r,s,n){var o,a,l,c=n*8-s-1,u=(1<<c)-1,d=u>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(o++,l/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(e*l-1)*Math.pow(2,s),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;i[t+g]=a&255,g+=f,a/=256,s-=8);for(o=o<<s|a,c+=s;c>0;i[t+g]=o&255,g+=f,o/=256,c-=8);i[t+g-f]|=y*128},rr)}function zc(){if(vi)return kt;vi=!0;let i=Hc(),e=Wc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;kt.Buffer=o,kt.SlowBuffer=w,kt.INSPECT_MAX_BYTES=50;let r=2147483647;kt.kMaxLength=r,o.TYPED_ARRAY_SUPPORT=s(),!o.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 h=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(h,_),h.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let _=new Uint8Array(h);return Object.setPrototypeOf(_,o.prototype),_}function o(h,_,A){if(typeof h=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,_,A)}o.poolSize=8192;function a(h,_,A){if(typeof h=="string")return d(h,_);if(ArrayBuffer.isView(h))return g(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(H(h,ArrayBuffer)||h&&H(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(h,SharedArrayBuffer)||h&&H(h.buffer,SharedArrayBuffer)))return f(h,_,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let D=h.valueOf&&h.valueOf();if(D!=null&&D!==h)return o.from(D,_,A);let X=y(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return o.from(h[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}o.from=function(h,_,A){return a(h,_,A)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function c(h,_,A){return l(h),h<=0?n(h):_!==void 0?typeof A=="string"?n(h).fill(_,A):n(h).fill(_):n(h)}o.alloc=function(h,_,A){return c(h,_,A)};function u(h){return l(h),n(h<0?0:b(h)|0)}o.allocUnsafe=function(h){return u(h)},o.allocUnsafeSlow=function(h){return u(h)};function d(h,_){if((typeof _!="string"||_==="")&&(_="utf8"),!o.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(h,_)|0,D=n(A),X=D.write(h,_);return X!==A&&(D=D.slice(0,X)),D}function p(h){let _=h.length<0?0:b(h.length)|0,A=n(_);for(let D=0;D<_;D+=1)A[D]=h[D]&255;return A}function g(h){if(H(h,Uint8Array)){let _=new Uint8Array(h);return f(_.buffer,_.byteOffset,_.byteLength)}return p(h)}function f(h,_,A){if(_<0||h.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let D;return _===void 0&&A===void 0?D=new Uint8Array(h):A===void 0?D=new Uint8Array(h,_):D=new Uint8Array(h,_,A),Object.setPrototypeOf(D,o.prototype),D}function y(h){if(o.isBuffer(h)){let _=b(h.length)|0,A=n(_);return A.length===0||h.copy(A,0,0,_),A}if(h.length!==void 0)return typeof h.length!="number"||me(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function b(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),o.alloc(+h)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,_){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),H(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),!o.isBuffer(h)||!o.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===_)return 0;let A=h.length,D=_.length;for(let X=0,de=Math.min(A,D);X<de;++X)if(h[X]!==_[X]){A=h[X],D=_[X];break}return A<D?-1:D<A?1:0},o.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(h,_){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<h.length;++A)_+=h[A].length;let D=o.allocUnsafe(_),X=0;for(A=0;A<h.length;++A){let de=h[A];if(H(de,Uint8Array))X+de.length>D.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(D,X)):Uint8Array.prototype.set.call(D,de,X);else if(o.isBuffer(de))de.copy(D,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return D};function m(h,_){if(o.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||H(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let A=h.length,D=arguments.length>2&&arguments[2]===!0;if(!D&&A===0)return 0;let X=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return q(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(h).length;default:if(X)return D?-1:q(h).length;_=(""+_).toLowerCase(),X=!0}}o.byteLength=m;function k(h,_,A){let D=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(h||(h="utf8");;)switch(h){case"hex":return W(this,_,A);case"utf8":case"utf-8":return $(this,_,A);case"ascii":return oe(this,_,A);case"latin1":case"binary":return K(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,_,A);default:if(D)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),D=!0}}o.prototype._isBuffer=!0;function S(h,_,A){let D=h[_];h[_]=h[A],h[A]=D}o.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<h;_+=2)S(this,_,_+1);return this},o.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<h;_+=4)S(this,_,_+3),S(this,_+1,_+2);return this},o.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<h;_+=8)S(this,_,_+7),S(this,_+1,_+6),S(this,_+2,_+5),S(this,_+3,_+4);return this},o.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?$(this,0,h):k.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="",_=kt.INSPECT_MAX_BYTES;return h=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(h+=" ... "),"<Buffer "+h+">"},t&&(o.prototype[t]=o.prototype.inspect),o.prototype.compare=function(h,_,A,D,X){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(_===void 0&&(_=0),A===void 0&&(A=h?h.length:0),D===void 0&&(D=0),X===void 0&&(X=this.length),_<0||A>h.length||D<0||X>this.length)throw new RangeError("out of range index");if(D>=X&&_>=A)return 0;if(D>=X)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,D>>>=0,X>>>=0,this===h)return 0;let de=X-D,_e=A-_,V=Math.min(de,_e),ie=this.slice(D,X),Ie=h.slice(_,A);for(let Te=0;Te<V;++Te)if(ie[Te]!==Ie[Te]){de=ie[Te],_e=Ie[Te];break}return de<_e?-1:_e<de?1:0};function v(h,_,A,D,X){if(h.length===0)return-1;if(typeof A=="string"?(D=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0:h.length-1),A<0&&(A=h.length+A),A>=h.length){if(X)return-1;A=h.length-1}else if(A<0)if(X)A=0;else return-1;if(typeof _=="string"&&(_=o.from(_,D)),o.isBuffer(_))return _.length===0?-1:x(h,_,A,D,X);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,_,A):Uint8Array.prototype.lastIndexOf.call(h,_,A):x(h,[_],A,D,X);throw new TypeError("val must be string, number or Buffer")}function x(h,_,A,D,X){let de=1,_e=h.length,V=_.length;if(D!==void 0&&(D=String(D).toLowerCase(),D==="ucs2"||D==="ucs-2"||D==="utf16le"||D==="utf-16le")){if(h.length<2||_.length<2)return-1;de=2,_e/=2,V/=2,A/=2}function ie(Te,Pe){return de===1?Te[Pe]:Te.readUInt16BE(Pe*de)}let Ie;if(X){let Te=-1;for(Ie=A;Ie<_e;Ie++)if(ie(h,Ie)===ie(_,Te===-1?0:Ie-Te)){if(Te===-1&&(Te=Ie),Ie-Te+1===V)return Te*de}else Te!==-1&&(Ie-=Ie-Te),Te=-1}else for(A+V>_e&&(A=_e-V),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Pe=0;Pe<V;Pe++)if(ie(h,Ie+Pe)!==ie(_,Pe)){Te=!1;break}if(Te)return Ie}return-1}o.prototype.includes=function(h,_,A){return this.indexOf(h,_,A)!==-1},o.prototype.indexOf=function(h,_,A){return v(this,h,_,A,!0)},o.prototype.lastIndexOf=function(h,_,A){return v(this,h,_,A,!1)};function E(h,_,A,D){A=Number(A)||0;let X=h.length-A;D?(D=Number(D),D>X&&(D=X)):D=X;let de=_.length;D>de/2&&(D=de/2);let _e;for(_e=0;_e<D;++_e){let V=parseInt(_.substr(_e*2,2),16);if(me(V))return _e;h[A+_e]=V}return _e}function I(h,_,A,D){return be(q(_,h.length-A),h,A,D)}function O(h,_,A,D){return be(ee(_),h,A,D)}function C(h,_,A,D){return be(fe(_),h,A,D)}function j(h,_,A,D){return be(he(_,h.length-A),h,A,D)}o.prototype.write=function(h,_,A,D){if(_===void 0)D="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")D=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,D===void 0&&(D="utf8")):(D=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-_;if((A===void 0||A>X)&&(A=X),h.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");D||(D="utf8");let de=!1;for(;;)switch(D){case"hex":return E(this,h,_,A);case"utf8":case"utf-8":return I(this,h,_,A);case"ascii":case"latin1":case"binary":return O(this,h,_,A);case"base64":return C(this,h,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,_,A);default:if(de)throw new TypeError("Unknown encoding: "+D);D=(""+D).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,_,A){return _===0&&A===h.length?i.fromByteArray(h):i.fromByteArray(h.slice(_,A))}function $(h,_,A){A=Math.min(h.length,A);let D=[],X=_;for(;X<A;){let de=h[X],_e=null,V=de>239?4:de>223?3:de>191?2:1;if(X+V<=A){let ie,Ie,Te,Pe;switch(V){case 1:de<128&&(_e=de);break;case 2:ie=h[X+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(_e=Pe));break;case 3:ie=h[X+1],Ie=h[X+2],(ie&192)===128&&(Ie&192)===128&&(Pe=(de&15)<<12|(ie&63)<<6|Ie&63,Pe>2047&&(Pe<55296||Pe>57343)&&(_e=Pe));break;case 4:ie=h[X+1],Ie=h[X+2],Te=h[X+3],(ie&192)===128&&(Ie&192)===128&&(Te&192)===128&&(Pe=(de&15)<<18|(ie&63)<<12|(Ie&63)<<6|Te&63,Pe>65535&&Pe<1114112&&(_e=Pe))}}_e===null?(_e=65533,V=1):_e>65535&&(_e-=65536,D.push(_e>>>10&1023|55296),_e=56320|_e&1023),D.push(_e),X+=V}return U(D)}let B=4096;function U(h){let _=h.length;if(_<=B)return String.fromCharCode.apply(String,h);let A="",D=0;for(;D<_;)A+=String.fromCharCode.apply(String,h.slice(D,D+=B));return A}function oe(h,_,A){let D="";A=Math.min(h.length,A);for(let X=_;X<A;++X)D+=String.fromCharCode(h[X]&127);return D}function K(h,_,A){let D="";A=Math.min(h.length,A);for(let X=_;X<A;++X)D+=String.fromCharCode(h[X]);return D}function W(h,_,A){let D=h.length;(!_||_<0)&&(_=0),(!A||A<0||A>D)&&(A=D);let X="";for(let de=_;de<A;++de)X+=ve[h[de]];return X}function re(h,_,A){let D=h.slice(_,A),X="";for(let de=0;de<D.length-1;de+=2)X+=String.fromCharCode(D[de]+D[de+1]*256);return X}o.prototype.slice=function(h,_){let A=this.length;h=~~h,_=_===void 0?A:~~_,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<h&&(_=h);let D=this.subarray(h,_);return Object.setPrototypeOf(D,o.prototype),D};function F(h,_,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+_>A)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||F(h,_,this.length);let D=this[h],X=1,de=0;for(;++de<_&&(X*=256);)D+=this[h+de]*X;return D},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||F(h,_,this.length);let D=this[h+--_],X=1;for(;_>0&&(X*=256);)D+=this[h+--_]*X;return D},o.prototype.readUint8=o.prototype.readUInt8=function(h,_){return h=h>>>0,_||F(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||F(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||F(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,_){return h=h>>>0,_||F(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ge(h,this.length-8);let D=_+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,X=this[++h]+this[++h]*2**8+this[++h]*2**16+A*2**24;return BigInt(D)+(BigInt(X)<<BigInt(32))}),o.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ge(h,this.length-8);let D=_*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],X=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A;return(BigInt(D)<<BigInt(32))+BigInt(X)}),o.prototype.readIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||F(h,_,this.length);let D=this[h],X=1,de=0;for(;++de<_&&(X*=256);)D+=this[h+de]*X;return X*=128,D>=X&&(D-=Math.pow(2,8*_)),D},o.prototype.readIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||F(h,_,this.length);let D=_,X=1,de=this[h+--D];for(;D>0&&(X*=256);)de+=this[h+--D]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*_)),de},o.prototype.readInt8=function(h,_){return h=h>>>0,_||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,_){h=h>>>0,_||F(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},o.prototype.readInt16BE=function(h,_){h=h>>>0,_||F(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},o.prototype.readInt32LE=function(h,_){return h=h>>>0,_||F(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,_){return h=h>>>0,_||F(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ge(h,this.length-8);let D=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(D)<<BigInt(32))+BigInt(_+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),o.prototype.readBigInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ge(h,this.length-8);let D=(_<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(D)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+A)}),o.prototype.readFloatLE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,_){return h=h>>>0,_||F(h,4,this.length),e.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||F(h,8,this.length),e.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||F(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,_,A,D,X,de){if(!o.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>X||_<de)throw new RangeError('"value" argument is out of bounds');if(A+D>h.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,_,A,D){if(h=+h,_=_>>>0,A=A>>>0,!D){let _e=Math.pow(2,8*A)-1;Z(this,h,_,A,_e,0)}let X=1,de=0;for(this[_]=h&255;++de<A&&(X*=256);)this[_+de]=h/X&255;return _+A},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,_,A,D){if(h=+h,_=_>>>0,A=A>>>0,!D){let _e=Math.pow(2,8*A)-1;Z(this,h,_,A,_e,0)}let X=A-1,de=1;for(this[_+X]=h&255;--X>=0&&(de*=256);)this[_+X]=h/de&255;return _+A},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,1,255,0),this[_]=h&255,_+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,65535,0),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,65535,0),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,4294967295,0),this[_+3]=h>>>24,this[_+2]=h>>>16,this[_+1]=h>>>8,this[_]=h&255,_+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,4294967295,0),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4};function M(h,_,A,D,X){Y(_,D,X,h,A,7);let de=Number(_&BigInt(4294967295));h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[A++]=_e,_e=_e>>8,h[A++]=_e,_e=_e>>8,h[A++]=_e,_e=_e>>8,h[A++]=_e,A}function Q(h,_,A,D,X){Y(_,D,X,h,A,7);let de=Number(_&BigInt(4294967295));h[A+7]=de,de=de>>8,h[A+6]=de,de=de>>8,h[A+5]=de,de=de>>8,h[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[A+3]=_e,_e=_e>>8,h[A+2]=_e,_e=_e>>8,h[A+1]=_e,_e=_e>>8,h[A]=_e,A+8}o.prototype.writeBigUInt64LE=ae(function(h,_=0){return M(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=ae(function(h,_=0){return Q(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,_,A,D){if(h=+h,_=_>>>0,!D){let V=Math.pow(2,8*A-1);Z(this,h,_,A,V-1,-V)}let X=0,de=1,_e=0;for(this[_]=h&255;++X<A&&(de*=256);)h<0&&_e===0&&this[_+X-1]!==0&&(_e=1),this[_+X]=(h/de>>0)-_e&255;return _+A},o.prototype.writeIntBE=function(h,_,A,D){if(h=+h,_=_>>>0,!D){let V=Math.pow(2,8*A-1);Z(this,h,_,A,V-1,-V)}let X=A-1,de=1,_e=0;for(this[_+X]=h&255;--X>=0&&(de*=256);)h<0&&_e===0&&this[_+X+1]!==0&&(_e=1),this[_+X]=(h/de>>0)-_e&255;return _+A},o.prototype.writeInt8=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,1,127,-128),h<0&&(h=255+h+1),this[_]=h&255,_+1},o.prototype.writeInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,32767,-32768),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,2,32767,-32768),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,2147483647,-2147483648),this[_]=h&255,this[_+1]=h>>>8,this[_+2]=h>>>16,this[_+3]=h>>>24,_+4},o.prototype.writeInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||Z(this,h,_,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4},o.prototype.writeBigInt64LE=ae(function(h,_=0){return M(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=ae(function(h,_=0){return Q(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ye(h,_,A,D,X,de){if(A+D>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(h,_,A,D,X){return _=+_,A=A>>>0,X||ye(h,_,A,4),e.write(h,_,A,D,23,4),A+4}o.prototype.writeFloatLE=function(h,_,A){return te(this,h,_,!0,A)},o.prototype.writeFloatBE=function(h,_,A){return te(this,h,_,!1,A)};function we(h,_,A,D,X){return _=+_,A=A>>>0,X||ye(h,_,A,8),e.write(h,_,A,D,52,8),A+8}o.prototype.writeDoubleLE=function(h,_,A){return we(this,h,_,!0,A)},o.prototype.writeDoubleBE=function(h,_,A){return we(this,h,_,!1,A)},o.prototype.copy=function(h,_,A,D){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!D&&D!==0&&(D=this.length),_>=h.length&&(_=h.length),_||(_=0),D>0&&D<A&&(D=A),D===A||h.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(D<0)throw new RangeError("sourceEnd out of bounds");D>this.length&&(D=this.length),h.length-_<D-A&&(D=h.length-_+A);let X=D-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,D):Uint8Array.prototype.set.call(h,this.subarray(A,D),_),X},o.prototype.fill=function(h,_,A,D){if(typeof h=="string"){if(typeof _=="string"?(D=_,_=0,A=this.length):typeof A=="string"&&(D=A,A=this.length),D!==void 0&&typeof D!="string")throw new TypeError("encoding must be a string");if(typeof D=="string"&&!o.isEncoding(D))throw new TypeError("Unknown encoding: "+D);if(h.length===1){let de=h.charCodeAt(0);(D==="utf8"&&de<128||D==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let X;if(typeof h=="number")for(X=_;X<A;++X)this[X]=h;else{let de=o.isBuffer(h)?h:o.from(h,D),_e=de.length;if(_e===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<A-_;++X)this[X+_]=de[X%_e]}return this};let G={};function N(h,_,A){G[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(D){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:D,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}N("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),N("ERR_INVALID_ARG_TYPE",function(h,_){return`The "${h}" argument must be of type number. Received type ${typeof _}`},TypeError),N("ERR_OUT_OF_RANGE",function(h,_,A){let D=`The value of "${h}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),D+=` It must be ${_}. Received ${X}`,D},RangeError);function ne(h){let _="",A=h.length,D=h[0]==="-"?1:0;for(;A>=D+4;A-=3)_=`_${h.slice(A-3,A)}${_}`;return`${h.slice(0,A)}${_}`}function z(h,_,A){J(_,"offset"),(h[_]===void 0||h[_+A]===void 0)&&ge(_,h.length-(A+1))}function Y(h,_,A,D,X,de){if(h>A||h<_){let _e=typeof _=="bigint"?"n":"",V;throw _===0||_===BigInt(0)?V=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:V=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new G.ERR_OUT_OF_RANGE("value",V,h)}z(D,X,de)}function J(h,_){if(typeof h!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",h)}function ge(h,_,A){throw Math.floor(h)!==h?(J(h,A),new G.ERR_OUT_OF_RANGE("offset","an integer",h)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,h)}let se=/[^+/0-9A-Za-z-_]/g;function L(h){if(h=h.split("=")[0],h=h.trim().replace(se,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function q(h,_){_=_||1/0;let A,D=h.length,X=null,de=[];for(let _e=0;_e<D;++_e){if(A=h.charCodeAt(_e),A>55295&&A<57344){if(!X){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===D){(_-=3)>-1&&de.push(239,191,189);continue}X=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(_-=3)>-1&&de.push(239,191,189);if(X=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function ee(h){let _=[];for(let A=0;A<h.length;++A)_.push(h.charCodeAt(A)&255);return _}function he(h,_){let A,D,X,de=[];for(let _e=0;_e<h.length&&!((_-=2)<0);++_e)A=h.charCodeAt(_e),D=A>>8,X=A%256,de.push(X),de.push(D);return de}function fe(h){return i.toByteArray(L(h))}function be(h,_,A,D){let X;for(X=0;X<D&&!(X+A>=_.length||X>=h.length);++X)_[X+A]=h[X];return X}function H(h,_){return h instanceof _||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===_.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let D=A*16;for(let X=0;X<16;++X)_[D+X]=h[A]+h[X]}return _})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return kt}var qt,yi,rr,bi,kt,vi,Vc=Ye(()=>{le(),ue(),ce(),qt={},yi=!1,rr={},bi=!1,kt={},vi=!1}),$e={};$t($e,{Buffer:()=>kr,INSPECT_MAX_BYTES:()=>as,default:()=>ht,kMaxLength:()=>ls});var ht,kr,as,ls,qe=Ye(()=>{le(),ue(),ce(),Vc(),ht=zc(),ht.Buffer,ht.SlowBuffer,ht.INSPECT_MAX_BYTES,ht.kMaxLength,kr=ht.Buffer,as=ht.INSPECT_MAX_BYTES,ls=ht.kMaxLength}),ue=Ye(()=>{qe()}),De=pe((i,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}}),cs=pe((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,n]){let o=r.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.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"{}"}}}}),Ke=pe((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=cs(),{AggregateError:s}=De(),n=globalThis.AggregateError||s,o=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function p(m){let k="",S=m.length,v=m[0]==="-"?1:0;for(;S>=v+4;S-=3)k=`_${m.slice(S-3,S)}${k}`;return`${m.slice(0,S)}${k}`}function g(m,k,S){if(typeof k=="function")return d(k.length<=S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${k.length}).`),k(...S);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${v}).`),S.length===0?k:t(k,...S)}function f(m,k,S){S||(S=Error);class v extends S{constructor(...E){super(g(m,k,E))}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[o]=!0,u[m]=v}function y(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function b(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let S=new n([k,m],k.message);return S.code=k.code,S}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,k,S)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let x=[],E=[],I=[];for(let C of k)d(typeof C=="string","All expected entries have to be of type string"),a.includes(C)?x.push(C.toLowerCase()):l.test(C)?E.push(C):(d(C!=="object",'The value "object" should be written as "Object"'),I.push(C));if(E.length>0){let C=x.indexOf("object");C!==-1&&(x.splice(x,C,1),E.push("Object"))}if(x.length>0){switch(x.length){case 1:v+=`of type ${x[0]}`;break;case 2:v+=`one of type ${x[0]} or ${x[1]}`;break;default:{let C=x.pop();v+=`one of type ${x.join(", ")}, or ${C}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let C=E.pop();v+=`an instance of ${E.join(", ")}, or ${C}`}}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 C=I.pop();v+=`one of ${I.join(", ")}, or ${C}`}}if(S==null)v+=`. Received ${S}`;else if(typeof S=="function"&&S.name)v+=`. Received function ${S.name}`;else if(typeof S=="object"){var O;if((O=S.constructor)!==null&&O!==void 0&&O.name)v+=`. Received an instance of ${S.constructor.name}`;else{let C=r(S,{depth:-1});v+=`. Received ${C}`}}else{let C=r(S,{colors:!1});C.length>25&&(C=`${C.slice(0,25)}...`),v+=`. Received type ${typeof S} (${C})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,k,S="is invalid")=>{let v=r(k);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,k,S)=>{var v;let x=S!=null&&(v=S.constructor)!==null&&v!==void 0&&v.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${m} to be returned from the "${k}" function but got ${x}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,S=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),S){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,k,S)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(S)&&Math.abs(S)>2**32)v=p(String(S));else if(typeof S=="bigint"){v=String(S);let x=BigInt(2)**BigInt(32);(S>x||S<-x)&&(v=p(v)),v+="n"}else v=r(S);return`The value of "${m}" is out of range. It must be ${k}. 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:w,aggregateTwoErrors:y(b),hideStackFrames:y,codes:u}}),nr=pe((i,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}),_t={};$t(_t,{EventEmitter:()=>us,default:()=>Ht,defaultMaxListeners:()=>ds,init:()=>hs,listenerCount:()=>fs,on:()=>ps,once:()=>ms});function Kc(){if(wi)return ir;wi=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,v,x){return Function.prototype.apply.call(S,v,x)},t;i&&typeof i.ownKeys=="function"?t=i.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)}ir=n,ir.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(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 o},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+".");o=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 l(S){return S._maxListeners===void 0?n.defaultMaxListeners:S._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(S){for(var v=[],x=1;x<arguments.length;x++)v.push(arguments[x]);var E=S==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var O;if(v.length>0&&(O=v[0]),O instanceof Error)throw O;var C=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw C.context=O,C}var j=I[S];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,$=f(j,T),x=0;x<T;++x)e($[x],this,v);return!0};function c(S,v,x,E){var I,O,C;if(a(x),O=S._events,O===void 0?(O=S._events=Object.create(null),S._eventsCount=0):(O.newListener!==void 0&&(S.emit("newListener",v,x.listener?x.listener:x),O=S._events),C=O[v]),C===void 0)C=O[v]=x,++S._eventsCount;else if(typeof C=="function"?C=O[v]=E?[x,C]:[C,x]:E?C.unshift(x):C.push(x),I=l(S),I>0&&C.length>I&&!C.warned){C.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+C.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=S,j.type=v,j.count=C.length,r(j)}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 d(S,v,x){var E={fired:!1,wrapFn:void 0,target:S,type:v,listener:x},I=u.bind(E);return I.listener=x,E.wrapFn=I,I}n.prototype.once=function(S,v){return a(v),this.on(S,d(this,S,v)),this},n.prototype.prependOnceListener=function(S,v){return a(v),this.prependListener(S,d(this,S,v)),this},n.prototype.removeListener=function(S,v){var x,E,I,O,C;if(a(v),E=this._events,E===void 0)return this;if(x=E[S],x===void 0)return this;if(x===v||x.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[S],E.removeListener&&this.emit("removeListener",S,x.listener||v));else if(typeof x!="function"){for(I=-1,O=x.length-1;O>=0;O--)if(x[O]===v||x[O].listener===v){C=x[O].listener,I=O;break}if(I<0)return this;I===0?x.shift():y(x,I),x.length===1&&(E[S]=x[0]),E.removeListener!==void 0&&this.emit("removeListener",S,C||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(S){var v,x,E;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[S]),this;if(arguments.length===0){var I=Object.keys(x),O;for(E=0;E<I.length;++E)O=I[E],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=x[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(S,v[E]);return this};function p(S,v,x){var E=S._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?x?[I.listener||I]:[I]:x?b(I):f(I,I.length)}n.prototype.listeners=function(S){return p(this,S,!0)},n.prototype.rawListeners=function(S){return p(this,S,!1)},n.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):g.call(S,v)},n.prototype.listenerCount=g;function g(S){var v=this._events;if(v!==void 0){var x=v[S];if(typeof x=="function")return 1;if(x!==void 0)return x.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(S,v){for(var x=new Array(v),E=0;E<v;++E)x[E]=S[E];return x}function y(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function b(S){for(var v=new Array(S.length),x=0;x<v.length;++x)v[x]=S[x].listener||S[x];return v}function w(S,v){return new Promise(function(x,E){function I(C){S.removeListener(v,O),E(C)}function O(){typeof S.removeListener=="function"&&S.removeListener("error",I),x([].slice.call(arguments))}k(S,v,O,{once:!0}),v!=="error"&&m(S,I,{once:!0})})}function m(S,v,x){typeof S.on=="function"&&k(S,"error",v,x)}function k(S,v,x,E){if(typeof S.on=="function")E.once?S.once(v,x):S.on(v,x);else if(typeof S.addEventListener=="function")S.addEventListener(v,function I(O){E.once&&S.removeEventListener(v,I),x(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return ir}var ir,wi,Ht,us,ds,hs,fs,ps,ms,Lt=Ye(()=>{le(),ue(),ce(),ir={},wi=!1,Ht=Kc(),Ht.once,Ht.once=function(i,e){return new Promise((t,r)=>{function s(...o){n!==void 0&&i.removeListener("error",n),t(o)}let n;e!=="error"&&(n=o=>{i.removeListener(name,s),r(o)},i.once("error",n)),i.once(e,s)})},Ht.on=function(i,e){let t=[],r=[],s=null,n=!1,o={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,d)=>r.push({resolve:u,reject:d}))},async return(){i.removeListener(e,a),i.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),o;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):s=c,o.return()}},{EventEmitter:us,defaultMaxListeners:ds,init:hs,listenerCount:fs,on:ps,once:ms}=Ht}),Je=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),{format:r,inspect:s}=cs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:o,AggregateError:a,SymbolDispose:l}=De(),c=globalThis.AbortSignal||nr().AbortSignal,u=globalThis.AbortController||nr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,w)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(w,"AbortSignal",b)},y=(b,w)=>{if(typeof b!="function")throw new n(w,"Function",b)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(b){let w=!1;return function(...m){w||(w=!0,b.apply(this,m))}},createDeferredPromise:function(){let b,w;return{promise:new Promise((m,k)=>{b=m,w=k}),resolve:b,reject:w}},promisify(b){return new Promise((w,m)=>{b((k,...S)=>k?m(k):w(...S))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:g,deprecate(b,w){return b},addAbortListener:(Lt(),Ne(_t)).addAbortListener||function(b,w){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),y(w,"listener");let m;return b.aborted?queueMicrotask(()=>w()):(b.addEventListener("abort",w,{__proto__:null,once:!0,[o]:!0}),m=()=>{b.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(b){if(b.length===1)return b[0];let w=new u,m=()=>w.abort();return b.forEach(k=>{f(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{b.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),or=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:o,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:y}=De(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:x}=Je(),{isAsyncFunction:E,isArrayBufferView:I}=Je().types,O={};function C(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,$="must be a 32-bit unsigned integer or an octal string";function B(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new k(me,H,$);H=u(H,8)}return K(H,me),H}var U=b((H,me,ve=c,ae=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);if(H<ve||H>ae)throw new S(me,`>= ${ve} && <= ${ae}`,H)}),oe=b((H,me,ve=-2147483648,ae=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);if(H<ve||H>ae)throw new S(me,`>= ${ve} && <= ${ae}`,H)}),K=b((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);let ae=ve?1:0,Oe=4294967295;if(H<ae||H>Oe)throw new S(me,`>= ${ae} && <= ${Oe}`,H)});function W(H,me){if(typeof H!="string")throw new m(me,"string",H)}function re(H,me,ve=void 0,ae){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||ae!=null&&H>ae||(ve!=null||ae!=null)&&a(H))throw new S(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,H)}var F=b((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+s(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:g(Oe)),", ");throw new k(me,H,ae)}});function Z(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function M(H,me,ve){return H==null||!d(H,me)?ve:H[me]}var Q=b((H,me,ve=null)=>{let ae=M(ve,"allowArray",!1),Oe=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Oe||typeof H!="function"))throw new m(me,"Object",H)}),ye=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 ae=`must be longer than ${ve}`;throw new k(me,H,ae)}});function we(H,me){te(H,me);for(let ve=0;ve<H.length;ve++)W(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 N(H,me){te(H,me);for(let ve=0;ve<H.length;ve++){let ae=H[ve],Oe=`${me}[${ve}]`;if(ae==null)throw new m(Oe,"AbortSignal",ae);ge(ae,Oe)}}function ne(H,me="signal"){if(W(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 z=b((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function Y(H,me){let ve=x(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new k("encoding",me,`is invalid for data of length ${ae}`)}function J(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&y(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(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)}),se=b((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),L=b((H,me)=>{if(typeof H!="function"||E(H))throw new m(me,"Function",H)}),q=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 he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function be(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 ae=0;ae<me;ae++){let Oe=H[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:C,isUint32:j,parseFileMode:B,validateArray:te,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:N,validateBoolean:Z,validateBuffer:z,validateDictionary:ye,validateEncoding:Y,validateFunction:se,validateInt32:oe,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:F,validatePlainFunction:L,validatePort:J,validateSignalName:ne,validateString:W,validateUint32:K,validateUndefined:q,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:be}}),Rt=pe((i,e)=>{le(),ue(),ce();var t=e.exports={},r,s;function n(){throw new Error("setTimeout has not been defined")}function o(){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=o}catch{s=o}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(s===clearTimeout)return clearTimeout(w);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(w);try{return s(w)}catch{try{return s.call(null,w)}catch{return s.call(this,w)}}}var c=[],u=!1,d,p=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++p<m;)d&&d[p].run();p=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new y(w,m)),c.length===1&&!u&&a(f)};function y(w,m){this.fun=w,this.array=m}y.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(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),ft=pe((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=De(),n=s("nodejs.stream.destroyed"),o=s("nodejs.stream.errored"),a=s("nodejs.stream.readable"),l=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),d=s("nodejs.webstream.controllerErrorFunction");function p(M,Q=!1){var ye;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((ye=M._readableState)===null||ye===void 0?void 0:ye.readable)!==!1)&&(!M._writableState||M._readableState))}function g(M){var Q;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((Q=M._writableState)===null||Q===void 0?void 0:Q.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function y(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&&!y(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!y(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!y(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function k(M){return b(M)||w(M)||m(M)}function S(M,Q){return M==null?!1:Q===!0?typeof M[t]=="function":Q===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!y(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function x(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let Q=M._writableState;return Q!=null&&Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function E(M,Q){if(!g(M))return null;if(M.writableFinished===!0)return!0;let ye=M._writableState;return ye!=null&&ye.errored?!1:typeof ye?.finished!="boolean"?null:!!(ye.finished||Q===!1&&ye.ended===!0&&ye.length===0)}function I(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let Q=M._readableState;return!Q||Q.errored?!1:typeof Q?.ended!="boolean"?null:Q.ended}function O(M,Q){if(!p(M))return null;let ye=M._readableState;return ye!=null&&ye.errored?!1:typeof ye?.endEmitted!="boolean"?null:!!(ye.endEmitted||Q===!1&&ye.ended===!0&&ye.length===0)}function C(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!O(M)}function j(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!x(M)}function T(M,Q){return y(M)?v(M)?!0:!(Q?.readable!==!1&&C(M)||Q?.writable!==!1&&j(M)):null}function $(M){var Q,ye;return y(M)?M.writableErrored?M.writableErrored:(Q=(ye=M._writableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function B(M){var Q,ye;return y(M)?M.readableErrored?M.readableErrored:(Q=(ye=M._readableState)===null||ye===void 0?void 0:ye.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!y(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,ye=M._readableState;return typeof Q?.closed=="boolean"||typeof ye?.closed=="boolean"?Q?.closed||ye?.closed:typeof M._closed=="boolean"&&oe(M)?M._closed:null}function oe(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function K(M){return typeof M._sent100=="boolean"&&oe(M)}function W(M){var Q;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((Q=M.req)===null||Q===void 0?void 0:Q.upgradeOrConnect)===void 0}function re(M){if(!y(M))return null;let Q=M._writableState,ye=M._readableState,te=Q||ye;return!te&&K(M)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function F(M){var Q;return!!(M&&((Q=M[c])!==null&&Q!==void 0?Q:M.readableDidRead||M.readableAborted))}function Z(M){var Q,ye,te,we,G,N,ne,z,Y,J;return!!(M&&((Q=(ye=(te=(we=(G=(N=M[o])!==null&&N!==void 0?N: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:(z=M._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&ye!==void 0?ye:(Y=M._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&Q!==void 0?Q:!((J=M._writableState)===null||J===void 0)&&J.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:Z,kIsErrored:o,isReadable:C,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:S,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:O,isReadableErrored:B,isNodeStream:y,isWebStream:k,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:x,isWritableFinished:E,isWritableErrored:$,isServerRequest:W,isServerResponse:K,willEmitClose:re,isTransformStream:m}}),St=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{AbortError:r,codes:s}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:o}=s,{kEmptyObject:a,once:l}=Je(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=or(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:y}=De(),{isClosed:b,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:S,isReadableErrored:v,isWritable:x,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:O,isWritableErrored:C,isNodeStream:j,willEmitClose:T,kIsClosedPromise:$}=ft(),B;function U(F){return F.setHeader&&typeof F.abort=="function"}var oe=()=>{};function K(F,Z,M){var Q,ye;if(arguments.length===2?(M=Z,Z=a):Z==null?Z=a:d(Z,"options"),u(M,"callback"),c(Z.signal,"options.signal"),M=l(M),k(F)||I(F))return W(F,Z,M);if(!j(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let te=(Q=Z.readable)!==null&&Q!==void 0?Q:m(F),we=(ye=Z.writable)!==null&&ye!==void 0?ye:E(F),G=F._writableState,N=F._readableState,ne=()=>{F.writable||J()},z=T(F)&&m(F)===te&&E(F)===we,Y=O(F,!1),J=()=>{Y=!0,F.destroyed&&(z=!1),!(z&&(!F.readable||te))&&(!te||ge)&&M.call(F)},ge=S(F,!1),se=()=>{ge=!0,F.destroyed&&(z=!1),!(z&&(!F.writable||we))&&(!we||Y)&&M.call(F)},L=H=>{M.call(F,H)},q=b(F),ee=()=>{q=!0;let H=C(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 o);if(we&&!Y&&!O(F,!1))return M.call(F,new o);M.call(F)},he=()=>{q=!0;let H=C(F)||v(F);if(H&&typeof H!="boolean")return M.call(F,H);M.call(F)},fe=()=>{F.req.on("finish",J)};U(F)?(F.on("complete",J),z||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!z&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",se),F.on("finish",J),Z.error!==!1&&F.on("error",L),F.on("close",ee),q?t.nextTick(ee):G!=null&&G.errorEmitted||N!=null&&N.errorEmitted?z||t.nextTick(he):(!te&&(!z||w(F))&&(Y||x(F)===!1)||!we&&(!z||x(F))&&(ge||w(F)===!1)||N&&F.req&&F.aborted)&&t.nextTick(he);let be=()=>{M=oe,F.removeListener("aborted",ee),F.removeListener("complete",J),F.removeListener("abort",ee),F.removeListener("request",fe),F.req&&F.req.removeListener("finish",J),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",J),F.removeListener("end",se),F.removeListener("error",L),F.removeListener("close",ee)};if(Z.signal&&!q){let H=()=>{let me=M;be(),me.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{B=B||Je().addAbortListener;let me=B(Z.signal,H),ve=M;M=l((...ae)=>{me[y](),ve.apply(F,ae)})}}return be}function W(F,Z,M){let Q=!1,ye=oe;if(Z.signal)if(ye=()=>{Q=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(ye);else{B=B||Je().addAbortListener;let we=B(Z.signal,ye),G=M;M=l((...N)=>{we[y](),G.apply(F,N)})}let te=(...we)=>{Q||t.nextTick(()=>M.apply(F,we))};return f(F[$].promise,te,te),oe}function re(F,Z){var M;let Q=!1;return Z===null&&(Z=a),(M=Z)!==null&&M!==void 0&&M.cleanup&&(p(Z.cleanup,"cleanup"),Q=Z.cleanup),new g((ye,te)=>{let we=K(F,Z,G=>{Q&&we(),G?te(G):ye()})})}e.exports=K,e.exports.finished=re}),Wt=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=Ke(),{Symbol:o}=De(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=ft(),d=o("kDestroy"),p=o("kConstruct");function g(T,$,B){T&&(T.stack,$&&!$.errored&&($.errored=T),B&&!B.errored&&(B.errored=T))}function f(T,$){let B=this._readableState,U=this._writableState,oe=U||B;return U!=null&&U.destroyed||B!=null&&B.destroyed?(typeof $=="function"&&$(),this):(g(T,U,B),U&&(U.destroyed=!0),B&&(B.destroyed=!0),oe.constructed?y(this,T,$):this.once(d,function(K){y(this,r(K,T),$)}),this)}function y(T,$,B){let U=!1;function oe(K){if(U)return;U=!0;let W=T._readableState,re=T._writableState;g(K,re,W),re&&(re.closed=!0),W&&(W.closed=!0),typeof B=="function"&&B(K),K?t.nextTick(b,T,K):t.nextTick(w,T)}try{T._destroy($||null,oe)}catch(K){oe(K)}}function b(T,$){m(T,$),w(T)}function w(T){let $=T._readableState,B=T._writableState;B&&(B.closeEmitted=!0),$&&($.closeEmitted=!0),(B!=null&&B.emitClose||$!=null&&$.emitClose)&&T.emit("close")}function m(T,$){let B=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||B!=null&&B.errorEmitted||(U&&(U.errorEmitted=!0),B&&(B.errorEmitted=!0),T.emit("error",$))}function k(){let T=this._readableState,$=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),$&&($.constructed=!0,$.destroyed=!1,$.closed=!1,$.closeEmitted=!1,$.errored=null,$.errorEmitted=!1,$.finalCalled=!1,$.prefinished=!1,$.ended=$.writable===!1,$.ending=$.writable===!1,$.finished=$.writable===!1)}function S(T,$,B){let U=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy($):$&&($.stack,oe&&!oe.errored&&(oe.errored=$),U&&!U.errored&&(U.errored=$),B?t.nextTick(m,T,$):m(T,$))}function v(T,$){if(typeof T._construct!="function")return;let B=T._readableState,U=T._writableState;B&&(B.constructed=!1),U&&(U.constructed=!1),T.once(p,$),!(T.listenerCount(p)>1)&&t.nextTick(x,T)}function x(T){let $=!1;function B(U){if($){S(T,U??new s);return}$=!0;let oe=T._readableState,K=T._writableState,W=K||oe;oe&&(oe.constructed=!0),K&&(K.constructed=!0),W.destroyed?T.emit(d,U):U?S(T,U,!0):t.nextTick(E,T)}try{T._construct(U=>{t.nextTick(B,U)})}catch(U){t.nextTick(B,U)}}function E(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function O(T){T.emit("close")}function C(T,$){T.emit("error",$),t.nextTick(O,T)}function j(T,$){!T||l(T)||(!$&&!c(T)&&($=new n),u(T)?(T.socket=null,T.destroy($)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy($):typeof T.close=="function"?T.close():$?t.nextTick(C,T,$):t.nextTick(O,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:j,destroy:f,undestroy:k,errorOrDestroy:S}}),ki=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=De(),{EventEmitter:s}=(Lt(),Ne(_t));function n(a){s.call(this,a)}r(n.prototype,s.prototype),r(n,s),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",f));let p=!1;function g(){p||(p=!0,a.end())}function f(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function y(w){b(),s.listenerCount(this,"error")===0&&this.emit("error",w)}o(c,"error",y),o(a,"error",y);function b(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",y),a.removeListener("error",y),c.removeListener("end",b),c.removeListener("close",b),a.removeListener("close",b)}return c.on("end",b),c.on("close",b),a.on("close",b),a.emit("pipe",c),a};function o(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:o}}),_r=pe((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=De(),{AbortError:r,codes:s}=Ke(),{isNodeStream:n,isWebStream:o,kControllerErrorFunction:a}=ft(),l=St(),{ERR_INVALID_ARG_TYPE:c}=s,u,d=(p,g)=>{if(typeof p!="object"||!("aborted"in p))throw new c(g,"AbortSignal",p)};e.exports.addAbortSignal=function(p,g){if(d(p,"signal"),!n(g)&&!o(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(p,g)},e.exports.addAbortSignalNoValidate=function(p,g){if(typeof p!="object"||!("aborted"in p))return g;let f=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[a](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Je().addAbortListener;let y=u(p,f);l(g,y[t])}return g}}),Gc=pe((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=De(),{Buffer:o}=(qe(),Ne($e)),{inspect:a}=Je();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return o.alloc(0);let c=o.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)s(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=o.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)s(c,g,u-l),l-=g.length;else{l===g.length?(s(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(s(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Sr=pe((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=De(),{validateInteger:s}=or(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,o=16*1024,a=16;function l(p,g,f){return p.highWaterMark!=null?p.highWaterMark:g?p[f]:null}function c(p){return p?a:o}function u(p,g){s(g,"value",0),p?a=g:o=g}function d(p,g,f,y){let b=l(g,y,f);if(b!=null){if(!r(b)||b<0){let w=y?`options.${f}`:"options.highWaterMark";throw new n(w,b)}return t(b)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Yc=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),r=t.Buffer;function s(o,a){for(var l in o)a[l]=o[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,i),i.Buffer=n);function n(o,a,l){return r(o,a,l)}n.prototype=Object.create(r.prototype),s(r,n),n.from=function(o,a,l){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,a,l)},n.alloc=function(o,a,l){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},n.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}}),Jc=pe(i=>{le(),ue(),ce();var e=Yc().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 k;;)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(k)return;m=(""+m).toLowerCase(),k=!0}}function s(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=s(m);var k;switch(this.encoding){case"utf16le":this.text=p,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=f,this.end=y,k=3;break;default:this.write=b,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,S;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";S=this.lastNeed,this.lastNeed=0}else S=0;return S<m.length?k?k+this.text(m,S):this.text(m,S):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function o(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,S){var v=k.length-1;if(v<S)return 0;var x=o(k[v]);return x>=0?(x>0&&(m.lastNeed=x-1),x):--v<S||x===-2?0:(x=o(k[v]),x>=0?(x>0&&(m.lastNeed=x-2),x):--v<S||x===-2?0:(x=o(k[v]),x>=0?(x>0&&(x===2?x=0:m.lastNeed=x-3),x):0))}function l(m,k,S){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,S=l(this,m);if(S!==void 0)return S;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var S=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=S;var v=m.length-(S-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function p(m,k){if((m.length-k)%2===0){var S=m.toString("utf16le",k);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",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var S=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,S)}return k}function f(m,k){var S=(m.length-k)%3;return S===0?m.toString("base64",k):(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",k,m.length-S))}function y(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function b(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),gs=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=De(),{Buffer:o}=(qe(),Ne($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,p){let g;if(typeof d=="string"||d instanceof o)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[s])f=!0,g=d[s]();else if(d&&d[n])f=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let y=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;y._read=function(){b||(b=!0,m())},y._destroy=function(k,S){r(w(k),()=>t.nextTick(S,k),v=>t.nextTick(S,v||k))};async function w(k){let S=k!=null,v=typeof g.throw=="function";if(S&&v){let{value:x,done:E}=await g.throw(k);if(await x,E)return}if(typeof g.return=="function"){let{value:x}=await g.return();await x}}async function m(){for(;;){try{let{value:k,done:S}=f?await g.next():g.next();if(S)y.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw b=!1,new l;if(y.push(v))continue;b=!1}}catch(k){y.destroy(k)}break}}return y}e.exports=c}),xr=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:o,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:f}=De();e.exports=ae,ae.ReadableState=ve;var{EventEmitter:y}=(Lt(),Ne(_t)),{Stream:b,prependListener:w}=ki(),{Buffer:m}=(qe(),Ne($e)),{addAbortSignal:k}=_r(),S=St(),v=Je().debuglog("stream",P=>{v=P}),x=Gc(),E=Wt(),{getHighWaterMark:I,getDefaultHighWaterMark:O}=Sr(),{aggregateTwoErrors:C,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:$,ERR_STREAM_PUSH_AFTER_EOF:B,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:oe}=Ke(),{validateObject:K}=or(),W=f("kPaused"),{StringDecoder:re}=Jc(),F=gs();c(ae.prototype,b.prototype),c(ae,b);var Z=()=>{},{errorOrDestroy:M}=E,Q=1,ye=2,te=4,we=8,G=16,N=32,ne=64,z=128,Y=256,J=512,ge=1024,se=2048,L=4096,q=8192,ee=16384,he=32768,fe=65536,be=1<<17,H=1<<18;function me(P){return{enumerable:!1,get(){return(this.state&P)!==0},set(R){R?this.state|=P:this.state&=~P}}}a(ve.prototype,{objectMode:me(Q),ended:me(ye),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(N),needReadable:me(ne),emittedReadable:me(z),readableListening:me(Y),resumeScheduled:me(J),errorEmitted:me(ge),emitClose:me(se),autoDestroy:me(L),destroyed:me(q),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(be),dataEmitted:me(H)});function ve(P,R,ke){typeof ke!="boolean"&&(ke=R instanceof pt()),this.state=se|L|G|N,P&&P.objectMode&&(this.state|=Q),ke&&P&&P.readableObjectMode&&(this.state|=Q),this.highWaterMark=P?I(this,P,"readableHighWaterMark",ke):O(!1),this.buffer=new x,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,P&&P.emitClose===!1&&(this.state&=~se),P&&P.autoDestroy===!1&&(this.state&=~L),this.errored=null,this.defaultEncoding=P&&P.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,P&&P.encoding&&(this.decoder=new re(P.encoding),this.encoding=P.encoding)}function ae(P){if(!(this instanceof ae))return new ae(P);let R=this instanceof pt();this._readableState=new ve(P,this,R),P&&(typeof P.read=="function"&&(this._read=P.read),typeof P.destroy=="function"&&(this._destroy=P.destroy),typeof P.construct=="function"&&(this._construct=P.construct),P.signal&&!R&&k(P.signal,this)),b.call(this,P),E.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(P,R){R(P)},ae.prototype[y.captureRejectionSymbol]=function(P){this.destroy(P)},ae.prototype[p]=function(){let P;return this.destroyed||(P=this.readableEnded?null:new oe,this.destroy(P)),new u((R,ke)=>S(this,xe=>xe&&xe!==P?ke(xe):R(null)))},ae.prototype.push=function(P,R){return Oe(this,P,R,!1)},ae.prototype.unshift=function(P,R){return Oe(this,P,R,!0)};function Oe(P,R,ke,xe){v("readableAddChunk",R);let Ae=P._readableState,Fe;if((Ae.state&Q)===0&&(typeof R=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(xe&&Ae.encoding?R=m.from(R,ke).toString(Ae.encoding):(R=m.from(R,ke),ke=""))):R instanceof m?ke="":b._isUint8Array(R)?(R=b._uint8ArrayToBuffer(R),ke=""):R!=null&&(Fe=new j("chunk",["string","Buffer","Uint8Array"],R))),Fe)M(P,Fe);else if(R===null)Ae.state&=~we,X(P,Ae);else if((Ae.state&Q)!==0||R&&R.length>0)if(xe)if((Ae.state&te)!==0)M(P,new U);else{if(Ae.destroyed||Ae.errored)return!1;h(P,Ae,R,!0)}else if(Ae.ended)M(P,new B);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~we,Ae.decoder&&!ke?(R=Ae.decoder.write(R),Ae.objectMode||R.length!==0?h(P,Ae,R,!1):V(P,Ae)):h(P,Ae,R,!1)}else xe||(Ae.state&=~we,V(P,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function h(P,R,ke,xe){R.flowing&&R.length===0&&!R.sync&&P.listenerCount("data")>0?((R.state&fe)!==0?R.awaitDrainWriters.clear():R.awaitDrainWriters=null,R.dataEmitted=!0,P.emit("data",ke)):(R.length+=R.objectMode?1:ke.length,xe?R.buffer.unshift(ke):R.buffer.push(ke),(R.state&ne)!==0&&de(P)),V(P,R)}ae.prototype.isPaused=function(){let P=this._readableState;return P[W]===!0||P.flowing===!1},ae.prototype.setEncoding=function(P){let R=new re(P);this._readableState.decoder=R,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,xe="";for(let Ae of ke)xe+=R.write(Ae);return ke.clear(),xe!==""&&ke.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(P){if(P>_)throw new $("size","<= 1GiB",P);return P--,P|=P>>>1,P|=P>>>2,P|=P>>>4,P|=P>>>8,P|=P>>>16,P++,P}function D(P,R){return P<=0||R.length===0&&R.ended?0:(R.state&Q)!==0?1:n(P)?R.flowing&&R.length?R.buffer.first().length:R.length:P<=R.length?P:R.ended?R.length:0}ae.prototype.read=function(P){v("read",P),P===void 0?P=NaN:s(P)||(P=o(P,10));let R=this._readableState,ke=P;if(P>R.highWaterMark&&(R.highWaterMark=A(P)),P!==0&&(R.state&=~z),P===0&&R.needReadable&&((R.highWaterMark!==0?R.length>=R.highWaterMark:R.length>0)||R.ended))return v("read: emitReadable",R.length,R.ended),R.length===0&&R.ended?at(this):de(this),null;if(P=D(P,R),P===0&&R.ended)return R.length===0&&at(this),null;let xe=(R.state&ne)!==0;if(v("need readable",xe),(R.length===0||R.length-P<R.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),R.ended||R.reading||R.destroyed||R.errored||!R.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),R.state|=we|N,R.length===0&&(R.state|=ne);try{this._read(R.highWaterMark)}catch(Fe){M(this,Fe)}R.state&=~N,R.reading||(P=D(ke,R))}let Ae;return P>0?Ae=Xt(P,R):Ae=null,Ae===null?(R.needReadable=R.length<=R.highWaterMark,P=0):(R.length-=P,R.multiAwaitDrain?R.awaitDrainWriters.clear():R.awaitDrainWriters=null),R.length===0&&(R.ended||(R.needReadable=!0),ke!==P&&R.ended&&at(this)),Ae!==null&&!R.errorEmitted&&!R.closeEmitted&&(R.dataEmitted=!0,this.emit("data",Ae)),Ae};function X(P,R){if(v("onEofChunk"),!R.ended){if(R.decoder){let ke=R.decoder.end();ke&&ke.length&&(R.buffer.push(ke),R.length+=R.objectMode?1:ke.length)}R.ended=!0,R.sync?de(P):(R.needReadable=!1,R.emittedReadable=!0,_e(P))}}function de(P){let R=P._readableState;v("emitReadable",R.needReadable,R.emittedReadable),R.needReadable=!1,R.emittedReadable||(v("emitReadable",R.flowing),R.emittedReadable=!0,t.nextTick(_e,P))}function _e(P){let R=P._readableState;v("emitReadable_",R.destroyed,R.length,R.ended),!R.destroyed&&!R.errored&&(R.length||R.ended)&&(P.emit("readable"),R.emittedReadable=!1),R.needReadable=!R.flowing&&!R.ended&&R.length<=R.highWaterMark,ot(P)}function V(P,R){!R.readingMore&&R.constructed&&(R.readingMore=!0,t.nextTick(ie,P,R))}function ie(P,R){for(;!R.reading&&!R.ended&&(R.length<R.highWaterMark||R.flowing&&R.length===0);){let ke=R.length;if(v("maybeReadMore read 0"),P.read(0),ke===R.length)break}R.readingMore=!1}ae.prototype._read=function(P){throw new T("_read()")},ae.prototype.pipe=function(P,R){let ke=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(P),v("pipe count=%d opts=%j",xe.pipes.length,R);let Ae=(!R||R.end!==!1)&&P!==t.stdout&&P!==t.stderr?Ge:Ft;xe.endEmitted?t.nextTick(Ae):ke.once("end",Ae),P.on("unpipe",Fe);function Fe(ct,wt){v("onunpipe"),ct===ke&&wt&&wt.hasUnpiped===!1&&(wt.hasUnpiped=!0,pr())}function Ge(){v("onend"),P.end()}let et,fr=!1;function pr(){v("cleanup"),P.removeListener("close",lt),P.removeListener("finish",Pt),et&&P.removeListener("drain",et),P.removeListener("error",Dt),P.removeListener("unpipe",Fe),ke.removeListener("end",Ge),ke.removeListener("end",Ft),ke.removeListener("data",sn),fr=!0,et&&xe.awaitDrainWriters&&(!P._writableState||P._writableState.needDrain)&&et()}function mr(){fr||(xe.pipes.length===1&&xe.pipes[0]===P?(v("false write response, pause",0),xe.awaitDrainWriters=P,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(P)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(P)),ke.pause()),et||(et=Ie(ke,P),P.on("drain",et))}ke.on("data",sn);function sn(ct){v("ondata");let wt=P.write(ct);v("dest.write",wt),wt===!1&&mr()}function Dt(ct){if(v("onerror",ct),Ft(),P.removeListener("error",Dt),P.listenerCount("error")===0){let wt=P._writableState||P._readableState;wt&&!wt.errorEmitted?M(P,ct):P.emit("error",ct)}}w(P,"error",Dt);function lt(){P.removeListener("finish",Pt),Ft()}P.once("close",lt);function Pt(){v("onfinish"),P.removeListener("close",lt),Ft()}P.once("finish",Pt);function Ft(){v("unpipe"),ke.unpipe(P)}return P.emit("pipe",ke),P.writableNeedDrain===!0?mr():xe.flowing||(v("pipe resume"),ke.resume()),P};function Ie(P,R){return function(){let ke=P._readableState;ke.awaitDrainWriters===R?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(R)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&P.listenerCount("data")&&P.resume()}}ae.prototype.unpipe=function(P){let R=this._readableState,ke={hasUnpiped:!1};if(R.pipes.length===0)return this;if(!P){let Ae=R.pipes;R.pipes=[],this.pause();for(let Fe=0;Fe<Ae.length;Fe++)Ae[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(R.pipes,P);return xe===-1?this:(R.pipes.splice(xe,1),R.pipes.length===0&&this.pause(),P.emit("unpipe",this,ke),this)},ae.prototype.on=function(P,R){let ke=b.prototype.on.call(this,P,R),xe=this._readableState;return P==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):P==="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?de(this):xe.reading||t.nextTick(Pe,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(P,R){let ke=b.prototype.removeListener.call(this,P,R);return P==="readable"&&t.nextTick(Te,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(P){let R=b.prototype.removeAllListeners.apply(this,arguments);return(P==="readable"||P===void 0)&&t.nextTick(Te,this),R};function Te(P){let R=P._readableState;R.readableListening=P.listenerCount("readable")>0,R.resumeScheduled&&R[W]===!1?R.flowing=!0:P.listenerCount("data")>0?P.resume():R.readableListening||(R.flowing=null)}function Pe(P){v("readable nexttick read 0"),P.read(0)}ae.prototype.resume=function(){let P=this._readableState;return P.flowing||(v("resume"),P.flowing=!P.readableListening,Le(this,P)),P[W]=!1,this};function Le(P,R){R.resumeScheduled||(R.resumeScheduled=!0,t.nextTick(it,P,R))}function it(P,R){v("resume",R.reading),R.reading||P.read(0),R.resumeScheduled=!1,P.emit("resume"),ot(P),R.flowing&&!R.reading&&P.read(0)}ae.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[W]=!0,this};function ot(P){let R=P._readableState;for(v("flow",R.flowing);R.flowing&&P.read()!==null;);}ae.prototype.wrap=function(P){let R=!1;P.on("data",xe=>{!this.push(xe)&&P.pause&&(R=!0,P.pause())}),P.on("end",()=>{this.push(null)}),P.on("error",xe=>{M(this,xe)}),P.on("close",()=>{this.destroy()}),P.on("destroy",()=>{this.destroy()}),this._read=()=>{R&&P.resume&&(R=!1,P.resume())};let ke=l(P);for(let xe=1;xe<ke.length;xe++){let Ae=ke[xe];this[Ae]===void 0&&typeof P[Ae]=="function"&&(this[Ae]=P[Ae].bind(P))}return this},ae.prototype[g]=function(){return Ve(this)},ae.prototype.iterator=function(P){return P!==void 0&&K(P,"options"),Ve(this,P)};function Ve(P,R){typeof P.read!="function"&&(P=ae.wrap(P,{objectMode:!0}));let ke=st(P,R);return ke.stream=P,ke}async function*st(P,R){let ke=Z;function xe(Ge){this===P?(ke(),ke=Z):ke=Ge}P.on("readable",xe);let Ae,Fe=S(P,{writable:!1},Ge=>{Ae=Ge?C(Ae,Ge):null,ke(),ke=Z});try{for(;;){let Ge=P.destroyed?null:P.read();if(Ge!==null)yield Ge;else{if(Ae)throw Ae;if(Ae===null)return;await new u(xe)}}}catch(Ge){throw Ae=C(Ae,Ge),Ae}finally{(Ae||R?.destroyOnReturn!==!1)&&(Ae===void 0||P._readableState.autoDestroy)?E.destroyer(P,null):(P.off("readable",xe),Fe())}}a(ae.prototype,{readable:{__proto__:null,get(){let P=this._readableState;return!!P&&P.readable!==!1&&!P.destroyed&&!P.errorEmitted&&!P.endEmitted},set(P){this._readableState&&(this._readableState.readable=!!P)}},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(P){this._readableState&&(this._readableState.flowing=P)}},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(P){this._readableState&&(this._readableState.destroyed=P)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[W]!==!1},set(P){this[W]=!!P}}}),ae._fromList=Xt;function Xt(P,R){if(R.length===0)return null;let ke;return R.objectMode?ke=R.buffer.shift():!P||P>=R.length?(R.decoder?ke=R.buffer.join(""):R.buffer.length===1?ke=R.buffer.first():ke=R.buffer.concat(R.length),R.buffer.clear()):ke=R.buffer.consume(P,R.decoder),ke}function at(P){let R=P._readableState;v("endReadable",R.endEmitted),R.endEmitted||(R.ended=!0,t.nextTick(Ze,R,P))}function Ze(P,R){if(v("endReadableNT",P.endEmitted,P.length),!P.errored&&!P.closeEmitted&&!P.endEmitted&&P.length===0){if(P.endEmitted=!0,R.emit("end"),R.writable&&R.allowHalfOpen===!1)t.nextTick(on,R);else if(P.autoDestroy){let ke=R._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&R.destroy()}}}function on(P){P.writable&&!P.writableEnded&&!P.destroyed&&P.end()}ae.from=function(P,R){return F(ae,P,R)};var Zt;function hr(){return Zt===void 0&&(Zt={}),Zt}ae.fromWeb=function(P,R){return hr().newStreamReadableFromReadableStream(P,R)},ae.toWeb=function(P,R){return hr().newReadableStreamFromStreamReadable(P,R)},ae.wrap=function(P,R){var ke,xe;return new ae({objectMode:(ke=(xe=P.readableObjectMode)!==null&&xe!==void 0?xe:P.objectMode)!==null&&ke!==void 0?ke:!0,...R,destroy(Ae,Fe){E.destroyer(P,Ae),Fe(Ae)}}).wrap(P)}}),_i=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:o,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=De();e.exports=K,K.WritableState=U;var{EventEmitter:p}=(Lt(),Ne(_t)),g=ki().Stream,{Buffer:f}=(qe(),Ne($e)),y=Wt(),{addAbortSignal:b}=_r(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Sr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:x,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:O,ERR_STREAM_WRITE_AFTER_END:C,ERR_UNKNOWN_ENCODING:j}=Ke().codes,{errorOrDestroy:T}=y;l(K.prototype,g.prototype),l(K,g);function $(){}var B=u("kOnFinished");function U(L,q,ee){typeof ee!="boolean"&&(ee=q instanceof pt()),this.objectMode=!!(L&&L.objectMode),ee&&(this.objectMode=this.objectMode||!!(L&&L.writableObjectMode)),this.highWaterMark=L?w(this,L,"writableHighWaterMark",ee):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(L&&L.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=L&&L.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=M.bind(void 0,q),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,oe(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!L||L.emitClose!==!1,this.autoDestroy=!L||L.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[B]=[]}function oe(L){L.buffered=[],L.bufferedIndex=0,L.allBuffers=!0,L.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},o(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function K(L){let q=this instanceof pt();if(!q&&!n(K,this))return new K(L);this._writableState=new U(L,this,q),L&&(typeof L.write=="function"&&(this._write=L.write),typeof L.writev=="function"&&(this._writev=L.writev),typeof L.destroy=="function"&&(this._destroy=L.destroy),typeof L.final=="function"&&(this._final=L.final),typeof L.construct=="function"&&(this._construct=L.construct),L.signal&&b(L.signal,this)),g.call(this,L),y.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),z(this,ee)})}o(K,d,{__proto__:null,value:function(L){return n(this,L)?!0:this!==K?!1:L&&L._writableState instanceof U}}),K.prototype.pipe=function(){T(this,new x)};function W(L,q,ee,he){let fe=L._writableState;if(typeof ee=="function")he=ee,ee=fe.defaultEncoding;else{if(!ee)ee=fe.defaultEncoding;else if(ee!=="buffer"&&!f.isEncoding(ee))throw new j(ee);typeof he!="function"&&(he=$)}if(q===null)throw new O;if(!fe.objectMode)if(typeof q=="string")fe.decodeStrings!==!1&&(q=f.from(q,ee),ee="buffer");else if(q instanceof f)ee="buffer";else if(g._isUint8Array(q))q=g._uint8ArrayToBuffer(q),ee="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],q);let be;return fe.ending?be=new C:fe.destroyed&&(be=new E("write")),be?(t.nextTick(he,be),T(L,be,!0),be):(fe.pendingcb++,re(L,fe,q,ee,he))}K.prototype.write=function(L,q,ee){return W(this,L,q,ee)===!0},K.prototype.cork=function(){this._writableState.corked++},K.prototype.uncork=function(){let L=this._writableState;L.corked&&(L.corked--,L.writing||we(this,L))},K.prototype.setDefaultEncoding=function(L){if(typeof L=="string"&&(L=c(L)),!f.isEncoding(L))throw new j(L);return this._writableState.defaultEncoding=L,this};function re(L,q,ee,he,fe){let be=q.objectMode?1:ee.length;q.length+=be;let H=q.length<q.highWaterMark;return H||(q.needDrain=!0),q.writing||q.corked||q.errored||!q.constructed?(q.buffered.push({chunk:ee,encoding:he,callback:fe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&fe!==$&&(q.allNoop=!1)):(q.writelen=be,q.writecb=fe,q.writing=!0,q.sync=!0,L._write(ee,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function F(L,q,ee,he,fe,be,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new E("write")):ee?L._writev(fe,q.onwrite):L._write(fe,be,q.onwrite),q.sync=!1}function Z(L,q,ee,he){--q.pendingcb,he(ee),te(q),T(L,ee)}function M(L,q){let ee=L._writableState,he=ee.sync,fe=ee.writecb;if(typeof fe!="function"){T(L,new v);return}ee.writing=!1,ee.writecb=null,ee.length-=ee.writelen,ee.writelen=0,q?(q.stack,ee.errored||(ee.errored=q),L._readableState&&!L._readableState.errored&&(L._readableState.errored=q),he?t.nextTick(Z,L,ee,q,fe):Z(L,ee,q,fe)):(ee.buffered.length>ee.bufferedIndex&&we(L,ee),he?ee.afterWriteTickInfo!==null&&ee.afterWriteTickInfo.cb===fe?ee.afterWriteTickInfo.count++:(ee.afterWriteTickInfo={count:1,cb:fe,stream:L,state:ee},t.nextTick(Q,ee.afterWriteTickInfo)):ye(L,ee,1,fe))}function Q({stream:L,state:q,count:ee,cb:he}){return q.afterWriteTickInfo=null,ye(L,q,ee,he)}function ye(L,q,ee,he){for(!q.ending&&!L.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,L.emit("drain"));ee-- >0;)q.pendingcb--,he();q.destroyed&&te(q),z(L,q)}function te(L){if(L.writing)return;for(let fe=L.bufferedIndex;fe<L.buffered.length;++fe){var q;let{chunk:be,callback:H}=L.buffered[fe],me=L.objectMode?1:be.length;L.length-=me,H((q=L.errored)!==null&&q!==void 0?q:new E("write"))}let ee=L[B].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=L.errored)!==null&&he!==void 0?he:new E("end"))}oe(L)}function we(L,q){if(q.corked||q.bufferProcessing||q.destroyed||!q.constructed)return;let{buffered:ee,bufferedIndex:he,objectMode:fe}=q,be=ee.length-he;if(!be)return;let H=he;if(q.bufferProcessing=!0,be>1&&L._writev){q.pendingcb-=be-1;let me=q.allNoop?$:ae=>{for(let Oe=H;Oe<ee.length;++Oe)ee[Oe].callback(ae)},ve=q.allNoop&&H===0?ee:r(ee,H);ve.allBuffers=q.allBuffers,F(L,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=ee[H];ee[H++]=null;let Oe=fe?1:me.length;F(L,q,!1,Oe,me,ve,ae)}while(H<ee.length&&!q.writing);H===ee.length?oe(q):H>256?(ee.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}K.prototype._write=function(L,q,ee){if(this._writev)this._writev([{chunk:L,encoding:q}],ee);else throw new S("_write()")},K.prototype._writev=null,K.prototype.end=function(L,q,ee){let he=this._writableState;typeof L=="function"?(ee=L,L=null,q=null):typeof q=="function"&&(ee=q,q=null);let fe;if(L!=null){let be=W(this,L,q);be instanceof s&&(fe=be)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,z(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new E("end"))),typeof ee=="function"&&(fe||he.finished?t.nextTick(ee,fe):he[B].push(ee)),this};function G(L){return L.ending&&!L.destroyed&&L.constructed&&L.length===0&&!L.errored&&L.buffered.length===0&&!L.finished&&!L.writing&&!L.errorEmitted&&!L.closeEmitted}function N(L,q){let ee=!1;function he(fe){if(ee){T(L,fe??v());return}if(ee=!0,q.pendingcb--,fe){let be=q[B].splice(0);for(let H=0;H<be.length;H++)be[H](fe);T(L,fe,q.sync)}else G(q)&&(q.prefinished=!0,L.emit("prefinish"),q.pendingcb++,t.nextTick(Y,L,q))}q.sync=!0,q.pendingcb++;try{L._final(he)}catch(fe){he(fe)}q.sync=!1}function ne(L,q){!q.prefinished&&!q.finalCalled&&(typeof L._final=="function"&&!q.destroyed?(q.finalCalled=!0,N(L,q)):(q.prefinished=!0,L.emit("prefinish")))}function z(L,q,ee){G(q)&&(ne(L,q),q.pendingcb===0&&(ee?(q.pendingcb++,t.nextTick((he,fe)=>{G(fe)?Y(he,fe):fe.pendingcb--},L,q)):G(q)&&(q.pendingcb++,Y(L,q))))}function Y(L,q){q.pendingcb--,q.finished=!0;let ee=q[B].splice(0);for(let he=0;he<ee.length;he++)ee[he]();if(L.emit("finish"),q.autoDestroy){let he=L._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&L.destroy()}}a(K.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(L){this._writableState&&(this._writableState.destroyed=L)}},writable:{__proto__:null,get(){let L=this._writableState;return!!L&&L.writable!==!1&&!L.destroyed&&!L.errored&&!L.ending&&!L.ended},set(L){this._writableState&&(this._writableState.writable=!!L)}},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 L=this._writableState;return L?!L.destroyed&&!L.ending&&L.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 J=y.destroy;K.prototype.destroy=function(L,q){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[B].length)&&t.nextTick(te,ee),J.call(this,L,q),this},K.prototype._undestroy=y.undestroy,K.prototype._destroy=function(L,q){q(L)},K.prototype[p.captureRejectionSymbol]=function(L){this.destroy(L)};var ge;function se(){return ge===void 0&&(ge={}),ge}K.fromWeb=function(L,q){return se().newStreamWritableFromWritableStream(L,q)},K.toWeb=function(L){return se().newWritableStreamFromStreamWritable(L)}}),Qc=pe((i,e)=>{le(),ue(),ce();var t=Rt(),r=(qe(),Ne($e)),{isReadable:s,isWritable:n,isIterable:o,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=ft(),g=St(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:y,ERR_INVALID_RETURN_VALUE:b}}=Ke(),{destroyer:w}=Wt(),m=pt(),k=xr(),S=_i(),{createDeferredPromise:v}=Je(),x=gs(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(B){return B instanceof E}:function(B){return!1},O=globalThis.AbortController||nr().AbortController,{FunctionPrototypeCall:C}=De(),j=class extends m{constructor(B){super(B),B?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),B?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function B(U,oe){if(u(U))return U;if(l(U))return $({readable:U});if(c(U))return $({writable:U});if(a(U))return $({writable:!1,readable:!1});if(d(U))return $({readable:k.fromWeb(U)});if(p(U))return $({writable:S.fromWeb(U)});if(typeof U=="function"){let{value:W,write:re,final:F,destroy:Z}=T(U);if(o(W))return x(j,W,{objectMode:!0,write:re,final:F,destroy:Z});let M=W?.then;if(typeof M=="function"){let Q,ye=C(M,W,te=>{if(te!=null)throw new b("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){F(async()=>{try{await ye,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new b("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(U))return B(U.arrayBuffer());if(o(U))return x(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&p(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let W=U!=null&&U.readable?l(U?.readable)?U?.readable:B(U.readable):void 0,re=U!=null&&U.writable?c(U?.writable)?U?.writable:B(U.writable):void 0;return $({readable:W,writable:re})}let K=U?.then;if(typeof K=="function"){let W;return C(K,U,re=>{re!=null&&W.push(re),W.push(null)},re=>{w(W,re)}),W=new j({objectMode:!0,writable:!1,read(){}})}throw new y(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(B){let{promise:U,resolve:oe}=v(),K=new O,W=K.signal;return{value:B((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(W.aborted)throw new f(void 0,{cause:W.reason});({promise:U,resolve:oe}=v()),yield F}})(),{signal:W}),write(re,F,Z){let M=oe;oe=null,M({chunk:re,done:!1,cb:Z})},final(re){let F=oe;oe=null,F({done:!0,cb:re})},destroy(re,F){K.abort(),F(re)}}}function $(B){let U=B.readable&&typeof B.readable.read!="function"?k.wrap(B.readable):B.readable,oe=B.writable,K=!!s(U),W=!!n(oe),re,F,Z,M,Q;function ye(te){let we=M;M=null,we?we(te):te&&Q.destroy(te)}return Q=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:K,writable:W}),W&&(g(oe,te=>{W=!1,te&&w(U,te),ye(te)}),Q._write=function(te,we,G){oe.write(te,we)?G():re=G},Q._final=function(te){oe.end(),F=te},oe.on("drain",function(){if(re){let te=re;re=null,te()}}),oe.on("finish",function(){if(F){let te=F;F=null,te()}})),K&&(g(U,te=>{K=!1,te&&w(U,te),ye(te)}),U.on("readable",function(){if(Z){let te=Z;Z=null,te()}}),U.on("end",function(){Q.push(null)}),Q._read=function(){for(;;){let te=U.read();if(te===null){Z=Q._read;return}if(!Q.push(te))return}}),Q._destroy=function(te,we){!te&&M!==null&&(te=new f),Z=null,re=null,F=null,M===null?we(te):(M=we,w(oe,te),w(U,te))},Q}}),pt=pe((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=De();e.exports=l;var o=xr(),a=_i();n(l.prototype,o.prototype),n(l,o);{let p=s(a.prototype);for(let g=0;g<p.length;g++){let f=p[g];l.prototype[f]||(l.prototype[f]=a.prototype[f])}}function l(p){if(!(this instanceof l))return new l(p);o.call(this,p),a.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(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.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}l.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=Qc()),d(p,"body")}}),ys=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=De();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:s}=Ke().codes,n=pt(),{getHighWaterMark:o}=Sr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?o(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,g)=>{if(p){d?d(p):this.destroy(p);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,p,g){throw new s("_transform()")},l.prototype._write=function(d,p,g){let f=this._readableState,y=this._writableState,b=f.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),y.ended||b===f.length||f.length<f.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),bs=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=De();e.exports=s;var r=ys();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,o,a){a(null,n)}}),Si=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:o}=De(),a=St(),{once:l}=Je(),c=Wt(),u=pt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:k}=or(),{isIterable:S,isReadable:v,isReadableNodeStream:x,isNodeStream:E,isTransformStream:I,isWebStream:O,isReadableStream:C,isReadableFinished:j}=ft(),T=globalThis.AbortController||nr().AbortController,$,B,U;function oe(te,we,G){let N=!1;te.on("close",()=>{N=!0});let ne=a(te,{readable:we,writable:G},z=>{N=!z});return{destroy:z=>{N||(N=!0,c.destroyer(te,z||new y("pipe")))},cleanup:ne}}function K(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function W(te){if(S(te))return te;if(x(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){B||(B=xr()),yield*B.prototype[n].call(te)}async function F(te,we,G,{end:N}){let ne,z=null,Y=se=>{if(se&&(ne=se),z){let L=z;z=null,L()}},J=()=>new s((se,L)=>{ne?L(ne):z=()=>{ne?L(ne):se()}});we.on("drain",Y);let ge=a(we,{readable:!1},Y);try{we.writableNeedDrain&&await J();for await(let se of te)we.write(se)||await J();N&&(we.end(),await J()),G()}catch(se){G(ne!==se?d(ne,se):se)}finally{ge(),we.off("drain",Y)}}async function Z(te,we,G,{end:N}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let z of te)await ne.ready,ne.write(z).catch(()=>{});await ne.ready,N&&await ne.close(),G()}catch(z){try{await ne.abort(z),G(z)}catch(Y){G(Y)}}}function M(...te){return Q(te,l(K(te)))}function Q(te,we,G){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new f("streams");let N=new T,ne=N.signal,z=G?.signal,Y=[];k(z,"options.signal");function J(){fe(new w)}U=U||Je().addAbortListener;let ge;z&&(ge=U(z,J));let se,L,q=[],ee=0;function he(ve){fe(ve,--ee===0)}function fe(ve,ae){var Oe;if(ve&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=ve),!(!se&&!ae)){for(;q.length;)q.shift()(se);(Oe=ge)===null||Oe===void 0||Oe[o](),N.abort(),ae&&(se||Y.forEach(h=>h()),t.nextTick(we,se,L))}}let be;for(let ve=0;ve<te.length;ve++){let ae=te[ve],Oe=ve<te.length-1,h=ve>0,_=Oe||G?.end!==!1,A=ve===te.length-1;if(E(ae)){let D=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(_){let{destroy:X,cleanup:de}=oe(ae,Oe,h);q.push(X),v(ae)&&A&&Y.push(de)}ae.on("error",D),v(ae)&&A&&Y.push(()=>{ae.removeListener("error",D)})}if(ve===0)if(typeof ae=="function"){if(be=ae({signal:ne}),!S(be))throw new g("Iterable, AsyncIterable or Stream","source",be)}else S(ae)||x(ae)||I(ae)?be=ae:be=u.from(ae);else if(typeof ae=="function"){if(I(be)){var H;be=W((H=be)===null||H===void 0?void 0:H.readable)}else be=W(be);if(be=ae(be,{signal:ne}),Oe){if(!S(be,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,be)}else{var me;$||($=bs());let D=new $({objectMode:!0}),X=(me=be)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(be,V=>{L=V,V!=null&&D.write(V),_&&D.end(),t.nextTick(he)},V=>{D.destroy(V),t.nextTick(he,V)});else if(S(be,!0))ee++,F(be,D,he,{end:_});else if(C(be)||I(be)){let V=be.readable||be;ee++,F(V,D,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",be);be=D;let{destroy:de,cleanup:_e}=oe(be,!1,!0);q.push(de),A&&Y.push(_e)}}else if(E(ae)){if(x(be)){ee+=2;let D=ye(be,ae,he,{end:_});v(ae)&&A&&Y.push(D)}else if(I(be)||C(be)){let D=be.readable||be;ee++,F(D,ae,he,{end:_})}else if(S(be))ee++,F(be,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else if(O(ae)){if(x(be))ee++,Z(W(be),ae,he,{end:_});else if(C(be)||S(be))ee++,Z(be,ae,he,{end:_});else if(I(be))ee++,Z(be.readable,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else be=u.from(ae)}return(ne!=null&&ne.aborted||z!=null&&z.aborted)&&t.nextTick(J),be}function ye(te,we,G,{end:N}){let ne=!1;if(we.on("close",()=>{ne||G(new b)}),te.pipe(we,{end:!1}),N){let z=function(){ne=!0,we.end()};j(te)?t.nextTick(z):te.once("end",z)}else G();return a(te,{readable:!0,writable:!1},z=>{let Y=te._readableState;z&&z.code==="ERR_STREAM_PREMATURE_CLOSE"&&Y&&Y.ended&&!Y.errored&&!Y.errorEmitted?te.once("end",G).once("error",G):G(z)}),a(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:Q,pipeline:M}}),vs=pe((i,e)=>{le(),ue(),ce();var{pipeline:t}=Si(),r=pt(),{destroyer:s}=Wt(),{isNodeStream:n,isReadable:o,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=ft(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ke(),y=St();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let w=[...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])&&!l(b[T]))){if(T<b.length-1&&!(o(b[T])||d(b[T])||c(b[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(b[T])||u(b[T])||c(b[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,S,v,x;function E(T){let $=v;v=null,$?$(T):T?x.destroy(T):!j&&!C&&x.destroy()}let I=b[0],O=t(b,E),C=!!(a(I)||u(I)||c(I)),j=!!(o(O)||d(O)||c(O));if(x=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(O!=null&&O.readableObjectMode),writable:C,readable:j}),C){if(n(I))x._write=function($,B,U){I.write($,B)?U():m=U},x._final=function($){I.end(),k=$},I.on("drain",function(){if(m){let $=m;m=null,$()}});else if(l(I)){let $=(c(I)?I.writable:I).getWriter();x._write=async function(B,U,oe){try{await $.ready,$.write(B).catch(()=>{}),oe()}catch(K){oe(K)}},x._final=async function(B){try{await $.ready,$.close().catch(()=>{}),k=B}catch(U){B(U)}}}let T=c(O)?O.readable:O;y(T,()=>{if(k){let $=k;k=null,$()}})}if(j){if(n(O))O.on("readable",function(){if(S){let T=S;S=null,T()}}),O.on("end",function(){x.push(null)}),x._read=function(){for(;;){let T=O.read();if(T===null){S=x._read;return}if(!x.push(T))return}};else if(l(O)){let T=(c(O)?O.readable:O).getReader();x._read=async function(){for(;;)try{let{value:$,done:B}=await T.read();if(!x.push($))return;if(B){x.push(null);return}}catch{return}}}}return x._destroy=function(T,$){!T&&v!==null&&(T=new p),S=null,m=null,k=null,v===null?$(T):(v=$,n(O)&&s(O,T))},x}}),Xc=pe((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||nr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:o},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=or(),d=De().Symbol("kWeak"),p=De().Symbol("kResistStopPropagation"),{finished:g}=St(),f=vs(),{addAbortSignalNoValidate:y}=_r(),{isWritable:b,isNodeStream:w}=ft(),{deprecate:m}=Je(),{ArrayPrototypePush:k,Boolean:S,MathFloor:v,Number:x,NumberIsNaN:E,Promise:I,PromiseReject:O,PromiseResolve:C,PromisePrototypeThen:j,Symbol:T}=De(),$=T("kEmpty"),B=T("kEof");function U(z,Y){if(Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),w(z)&&!b(z))throw new r("stream",z,"must be writable");let J=f(this,z);return Y!=null&&Y.signal&&y(Y.signal,J),J}function oe(z,Y){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal");let J=1;Y?.concurrency!=null&&(J=v(Y.concurrency));let ge=J-1;return Y?.highWaterMark!=null&&(ge=v(Y.highWaterMark)),c(J,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=J,(async function*(){let se=Je().AbortSignalAny([Y?.signal].filter(S)),L=this,q=[],ee={signal:se},he,fe,be=!1,H=0;function me(){be=!0,ve()}function ve(){H-=1,ae()}function ae(){fe&&!be&&H<J&&q.length<ge&&(fe(),fe=null)}async function Oe(){try{for await(let h of L){if(be)return;if(se.aborted)throw new a;try{if(h=z(h,ee),h===$)continue;h=C(h)}catch(_){h=O(_)}H+=1,j(h,ve,me),q.push(h),he&&(he(),he=null),!be&&(q.length>=ge||H>=J)&&await new I(_=>{fe=_})}q.push(B)}catch(h){let _=O(h);j(_,ve,me),q.push(_)}finally{be=!0,he&&(he(),he=null)}}Oe();try{for(;;){for(;q.length>0;){let h=await q[0];if(h===B)return;if(se.aborted)throw new a;h!==$&&(yield h),q.shift(),ae()}await new I(h=>{he=h})}}finally{be=!0,fe&&(fe(),fe=null)}}).call(this)}function K(z=void 0){return z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal"),(async function*(){let Y=0;for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a({cause:z.signal.reason});yield[Y++,ge]}}).call(this)}async function W(z,Y=void 0){for await(let J of M.call(this,z,Y))return!0;return!1}async function re(z,Y=void 0){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);return!await W.call(this,async(...J)=>!await z(...J),Y)}async function F(z,Y){for await(let J of M.call(this,z,Y))return J}async function Z(z,Y){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se),$}for await(let ge of oe.call(this,J,Y));}function M(z,Y){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function J(ge,se){return await z(ge,se)?ge:$}return oe.call(this,J,Y)}var Q=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function ye(z,Y,J){var ge;if(typeof z!="function")throw new s("reducer",["Function","AsyncFunction"],z);J!=null&&u(J,"options"),J?.signal!=null&&l(J.signal,"options.signal");let se=arguments.length>1;if(J!=null&&(ge=J.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new a(void 0,{cause:J.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let L=new t,q=L.signal;if(J!=null&&J.signal){let fe={once:!0,[d]:this,[p]:!0};J.signal.addEventListener("abort",()=>L.abort(),fe)}let ee=!1;try{for await(let fe of this){var he;if(ee=!0,J!=null&&(he=J.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?Y=await z(Y,fe,{signal:q}):(Y=fe,se=!0)}if(!ee&&!se)throw new Q}finally{L.abort()}return Y}async function te(z){z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal");let Y=[];for await(let ge of this){var J;if(z!=null&&(J=z.signal)!==null&&J!==void 0&&J.aborted)throw new a(void 0,{cause:z.signal.reason});k(Y,ge)}return Y}function we(z,Y){let J=oe.call(this,z,Y);return(async function*(){for await(let ge of J)yield*ge}).call(this)}function G(z){if(z=x(z),E(z))return 0;if(z<0)throw new o("number",">= 0",z);return z}function N(z,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),z=G(z),(async function*(){var J;if(Y!=null&&(J=Y.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(Y!=null&&(ge=Y.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;z--<=0&&(yield se)}}).call(this)}function ne(z,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),z=G(z),(async function*(){var J;if(Y!=null&&(J=Y.signal)!==null&&J!==void 0&&J.aborted)throw new a;for await(let se of this){var ge;if(Y!=null&&(ge=Y.signal)!==null&&ge!==void 0&&ge.aborted)throw new a;if(z-- >0&&(yield se),z<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(K,"readable.asIndexedPairs will be removed in a future version."),drop:N,filter:M,flatMap:we,map:oe,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:ye,toArray:te,some:W,find:F}}),ws=pe((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=De(),{isIterable:s,isNodeStream:n,isWebStream:o}=ft(),{pipelineImpl:a}=Si(),{finished:l}=St();ks();function c(...u){return new r((d,p)=>{let g,f,y=u[u.length-1];if(y&&typeof y=="object"&&!n(y)&&!s(y)&&!o(y)){let b=t(u);g=b.signal,f=b.end}a(u,(b,w)=>{b?p(b):d(w)},{signal:g,end:f})})}e.exports={finished:l,pipeline:c}}),ks=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=De(),{promisify:{custom:o}}=Je(),{streamReturningOperators:a,promiseReturningOperators:l}=Xc(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=vs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Sr(),{pipeline:g}=Si(),{destroyer:f}=Wt(),y=St(),b=ws(),w=ft(),m=e.exports=ki().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=xr();for(let S of s(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(x,this,E))},x=a[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let S of s(l)){let v=function(...E){if(new.target)throw c();return n(x,this,E)},x=l[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=_i(),m.Duplex=pt(),m.Transform=ys(),m.PassThrough=bs(),m.pipeline=g;var{addAbortSignal:k}=_r();m.addAbortSignal=k,m.finished=y,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(g,o,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(y,o,{__proto__:null,enumerable:!0,get(){return b.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)}}),Nt=pe((i,e)=>{le(),ue(),ce();var t=ks(),r=ws(),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}),Zc=pe((i,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}}}),eu=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),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 o=0;for(let a=0;a<this._bufs.length;a++){let l=o+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-o];o=l}},s.prototype._reverseOffset=function(n){let o=n[0],a=n[1];for(let l=0;l<o;l++)a+=this._bufs[l].length;return a},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let o=this._offset(n);return this._bufs[o[0]][o[1]]},s.prototype.slice=function(n,o){return typeof n=="number"&&n<0&&(n+=this.length),typeof o=="number"&&o<0&&(o+=this.length),this.copy(null,0,n,o)},s.prototype.copy=function(n,o,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,p=d,g=c&&o||0,f=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let y=0;y<this._bufs.length;y++)this._bufs[y].copy(n,g),g+=this._bufs[y].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,o,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let y=u[0];y<this._bufs.length;y++){let b=this._bufs[y].length-f;if(p>b)this._bufs[y].copy(n,g,f),g+=b;else{this._bufs[y].copy(n,g,f,f+p),g+=b;break}p-=b,f&&(f=0)}return n.length>g?n.slice(0,g):n},s.prototype.shallowSlice=function(n,o){if(n=n||0,o=typeof o!="number"?this.length:o,n<0&&(n+=this.length),o<0&&(o+=this.length),n===o)return this._new();let a=this._offset(n),l=this._offset(o),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},s.prototype.toString=function(n,o,a){return this.slice(o,a).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 o=0;o<this._bufs.length;o++)n.append(this._bufs[o]);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,o,a){if(n==null)return this;if(n.buffer)o.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],o,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],o,a)}else typeof n=="number"&&(n=n.toString()),o.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,o,a){if(a===void 0&&typeof o=="string"&&(a=o,o=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,a):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)),o=Number(o||0),isNaN(o)&&(o=0),o<0&&(o=this.length+o),o<0&&(o=0),n.length===0)return o>this.length?this.length:o;let l=this._offset(o),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.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,o){if(this.length-n<o.length)return!1;for(let a=0;a<o.length;a++)if(this.get(n+a)!==o[a])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 o in n)(function(a){n[a]===null?s.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:s.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(o)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),tu=pe((i,e)=>{le(),ue(),ce();var t=Nt().Duplex,r=Zc(),s=eu();function n(o){if(!(this instanceof n))return new n(o);if(typeof o=="function"){this._callback=o;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),o=null}s._init.call(this,o),t.call(this)}r(n,t),Object.assign(n.prototype,s.prototype),n.prototype._new=function(o){return new n(o)},n.prototype._write=function(o,a,l){this._appendBuffer(o),typeof l=="function"&&l()},n.prototype._read=function(o){if(!this.length)return this.push(null);o=Math.min(o,this.length),this.push(this.slice(0,o)),this.consume(o)},n.prototype.end=function(o){t.prototype.end.call(this,o),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(o,a){this._bufs.length=0,this.length=0,a(o)},n.prototype._isBufferList=function(o){return o instanceof n||o instanceof s||n.isBufferList(o)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),ru=pe((i,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}),_s=pe((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(qe(),Ne($e));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 o=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+o.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let o=t.types[n];t.codes[o]=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 o=t.properties[n];t.propertiesCodes[o]=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(o=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|o<<t.QOS_SHIFT|l,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"}}),nu=pe((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,o=n*7,a=n*365.25;e.exports=function(p,g){g=g||{};var f=typeof p;if(f==="string"&&p.length>0)return l(p);if(f==="number"&&isFinite(p))return g.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function l(p){if(p=String(p),!(p.length>100)){var g=/^(-?(?:\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(g){var f=parseFloat(g[1]),y=(g[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return f*a;case"weeks":case"week":case"w":return f*o;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 g=Math.abs(p);return g>=n?Math.round(p/n)+"d":g>=s?Math.round(p/s)+"h":g>=r?Math.round(p/r)+"m":g>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var g=Math.abs(p);return g>=n?d(p,g,n,"day"):g>=s?d(p,g,s,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,f,y){var b=g>=f*1.5;return Math.round(p/f)+" "+y+(b?"s":"")}}),iu=pe((i,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=nu(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function s(g){let f=0;for(let y=0;y<g.length;y++)f=(f<<5)-f+g.charCodeAt(y),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=s;function n(g){let f,y=null,b,w;function m(...k){if(!m.enabled)return;let S=m,v=Number(new Date),x=v-(f||v);S.diff=x,S.prev=f,S.curr=v,f=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,O)=>{if(I==="%%")return"%";E++;let C=n.formatters[O];if(typeof C=="function"){let j=k[E];I=C.call(S,j),k.splice(E,1),E--}return I}),n.formatArgs.call(S,k),(S.log||n.log).apply(S,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=o,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==n.namespaces&&(b=n.namespaces,w=n.enabled(g)),w),set:k=>{y=k}}),typeof n.init=="function"&&n.init(m),m}function o(g,f){let y=n(this.namespace+(typeof f>"u"?":":f)+g);return y.log=this.log,y}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let f=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of f)y[0]==="-"?n.skips.push(y.slice(1)):n.names.push(y)}function l(g,f){let y=0,b=0,w=-1,m=0;for(;y<g.length;)if(b<f.length&&(f[b]===g[y]||f[b]==="*"))f[b]==="*"?(w=b,m=y,b++):(y++,b++);else if(w!==-1)b=w+1,m++,y=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function c(){let g=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),g}function u(g){for(let f of n.skips)if(l(g,f))return!1;for(let f of n.names)if(l(g,f))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}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}),mt=pe((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=s,i.load=n,i.useColors=t,i.storage=o(),i.destroy=(()=>{let l=!1;return()=>{l||(l=!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`."))}})(),i.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 l;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&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}i.log=console.debug||console.log||(()=>{});function s(l){try{l?i.storage.setItem("debug",l):i.storage.removeItem("debug")}catch{}}function n(){let l;try{l=i.storage.getItem("debug")||i.storage.getItem("DEBUG")}catch{}return!l&&typeof je<"u"&&"env"in je&&(l=je.env.DEBUG),l}function o(){try{return localStorage}catch{}}e.exports=iu()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),ou=pe((i,e)=>{le(),ue(),ce();var t=tu(),{EventEmitter:r}=(Lt(),Ne(_t)),s=ru(),n=_s(),o=mt()("mqtt-packet:parser"),a=class Uo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Uo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Uo().parser(c)}_resetState(){o("_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),o("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++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("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 d=c&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==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,o("_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)),o("_parseLength %d",c.value),!!c}_parsePayload(){o("_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 o("_parsePayload complete result: %s",c),c}_parseConnect(){o("_parseConnect");let c,u,d,p,g={},f=this.packet,y=this._parseString();if(y===null)return this._emitError(new Error("Cannot parse protocolId"));if(y!=="MQTT"&&y!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=y,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"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)f.will={},f.will.retain=b,f.will.qos=w;else{if(b)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)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 k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,o("_parseConnect: packet.clientId: %s",f.clientId),g.will){if(f.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,o("_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,o("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(g.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,o("_parseConnect: packet.username: %s",f.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,o("_parseConnect: complete"),f}_parseConnack(){o("_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 d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}o("_parseConnack: complete")}_parsePublish(){o("_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),o("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){o("_parseSubscribe");let c=this.packet,u,d,p,g,f,y,b;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}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(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(y=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=y,b.rap=f,b.rh=g):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",b),c.subscriptions.push(b)}}}_parseSuback(){o("_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(){o("_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"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){o("_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 d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){o("_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}o("_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(o("_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 o("_parseDisconnect result: true"),!0}_parseAuth(){o("_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),o("_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):(o("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,o("_parseString: result: %s",p),p}_parseStringPair(){return o("_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 d=this._list.slice(this._pos,u);return this._pos+=c,o("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,o("_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,o("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){o("_parseVarByteNum");let u=4,d=0,p=1,g=0,f=!1,y,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(y=this._list.readUInt8(b+d++),g+=p*(y&n.VARBYTEINT_MASK),p*=128,(y&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=d),f?c?f={bytes:d,value:g}:f=g:f=!1,o("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",c),c}_parseByType(c){switch(o("_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(){o("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[p];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let f=this._parseByType(n.propertiesTypes[g]);if(d[g][f.name])if(Array.isArray(d[g][f.name]))d[g][f.name].push(f.value);else{let y=d[g][f.name];d[g][f.name]=[y],d[g][f.name].push(f.value)}else d[g][f.name]=f.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_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)),o("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(c){o("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),su=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),r=65536,s={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function o(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)s[u]=o(u)}function l(u){let d=0,p=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?g.subarray(0,p):g.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:s,generateCache:a,generateNumber:o,genBufVariableByteInt:l,generate4ByteBuffer:c}}),au=pe((i,e)=>{le(),ue(),ce(),typeof je>"u"||!je.version||je.version.indexOf("v0.")===0||je.version.indexOf("v1.")===0&&je.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=je;function t(r,s,n,o){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return je.nextTick(r);case 2:return je.nextTick(function(){r.call(null,s)});case 3:return je.nextTick(function(){r.call(null,s,n)});case 4:return je.nextTick(function(){r.call(null,s,n,o)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return je.nextTick(function(){r.apply(null,l)})}}}),Ss=pe((i,e)=>{le(),ue(),ce();var t=_s(),{Buffer:r}=(qe(),Ne($e)),s=r.allocUnsafe(0),n=r.from([0]),o=su(),a=au().nextTick,l=mt()("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,p=o.genBufVariableByteInt,g=o.generate4ByteBuffer,f=K,y=!0;function b(G,N,ne){switch(l("generate called"),N.cork&&(N.cork(),a(w,N)),y&&(y=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,N);case"connack":return k(G,N,ne);case"publish":return S(G,N,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,N,ne);case"subscribe":return x(G,N,ne);case"suback":return E(G,N,ne);case"unsubscribe":return I(G,N,ne);case"unsuback":return O(G,N,ne);case"pingreq":case"pingresp":return C(G,N);case"disconnect":return j(G,N,ne);case"auth":return T(G,N,ne);default:return N.destroy(new Error("Unknown command")),!1}}Object.defineProperty(b,"cacheNumbers",{get(){return f===K},set(G){G?((!c||Object.keys(c).length===0)&&(y=!0),f=K):(y=!1,f=W)}});function w(G){G.uncork()}function m(G,N,ne){let z=G||{},Y=z.protocolId||"MQTT",J=z.protocolVersion||4,ge=z.will,se=z.clean,L=z.keepalive||0,q=z.clientId||"",ee=z.username,he=z.password,fe=z.properties;se===void 0&&(se=!0);let be=0;if(typeof Y!="string"&&!r.isBuffer(Y))return N.destroy(new Error("Invalid protocolId")),!1;if(be+=Y.length+2,J!==3&&J!==4&&J!==5)return N.destroy(new Error("Invalid protocol version")),!1;if(be+=1,(typeof q=="string"||r.isBuffer(q))&&(q||J>=4)&&(q||se))be+=r.byteLength(q)+2;else{if(J<4)return N.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return N.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof L!="number"||L<0||L>65535||L%1!==0)return N.destroy(new Error("Invalid keepalive")),!1;be+=2,be+=1;let H,me;if(J===5){if(H=Z(N,fe),!H)return!1;be+=H.length}if(ge){if(typeof ge!="object")return N.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return N.destroy(new Error("Invalid will topic")),!1;if(be+=r.byteLength(ge.topic)+2,be+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?be+=r.byteLength(ge.payload):be+=ge.payload.length;else return N.destroy(new Error("Invalid will payload")),!1;if(me={},J===5){if(me=Z(N,ge.properties),!me)return!1;be+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,be+=r.byteLength(ee)+2;else return N.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return N.destroy(new Error("Username is required to use password")),!1;if(we(he))be+=te(he)+2;else return N.destroy(new Error("Invalid password")),!1}N.write(t.CONNECT_HEADER),B(N,be),F(N,Y),z.bridgeMode&&(J+=128),N.write(J===131?t.VERSION131:J===132?t.VERSION132:J===4?t.VERSION4:J===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=ee!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=ge&&ge.retain?t.WILL_RETAIN_MASK:0,ae|=ge&&ge.qos?ge.qos<<t.WILL_QOS_SHIFT:0,ae|=ge?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,N.write(r.from([ae])),f(N,L),J===5&&H.write(),F(N,q),ge&&(J===5&&me.write(),U(N,ge.topic),F(N,ge.payload)),ee!=null&&F(N,ee),he!=null&&F(N,he),!0}function k(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=z===5?Y.reasonCode:Y.returnCode,ge=Y.properties,se=2;if(typeof J!="number")return N.destroy(new Error("Invalid return code")),!1;let L=null;if(z===5){if(L=Z(N,ge),!L)return!1;se+=L.length}return N.write(t.CONNACK_HEADER),B(N,se),N.write(Y.sessionPresent?t.SESSIONPRESENT_HEADER:n),N.write(r.from([J])),L?.write(),!0}function S(G,N,ne){l("publish: packet: %o",G);let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.qos||0,ge=Y.retain?t.RETAIN_MASK:0,se=Y.topic,L=Y.payload||s,q=Y.messageId,ee=Y.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return N.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(L)?he+=L.length:he+=r.byteLength(L),J&&typeof q!="number")return N.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(z===5){if(fe=Z(N,ee),!fe)return!1;he+=fe.length}return N.write(t.PUBLISH_HEADER[J][Y.dup?1:0][ge?1:0]),B(N,he),f(N,te(se)),N.write(se),J>0&&f(N,q),fe?.write(),l("publish: payload: %o",L),N.write(L)}function v(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.cmd||"puback",ge=Y.messageId,se=Y.dup&&J==="pubrel"?t.DUP_MASK:0,L=0,q=Y.reasonCode,ee=Y.properties,he=z===5?3:2;if(J==="pubrel"&&(L=1),typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;let fe=null;if(z===5&&typeof ee=="object"){if(fe=M(N,ee,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[J][L][se][0]),he===3&&(he+=q!==0?1:-1),B(N,he),f(N,ge),z===5&&he!==2&&N.write(r.from([q])),fe!==null?fe.write():he===4&&N.write(r.from([0])),!0}function x(G,N,ne){l("subscribe: packet: ");let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.dup?t.DUP_MASK:0,ge=Y.messageId,se=Y.subscriptions,L=Y.properties,q=0;if(typeof ge!="number")return N.destroy(new Error("Invalid messageId")),!1;q+=2;let ee=null;if(z===5){if(ee=Z(N,L),!ee)return!1;q+=ee.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let be=se[fe].topic,H=se[fe].qos;if(typeof be!="string")return N.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return N.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(z===5){if(typeof(se[fe].nl||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return N.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[fe].rh||0;if(typeof me!="number"||me>2)return N.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=r.byteLength(be)+2+1}else return N.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),N.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),B(N,q),f(N,ge),ee!==null&&ee.write();let he=!0;for(let fe of se){let be=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;U(N,be),Oe=t.SUBSCRIBE_OPTIONS_QOS[H],z===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=N.write(r.from([Oe]))}return he}function E(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.granted,se=Y.properties,L=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(L+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return N.destroy(new Error("Invalid qos vector")),!1;L+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let q=null;if(z===5){if(q=M(N,se,ne,L),!q)return!1;L+=q.length}return N.write(t.SUBACK_HEADER),B(N,L),f(N,J),q!==null&&q.write(),N.write(r.from(ge))}function I(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.unsubscriptions,L=Y.properties,q=0;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(q+=2,typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){if(typeof se[fe]!="string")return N.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return N.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(z===5){if(ee=Z(N,L),!ee)return!1;q+=ee.length}N.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),B(N,q),f(N,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(N,se[fe]);return he}function O(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.granted,L=Y.properties,q=Y.cmd,ee=0,he=2;if(typeof J!="number")return N.destroy(new Error("Invalid messageId")),!1;if(z===5)if(typeof se=="object"&&se.length)for(let be=0;be<se.length;be+=1){if(typeof se[be]!="number")return N.destroy(new Error("Invalid qos vector")),!1;he+=1}else return N.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(z===5){if(fe=M(N,L,ne,he),!fe)return!1;he+=fe.length}return N.write(t.ACKS[q][ee][ge][0]),B(N,he),f(N,J),fe!==null&&fe.write(),z===5&&N.write(r.from(se)),!0}function C(G,N,ne){return N.write(t.EMPTY[G.cmd])}function j(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.reasonCode,ge=Y.properties,se=z===5?1:0,L=null;if(z===5){if(L=M(N,ge,ne,se),!L)return!1;se+=L.length}return N.write(r.from([t.codes.disconnect<<4])),B(N,se),z===5&&N.write(r.from([J])),L!==null&&L.write(),!0}function T(G,N,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.reasonCode,ge=Y.properties,se=z===5?1:0;z!==5&&N.destroy(new Error("Invalid mqtt version for auth packet"));let L=M(N,ge,ne,se);return L?(se+=L.length,N.write(r.from([t.codes.auth<<4])),B(N,se),N.write(r.from([J])),L!==null&&L.write(),!0):!1}var $={};function B(G,N){if(N>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${N}`)),!1;let ne=$[N];return ne||(ne=p(N),N<16384&&($[N]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,N){let ne=r.byteLength(N);return f(G,ne),l("writeString: %s",N),G.write(N,"utf8")}function oe(G,N,ne){U(G,N),U(G,ne)}function K(G,N){return l("writeNumberCached: number: %d",N),l("writeNumberCached: %o",c[N]),G.write(c[N])}function W(G,N){let ne=u(N);return l("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,N){let ne=g(N);return l("write4ByteNumber: %o",ne),G.write(ne)}function F(G,N){typeof N=="string"?U(G,N):N?(f(G,N.length),G.write(N)):f(G,0)}function Z(G,N){if(typeof N!="object"||N.length!=null)return{length:1,write(){ye(G,{},0)}};let ne=0;function z(Y,J){let ge=t.propertiesTypes[Y],se=0;switch(ge){case"byte":{if(typeof J!="boolean")return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=2;break}case"int8":{if(typeof J!="number"||J<0||J>255)return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=2;break}case"binary":{if(J&&J===null)return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=1+r.byteLength(J)+2;break}case"int16":{if(typeof J!="number"||J<0||J>65535)return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=3;break}case"int32":{if(typeof J!="number"||J<0||J>4294967295)return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=5;break}case"var":{if(typeof J!="number"||J<0||J>268435455)return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=1+r.byteLength(p(J));break}case"string":{if(typeof J!="string")return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=3+r.byteLength(J.toString());break}case"pair":{if(typeof J!="object")return G.destroy(new Error(`Invalid ${Y}: ${J}`)),!1;se+=Object.getOwnPropertyNames(J).reduce((L,q)=>{let ee=J[q];return Array.isArray(ee)?L+=ee.reduce((he,fe)=>(he+=3+r.byteLength(q.toString())+2+r.byteLength(fe.toString()),he),0):L+=3+r.byteLength(q.toString())+2+r.byteLength(J[q].toString()),L},0);break}default:return G.destroy(new Error(`Invalid property ${Y}: ${J}`)),!1}return se}if(N)for(let Y in N){let J=0,ge=0,se=N[Y];if(se!==void 0){if(Array.isArray(se))for(let L=0;L<se.length;L++){if(ge=z(Y,se[L]),!ge)return!1;J+=ge}else{if(ge=z(Y,se),!ge)return!1;J=ge}if(!J)return!1;ne+=J}}return{length:r.byteLength(p(ne))+ne,write(){ye(G,N,ne)}}}function M(G,N,ne,z){let Y=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,N);if(J)for(;z+ge.length>J;){let se=Y.shift();if(se&&N[se])delete N[se],ge=Z(G,N);else return!1}return ge}function Q(G,N,ne){switch(t.propertiesTypes[N]){case"byte":{G.write(r.from([t.properties[N]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[N]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[N]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[N]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[N]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[N]])),B(G,ne);break}case"string":{G.write(r.from([t.properties[N]])),U(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(z=>{let Y=ne[z];Array.isArray(Y)?Y.forEach(J=>{G.write(r.from([t.properties[N]])),oe(G,z.toString(),J.toString())}):(G.write(r.from([t.properties[N]])),oe(G,z.toString(),Y.toString()))});break}default:return G.destroy(new Error(`Invalid property ${N} value: ${ne}`)),!1}}function ye(G,N,ne){B(G,ne);for(let z in N)if(Object.prototype.hasOwnProperty.call(N,z)&&N[z]!=null){let Y=N[z];if(Array.isArray(Y))for(let J=0;J<Y.length;J++)Q(G,z,Y[J]);else Q(G,z,Y)}}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}),lu=pe((i,e)=>{le(),ue(),ce();var t=Ss(),{EventEmitter:r}=(Lt(),Ne(_t)),{Buffer:s}=(qe(),Ne($e));function n(a,l){let c=new o;return t(a,c,l),c.concat()}var o=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=s.byteLength(c[d]),a+=l[d];let p=s.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),cu=pe(i=>{le(),ue(),ce(),i.parser=ou().parser,i.generate=lu(),i.writeToStream=Ss()}),uu=pe((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof kr?kr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let o=new Map;if(o.set(Date,d=>new Date(d)),o.set(Map,(d,p)=>new Map(l(Array.from(d),p))),o.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)o.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,p){let g=Object.keys(d),f=new Array(g.length);for(let y=0;y<g.length;y++){let b=g[y],w=d[b];typeof w!="object"||w===null?f[b]=w:w.constructor!==Object&&(a=o.get(w.constructor))?f[b]=a(w,p):ArrayBuffer.isView(w)?f[b]=t(w):f[b]=p(w)}return f}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,c);let p={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[g]=a(f,c):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=c(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,u);let p={};for(let g in d){let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[g]=a(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function s(n){let o=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,f)=>new Map(u(Array.from(g),f))),l.set(Set,(g,f)=>new Set(u(Array.from(g),f))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?p:d;function u(g,f){let y=Object.keys(g),b=new Array(y.length);for(let w=0;w<y.length;w++){let m=y[w],k=g[m];if(typeof k!="object"||k===null)b[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))b[m]=c(k,f);else if(ArrayBuffer.isView(k))b[m]=t(k);else{let S=o.indexOf(k);S!==-1?b[m]=a[S]:b[m]=f(k)}}return b}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let f={};o.push(g),a.push(f);for(let y in g){if(Object.hasOwnProperty.call(g,y)===!1)continue;let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=l.get(b.constructor)))f[y]=c(b,d);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=a[w]:f[y]=d(b)}}return o.pop(),a.pop(),f}function p(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,p);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,p);let f={};o.push(g),a.push(f);for(let y in g){let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=l.get(b.constructor)))f[y]=c(b,p);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=a[w]:f[y]=p(b)}}return o.pop(),a.pop(),f}}}),du=pe((i,e)=>{le(),ue(),ce(),e.exports=uu()()}),xs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.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}}),Es=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Nt(),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,o){return this._inflights.set(n.messageId,n),o&&o(),this}createStream(){let n=new e.Readable(t),o=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{o.push(c)}),n._read=()=>{!a&&l<o.length?n.push(o[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,o){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),o(null,a)):o&&o(new Error("missing packet")),this}get(n,o){let a=this._inflights.get(n.messageId);return a?o(null,a):o&&o(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=s}),hu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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 o=s.topic.toString(),a=s.payload,{qos:l}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let d;if(s.properties&&(d=s.properties.topicAlias),typeof d<"u")if(o.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)o=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",o,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(o,d))r.log("handlePublish :: registered topic: %s - alias: %d",o,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",o,a,s),r.handleMessage(s,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",o,a,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),fu=pe((i,e)=>{e.exports={version:"5.15.0"}}),zt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.MQTTJS_VERSION=i.nextTick=i.ErrorWithSubackPacket=i.ErrorWithReasonCode=void 0,i.applyMixin=r;var e=class bc extends Error{code;constructor(n,o){super(n),this.code=o,Object.setPrototypeOf(this,bc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class vc extends Error{packet;constructor(n,o){super(n),this.packet=o,Object.setPrototypeOf(this,vc.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(s,n,o=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(o||c!=="constructor")&&Object.defineProperty(s.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof je?.nextTick=="function"?je.nextTick:s=>{setTimeout(s,0)},i.MQTTJS_VERSION=fu().version}),Er=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=zt();i.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,o=s.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[p]}`),c.code=p;let g=r.messageIdToTopic[n];g&&g.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),pu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=zt(),t=Er(),r=(s,n)=>{let{options:o}=s,a=o.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(l===24)s.reconnecting=!1,s._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);s.emit("error",d)}})};i.default=r}),mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof je=="object"&&je?je:{},s=(g,f,y,b)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,y,b):console.error(`[${y}] ${f}: ${g}`)},n=globalThis.AbortController,o=globalThis.AbortSignal;if(typeof n>"u"){o=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(y,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new o;abort(y){if(!this.signal.aborted){this.signal.reason=y,this.signal.aborted=!0;for(let b of this.signal._onabort)b(y);this.signal.onabort?.(y)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!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 a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class gr{heap;length;static#l=!1;static create(f){let y=c(f);if(!y)return[];gr.#l=!0;let b=new gr(f,y);return gr.#l=!1,b}constructor(f,y){if(!gr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new y(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class wc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#r;#e;#c;#h;#a;#o;#b;#s;#v;#w;#f;#k;#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.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#b,isBackgroundFetch:y=>f.#t(y),backgroundFetch:(y,b,w,m)=>f.#R(y,b,w,m),moveToTail:y=>f.#C(y),indexes:y=>f.#_(y),rindexes:y=>f.#S(y),isStale:y=>f.#p(y)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(f){let{max:y=0,ttl:b,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:S,allowStale:v,dispose:x,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:O,maxSize:C=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:$,memoMethod:B,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:K,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=f;if(y!==0&&!l(y))throw new TypeError("max option must be a nonnegative integer");let F=y?c(y):Array;if(!F)throw new Error("invalid max value: "+y);if(this.#l=y,this.#d=C,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!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(B!==void 0&&typeof B!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=B,$!==void 0&&typeof $!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=$,this.#A=!!$,this.#n=new Map,this.#r=new Array(y).fill(void 0),this.#e=new Array(y).fill(void 0),this.#c=new F(y),this.#h=new F(y),this.#a=0,this.#o=0,this.#b=d.create(y),this.#i=0,this.#y=0,typeof x=="function"&&(this.#m=x),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!O,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!K,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!re,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!S,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#d){let Z="LRU_CACHE_UNBOUNDED";a(Z)&&(t.add(Z),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,wc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),y=new u(this.#l);this.#f=f,this.#w=y,this.#j=(m,k,S=e.now())=>{if(y[m]=k!==0?S:0,f[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#x(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{y[m]=f[m]!==0?e.now():0},this.#E=(m,k)=>{if(f[k]){let S=f[k],v=y[k];if(!S||!v)return;m.ttl=S,m.start=v,m.now=b||w();let x=m.now-v;m.remainingTTL=S-x}};let b=0,w=()=>{let m=e.now();if(this.ttlResolution>0){b=m;let k=setTimeout(()=>b=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let S=f[k],v=y[k];if(!S||!v)return 1/0;let x=(b||w())-v;return S-x},this.#p=m=>{let k=y[m],S=f[m];return!!S&&!!k&&(b||w())-k>S}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#y=0,this.#v=f,this.#T=y=>{this.#y-=f[y],f[y]=0},this.#U=(y,b,w,m)=>{if(this.#t(b))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(b,y),!l(w))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 w},this.#M=(y,b,w)=>{if(f[y]=b,this.#d){let m=this.#d-f[y];for(;this.#y>m;)this.#L(!0)}this.#y+=f[y],w&&(w.entrySize=b,w.totalCalculatedSize=this.#y)}}#T=f=>{};#M=(f,y,b)=>{};#U=(f,y,b,w)=>{if(b||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:f=this.allowStale}={}){if(this.#i)for(let y=this.#o;!(!this.#B(y)||((f||!this.#p(y))&&(yield y),y===this.#a));)y=this.#h[y]}*#S({allowStale:f=this.allowStale}={}){if(this.#i)for(let y=this.#a;!(!this.#B(y)||((f||!this.#p(y))&&(yield y),y===this.#o));)y=this.#c[y]}#B(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#_())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#S())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#_()){let y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*rkeys(){for(let f of this.#S()){let y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*values(){for(let f of this.#_())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#S())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,y={}){for(let b of this.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[b],this))return this.get(this.#r[b],y)}}forEach(f,y=this){for(let b of this.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}rforEach(f,y=this){for(let b of this.#S()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}purgeStale(){let f=!1;for(let y of this.#S({allowStale:!0}))this.#p(y)&&(this.#x(this.#r[y],"expire"),f=!0);return f}info(f){let y=this.#n.get(f);if(y===void 0)return;let b=this.#e[y],w=this.#t(b)?b.__staleWhileFetching:b;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[y],S=this.#w[y];if(k&&S){let v=k-(e.now()-S);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[y]),m}dump(){let f=[];for(let y of this.#_({allowStale:!0})){let b=this.#r[y],w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||b===void 0)continue;let k={value:m};if(this.#f&&this.#w){k.ttl=this.#f[y];let S=e.now()-this.#w[y];k.start=Math.floor(Date.now()-S)}this.#v&&(k.size=this.#v[y]),f.unshift([b,k])}return f}load(f){this.clear();for(let[y,b]of f){if(b.start){let w=Date.now()-b.start;b.start=e.now()-w}this.set(y,b.value,b)}}set(f,y,b={}){if(y===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:S=this.sizeCalculation,status:v}=b,{noUpdateTTL:x=this.noUpdateTTL}=b,E=this.#U(f,y,b.size||0,S);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#x(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.#b.length!==0?this.#b.pop():this.#i===this.#l?this.#L(!1):this.#i,this.#r[I]=f,this.#e[I]=y,this.#n.set(f,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#M(I,E,v),v&&(v.set="add"),x=!1;else{this.#C(I);let O=this.#e[I];if(y!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:C}=O;C!==void 0&&!k&&(this.#k&&this.#m?.(C,f,"set"),this.#u&&this.#s?.push([C,f,"set"]))}else k||(this.#k&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]));if(this.#T(I),this.#M(I,E,v),this.#e[I]=y,v){v.set="replace";let C=O&&this.#t(O)?O.__staleWhileFetching:O;C!==void 0&&(v.oldValue=C)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(x||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let O=this.#s,C;for(;C=O?.shift();)this.#g?.(...C)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#L(!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,y;for(;y=f?.shift();)this.#g?.(...y)}}}#L(f){let y=this.#a,b=this.#r[y],w=this.#e[y];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,b,"evict"),this.#u&&this.#s?.push([w,b,"evict"])),this.#T(y),f&&(this.#r[y]=void 0,this.#e[y]=void 0,this.#b.push(y)),this.#i===1?(this.#a=this.#o=0,this.#b.length=0):this.#a=this.#c[y],this.#n.delete(b),this.#i--,y}has(f,y={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:w}=y,m=this.#n.get(f);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return b&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,y={}){let{allowStale:b=this.allowStale}=y,w=this.#n.get(f);if(w===void 0||!b&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#R(f,y,b,w){let m=y===void 0?void 0:this.#e[y];if(this.#t(m))return m;let k=new n,{signal:S}=b;S?.addEventListener("abort",()=>k.abort(S.reason),{signal:k.signal});let v={signal:k.signal,options:b,context:w},x=(T,$=!1)=>{let{aborted:B}=k.signal,U=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(B&&!$?(b.status.fetchAborted=!0,b.status.fetchError=k.signal.reason,U&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),B&&!U&&!$)return I(k.signal.reason);let oe=C;return this.#e[y]===C&&(T===void 0?oe.__staleWhileFetching?this.#e[y]=oe.__staleWhileFetching:this.#x(f,"fetch"):(b.status&&(b.status.fetchUpdated=!0),this.set(f,T,v.options))),T},E=T=>(b.status&&(b.status.fetchRejected=!0,b.status.fetchError=T),I(T)),I=T=>{let{aborted:$}=k.signal,B=$&&b.allowStaleOnFetchAbort,U=B||b.allowStaleOnFetchRejection,oe=U||b.noDeleteOnFetchRejection,K=C;if(this.#e[y]===C&&(!oe||K.__staleWhileFetching===void 0?this.#x(f,"fetch"):B||(this.#e[y]=K.__staleWhileFetching)),U)return b.status&&K.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),K.__staleWhileFetching;if(K.__returned===K)throw T},O=(T,$)=>{let B=this.#P?.(f,m,v);B&&B instanceof Promise&&B.then(U=>T(U===void 0?void 0:U),$),k.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=U=>x(U,!0)))})};b.status&&(b.status.fetchDispatched=!0);let C=new Promise(O).then(x,E),j=Object.assign(C,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return y===void 0?(this.set(f,j,{...v.options,status:void 0}),y=this.#n.get(f)):this.#e[y]=j,j}#t(f){if(!this.#A)return!1;let y=f;return!!y&&y instanceof Promise&&y.hasOwnProperty("__staleWhileFetching")&&y.__abortController instanceof n}async fetch(f,y={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:S=this.noDisposeOnSet,size:v=0,sizeCalculation:x=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:O=this.allowStaleOnFetchRejection,ignoreFetchAbort:C=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:$=!1,status:B,signal:U}=y;if(!this.#A)return B&&(B.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:B});let oe={allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:S,size:v,sizeCalculation:x,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:j,ignoreFetchAbort:C,status:B,signal:U},K=this.#n.get(f);if(K===void 0){B&&(B.fetch="miss");let W=this.#R(f,K,oe,T);return W.__returned=W}else{let W=this.#e[K];if(this.#t(W)){let M=b&&W.__staleWhileFetching!==void 0;return B&&(B.fetch="inflight",M&&(B.returnedStale=!0)),M?W.__staleWhileFetching:W.__returned=W}let re=this.#p(K);if(!$&&!re)return B&&(B.fetch="hit"),this.#C(K),w&&this.#I(K),B&&this.#E(B,K),W;let F=this.#R(f,K,oe,T),Z=F.__staleWhileFetching!==void 0&&b;return B&&(B.fetch=re?"stale":"refresh",Z&&re&&(B.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,y={}){let b=await this.fetch(f,y);if(b===void 0)throw new Error("fetch() returned undefined");return b}memo(f,y={}){let b=this.#O;if(!b)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=y,S=this.get(f,k);if(!m&&S!==void 0)return S;let v=b(f,S,{options:k,context:w});return this.set(f,v,k),v}get(f,y={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=y,S=this.#n.get(f);if(S!==void 0){let v=this.#e[S],x=this.#t(v);return k&&this.#E(k,S),this.#p(S)?(k&&(k.get="stale"),x?(k&&b&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#x(f,"expire"),k&&b&&(k.returnedStale=!0),b?v:void 0)):(k&&(k.get="hit"),x?v.__staleWhileFetching:(this.#C(S),w&&this.#I(S),v))}else k&&(k.get="miss")}#D(f,y){this.#h[y]=f,this.#c[f]=y}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#D(this.#h[f],this.#c[f]),this.#D(this.#o,f),this.#o=f)}delete(f){return this.#x(f,"delete")}#x(f,y){let b=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(b=!0,this.#i===1)this.#F(y);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,f,y),this.#u&&this.#s?.push([m,f,y])),this.#n.delete(f),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let S=this.#c[w];this.#h[S]=this.#h[w]}this.#i--,this.#b.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return b}clear(){return this.#F("delete")}#F(f){for(let y of this.#S({allowStale:!0})){let b=this.#e[y];if(this.#t(b))b.__abortController.abort(new Error("deleted"));else{let w=this.#r[y];this.#k&&this.#m?.(b,w,f),this.#u&&this.#s?.push([b,w,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.#b.length=0,this.#y=0,this.#i=0,this.#u&&this.#s){let y=this.#s,b;for(;b=y?.shift();)this.#g?.(...b)}}};i.LRUCache=p}),gt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};i.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};i.Base=t;var r=class extends t{};i.Container=r}),gu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(o){n.push(o)})}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;i.default=r}),yu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(o){n.push(o)})}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 o=this.i;for(let a=0;a<o;++a)this.q[a]=this.q[this.j+a];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;i.default=r}),bu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=gt(),t=class extends e.Base{constructor(s=[],n=function(a,l){return a>l?-1:a<l?1:0},o=!0){if(super(),this.v=n,Array.isArray(s))this.C=o?[...s]:s;else{this.C=[];let l=this;s.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(s){let n=this.C[s];for(;s>0;){let o=s-1>>1,a=this.C[o];if(this.v(a,n)<=0)break;this.C[s]=a,s=o}this.C[s]=n}k(s,n){let o=this.C[s];for(;s<n;){let a=s<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,o)>=0)break;this.C[s]=c,s=a}this.C[s]=o}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;i.default=r}),xi=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=gt(),t=class extends e.Container{},r=t;i.default=r}),yt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),As=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=gt(),t=yt(),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)}};i.RandomIterator=r}),vu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=As();function r(a){return a&&a.t?a:{default:a}}var s=class kc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new kc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.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(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new s(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},o=n;i.default=o}),wu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(xi()),t=gt(),r=yt();function s(l){return l&&l.t?l:{default:l}}var n=class _c extends t.ContainerIterator{constructor(c,u,d,p){super(p),this.o=c,this.h=u,this.container=d,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l}set pointer(c){this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.l=c}copy(){return new _c(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=o;i.default=a}),ku=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=As();function r(a){return a&&a.t?a:{default:a}}var s=class Sc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Sc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,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 d=this;a.forEach(function(p){d.pushBack(p)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new 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(a){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]=a,this.i}popBack(){if(this.i===0)return;let a=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,a}pushFront(a){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]=a,this.i}popFront(){if(this.i===0)return;let a=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,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new s(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),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 l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},o=n;i.default=o}),_u=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.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}};i.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)}};i.TreeNodeEnableIndex=t}),Is=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=_u(),t=gt(),r=yt(),s=class extends t.Container{constructor(o=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=o,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(d);if(g){let{parentNode:f,grandParent:y,curNode:b}=g;f.ie(),y.ie(),b.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)o=o.W;else if(c>0)l=o,o=o.U;else return o}return l}Z(o,a){let l=this.h;for(;o;)this.v(o.u,a)<=0?o=o.W:(l=o,o=o.U);return l}$(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)l=o,o=o.W;else if(c>0)o=o.U;else return o}return l}rr(o,a){let l=this.h;for(;o;)this.v(o.u,a)<0?(l=o,o=o.W):o=o.U;return l}ue(o){for(;;){let a=o.tt;if(a===this.h)return;if(o.ee===1){o.ee=0;return}if(o===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,o=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,o=a)}}}fe(o){if(this.i===1)return this.clear(),this.h;let a=o;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[o.u,a.u]=[a.u,o.u],[o.l,a.l]=[a.l,o.l],o=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(o,a){return o===void 0?!1:this.oe(o.U,a)||a(o)?!0:this.oe(o.W,a)}he(o){for(;;){let a=o.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.W){if(o.ee=0,o.U&&(o.U.tt=a),o.W&&(o.W.tt=l),a.W=o.U,l.U=o.W,o.U=a,o.W=l,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.U){if(o.ee=0,o.U&&(o.U.tt=l),o.W&&(o.W.tt=a),l.W=o.U,a.U=o.W,o.U=l,o.W=a,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(o,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(o,a),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,d=this.v(u.u,o);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(o,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,o);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(o,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let f=l.o;if(f!==this.h){let y=this.v(f.u,o);if(y===0){f.l=a;return}else if(y>0){let b=f.L(),w=this.v(b.u,o);if(w===0){b.l=a;return}else w<0&&(c=new this.re(o,a),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,o);if(f>0){if(c.U===void 0){c.U=new this.re(o,a),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(o,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(o,a){for(;o;){let l=this.v(o.u,a);if(l<0)o=o.W;else if(l>0)o=o.U;else return o}return o||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(o,a){let l=o.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return o===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(o){if(this.i===0)return!1;let a=this.I(this.Y,o);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(o){let a=o.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return o.iteratorType===0?l&&o.next():(!l||a.U===void 0)&&o.next(),this.V(a),o}forEach(o){let a=0;for(let l of this)o(l,a++,this)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===o){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let o=function(a){return a?Math.max(o(a.U),o(a.W))+1:0};return o(this.Y)}},n=s;i.default=n}),Ts=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=gt(),t=yt(),r=class extends e.ContainerIterator{constructor(n,o,a){super(a),this.o=n,this.h=o,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,o=this.h.tt;if(n===this.h)return o?o.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==o;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},s=r;i.default=s}),Su=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(Is()),t=s(Ts()),r=yt();function s(l){return l&&l.t?l:{default:l}}var n=class xc extends t.default{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new xc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.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(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),xu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(Is()),t=s(Ts()),r=yt();function s(l){return l&&l.t?l:{default:l}}var n=class Ec extends t.default{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Ec(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.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 l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),Cs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ps=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=gt(),t=s(Cs()),r=yt();function s(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,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})}};i.HashContainerIterator=n;var o=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(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};i.HashContainer=o}),Eu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ps(),t=yt(),r=class Ac extends e.HashContainerIterator{constructor(a,l,c,u){super(a,l,u),this.container=c}get pointer(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o.u}copy(){return new Ac(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(o=[]){super();let a=this;o.forEach(function(l){a.insert(l)})}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(o,a){return this.M(o,void 0,a)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=this.p;for(;o--;)a=a.B;return a.u}find(o,a){let l=this.I(o,a);return new r(l,this.h,this)}forEach(o){let a=0,l=this.p;for(;l!==this.h;)o(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield o.u,o=o.B}).bind(this)()}},n=s;i.default=n}),Au=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ps(),t=s(Cs()),r=yt();function s(l){return l&&l.t?l:{default:l}}var n=class Ic extends e.HashContainerIterator{constructor(c,u,d,p){super(c,u,p),this.container=d}get pointer(){this.o===this.h&&(0,r.throwIteratorAccessError)();let c=this;return new Proxy([],{get(u,d){if(d==="0")return c.o.u;if(d==="1")return c.o.l},set(u,d,p){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=p,!0}})}copy(){return new Ic(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.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(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=o;i.default=a}),Iu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(i,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(i,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(i,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(i,"Vector",{enumerable:!0,get:function(){return s.default}});var e=d(gu()),t=d(yu()),r=d(bu()),s=d(vu()),n=d(wu()),o=d(ku()),a=d(Su()),l=d(xu()),c=d(Eu()),u=d(Au());function d(p){return p&&p.t?p:{default:p}}}),Tu=pe((i,e)=>{le(),ue(),ce();var t=Iu().OrderedSet,r=mt()("number-allocator:trace"),s=mt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function o(a,l){if(!(this instanceof o))return new o(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}o.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},o.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},o.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},o.prototype.free=function(a){if(a<this.min||a>this.max){s("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},o.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=o}),Os=pe((i,e)=>{le(),ue(),ce();var t=Tu();e.exports.NumberAllocator=t}),Cu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=mu(),t=Os(),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 o=this.aliasToTopic.get(n);return o&&delete this.topicToAlias[o],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]}};i.default=r}),Pu=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(i,"__esModule",{value:!0});var t=Er(),r=e(Cu()),s=zt(),n=(o,a)=>{o.log("_handleConnack");let{options:l}=o,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(o.connackTimer),delete o.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){o.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(o.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)o.reconnecting=!1,o._onConnect(a);else if(c>0){let u=new s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);o.emit("error",u),o.options.reconnectOnConnackError&&o._cleanUp(!0)}};i.default=n}),Ou=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s:t.noop,{messageId:o}=r,a={cmd:"pubcomp",messageId:o};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,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(a,n)}))})};i.default=e}),Mu=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(hu()),r=e(pu()),s=e(Pu()),n=e(Er()),o=e(Ou()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,o.default)(l,c,u);break;case"connack":(0,s.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};i.default=a}),Ms=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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(){}};i.default=e}),Lu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__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={}}};i.default=e}),Ru=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=void 0;var t=e((Lt(),Ne(_t))),r=zt(),s=class{};i.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),Ar=pe((i,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}),Nu=pe((i,e)=>{le(),ue(),ce();var t=Ar().default;function r(s,n){if(t(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,n||"default");if(t(a)!="object")return a;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}),ju=pe((i,e)=>{le(),ue(),ce();var t=Ar().default,r=Nu();function s(n){var o=r(n,"string");return t(o)=="symbol"?o:o+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Uu=pe((i,e)=>{le(),ue(),ce();var t=ju();function r(s,n,o){return(n=t(n))in s?Object.defineProperty(s,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):s[n]=o,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((i,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}),Du=pe((i,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 o,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(o=l.call(n)).done)&&(u.push(o.value),u.length!==s);d=!0);}catch(g){p=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((i,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,o=Array(s);n<s;n++)o[n]=r[n];return o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((i,e)=>{le(),ue(),ce();var t=Fu();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var o={}.toString.call(s).slice(8,-1);return o==="Object"&&s.constructor&&(o=s.constructor.name),o==="Map"||o==="Set"?Array.from(s):o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((i,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}),Hu=pe((i,e)=>{le(),ue(),ce();var t=Bu(),r=Du(),s=$u(),n=qu();function o(a,l){return t(a)||r(a,l)||s(a,l)||n()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(i,function(t){var r=function(g){return function(f){var y=g(f);return f.add(y),y}},s=function(g){return function(f,y){return g.set(f,y),y}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,a=o*2,l=function(g,f){return function(y){var b=f.get(y),w=b===void 0?y.size:b<a?b+1:0;if(!y.has(w))return g(y,w);if(y.size<o){for(;y.has(w);)w=Math.floor(Math.random()*a);return g(y,w)}if(y.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;y.has(w);)w=Math.floor(Math.random()*n);return g(y,w)}},c=new WeakMap,u=s(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Wu=pe((i,e)=>{le(),ue(),ce();function t(s,n,o,a,l,c,u){try{var d=s[c](u),p=d.value}catch(g){return void o(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(s){return function(){var n=this,o=arguments;return new Promise(function(a,l){var c=s.apply(n,o);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((i,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}),Ns=pe((i,e)=>{le(),ue(),ce();function t(r,s,n,o){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(g,f){t(l,g,function(y){return this._invoke(g,f,y)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),js=pe((i,e)=>{le(),ue(),ce();var t=Ns();function r(){var s,n,o=typeof Symbol=="function"?Symbol:{},a=o.iterator||"@@iterator",l=o.toStringTag||"@@toStringTag";function c(w,m,k,S){var v=m&&m.prototype instanceof d?m:d,x=Object.create(v.prototype);return t(x,"_invoke",(function(E,I,O){var C,j,T,$=0,B=O||[],U=!1,oe={p:0,n:0,v:s,a:K,f:K.bind(s,4),d:function(W,re){return C=W,j=0,T=s,oe.n=re,u}};function K(W,re){for(j=W,T=re,n=0;!U&&$&&!F&&n<B.length;n++){var F,Z=B[n],M=oe.p,Q=Z[2];W>3?(F=Q===re)&&(T=Z[(j=Z[4])?5:(j=3,3)],Z[4]=Z[5]=s):Z[0]<=M&&((F=W<2&&M<Z[1])?(j=0,oe.v=re,oe.n=Z[1]):M<Q&&(F=W<3||Z[0]>re||re>Q)&&(Z[4]=W,Z[5]=re,oe.n=Q,j=0))}if(F||W>1)return u;throw U=!0,re}return function(W,re,F){if($>1)throw TypeError("Generator is already running");for(U&&re===1&&K(re,F),j=re,T=F;(n=j<2?s:T)||!U;){C||(j?j<3?(j>1&&(oe.n=-1),K(j,T)):oe.n=T:oe.v=T);try{if($=2,C){if(j||(W="next"),n=C[W]){if(!(n=n.call(C,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=C.return)&&n.call(C),j<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),j=1);C=s}else if((n=(U=oe.n<0)?T:E.call(I,oe))!==u)break}catch(Z){C=s,j=1,T=Z}finally{$=1}}return{value:n,done:U}}})(w,k,S),!0),x}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),y=g.prototype=d.prototype=Object.create(f);function b(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(y),w}return p.prototype=g,t(y,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(y),t(y,l,"Generator"),t(y,a,function(){return this}),t(y,"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}),Us=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=Ns();function s(n,o){function a(c,u,d,p){try{var g=n[c](u),f=g.value;return f instanceof t?o.resolve(f.v).then(function(y){a("next",y,d,p)},function(y){a("throw",y,d,p)}):o.resolve(f).then(function(y){g.value=y,d(g)},function(y){return a("throw",y,d,p)})}catch(y){p(y)}}var l;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new o(function(g,f){a(c,d,g,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Bs=pe((i,e)=>{le(),ue(),ce();var t=js(),r=Us();function s(n,o,a,l,c){return new r(t().w(n,o,a,l),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=pe((i,e)=>{le(),ue(),ce();var t=Bs();function r(s,n,o,a,l){var c=t(s,n,o,a,l);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}),Vu=pe((i,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var o in s)n.unshift(o);return function a(){for(;n.length;)if((o=n.pop())in s)return a.value=o,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ku=pe((i,e)=>{le(),ue(),ce();var t=Ar().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],o=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&o>=s.length&&(s=void 0),{value:s&&s[o++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Gu=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=js(),s=zu(),n=Bs(),o=Us(),a=Vu(),l=Ku();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(b){var w=typeof b=="function"&&b.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function y(b){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(S,v){return m(k.a,f[S],v)},delegateYield:function(S,v,x){return w.resultName=v,m(k.d,l(S),x)},finish:function(S){return m(k.f,S)}},m=function(S,v,x){k.p=w.prev,k.n=w.next;try{return S(v,x)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return b.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(b,w,m,k){return u.w(y(b),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(b,w){return new t(b,w)},AsyncIterator:o,async:function(b,w,m,k,S){return(g(w)?n:s)(y(b),w,m,k,S)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Yu=pe((i,e)=>{le(),ue(),ce();var t=Gu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Ju=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Uu(),Hu(),Ls(),Wu(),Yu()):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))})(i,function(t,r,s,n,o,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),S.push.apply(S,v)}return S}function d(m){for(var k=1;k<arguments.length;k++){var S=arguments[k]!=null?arguments[k]:{};k%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 d(d({},m),{},{connect:function(k){var S=k.call;return o(a.mark(function v(){var x,E,I,O;return a.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return x=new MessageChannel,E=x.port1,I=x.port2,C.next=1,S("connect",{port:E},[E]);case 1:return O=C.sent,c.set(I,O),C.abrupt("return",I);case 2:case"end":return C.stop()}},v)}))},disconnect:function(k){var S=k.call;return(function(){var v=o(a.mark(function x(E){var I;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:if(I=c.get(E),I!==void 0){O.next=1;break}throw new Error("The given port is not connected.");case 1:return O.next=2,S("disconnect",{portId:I});case 2:case"end":return O.stop()}},x)}));return function(x){return v.apply(this,arguments)}})()},isSupported:function(k){var S=k.call;return function(){return S("isSupported")}}})};function g(m,k){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),S.push.apply(S,v)}return S}function f(m){for(var k=1;k<arguments.length;k++){var S=arguments[k]!=null?arguments[k]:{};k%2?g(Object(S),!0).forEach(function(v){r(m,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(S)):g(Object(S)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(S,v))})}return m}var y=new WeakMap,b=function(m){if(y.has(m))return y.get(m);var k=new Map;return y.set(m,k),k},w=function(m){var k=p(m);return function(S){var v=b(S);S.addEventListener("message",function(B){var U=B.data,oe=U.id;if(oe!==null&&v.has(oe)){var K=v.get(oe),W=K.reject,re=K.resolve;v.delete(oe),U.error===void 0?re(U.result):W(new Error(U.error.message))}}),l(S)&&S.start();for(var x=function(B){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(K,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:K}),U===null?S.postMessage({id:re,method:B},oe):S.postMessage({id:re,method:B,params:U},oe)})},E=function(B,U){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];S.postMessage({id:null,method:B,params:U},oe)},I={},O=0,C=Object.entries(k);O<C.length;O++){var j=s(C[O],2),T=j[0],$=j[1];I=f(f({},I),{},r({},T,$({call:x,notify:E})))}return f({},I)}};t.createBroker=w})}),Qu=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Ar(),Ju(),Ls()):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))})(i,function(t,r,s,n){var o=new Map([[0,null]]),a=new Map([[0,null]]),l=s.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){o.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(o);o.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var S=o.get(m);if(S===void 0)throw new Error("The timer is in an undefined state.");S===w&&(p.apply(void 0,y),o.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),p.apply(void 0,y))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),Xu=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Qu()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(i,function(t,r){var s=function(d,p){var g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),y=URL.createObjectURL(f);return g=d(y),setTimeout(function(){return URL.revokeObjectURL(y)}),g}},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)})()})();`,o=s(r.load,n),a=function(d){return o().clearInterval(d)},l=function(d){return o().clearTimeout(d)},c=function(){var d;return(d=o()).setInterval.apply(d,arguments)},u=function(){var d;return(d=o()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Ir=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.isReactNativeBrowser=i.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&je?.versions?!Object.prototype.hasOwnProperty.call(je.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();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=s}),Zu=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,g)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=i&&i.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=i&&i.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(p[p.length]=g);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),g=0;g<p.length;g++)p[g]!=="default"&&e(d,u,p[g]);return t(d,u),d}})();Object.defineProperty(i,"__esModule",{value:!0});var s=Xu(),n=r(Ir()),o={set:s.setInterval,clear:s.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return o;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?o:a}};i.default=l}),Ds=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(Zu()),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)}};i.default=r}),Ei=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(v,x,E,I){I===void 0&&(I=E);var O=Object.getOwnPropertyDescriptor(x,E);(!O||("get"in O?!x.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return x[E]}}),Object.defineProperty(v,I,O)}:function(v,x,E,I){I===void 0&&(I=E),v[I]=x[E]}),t=i&&i.__setModuleDefault||(Object.create?function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}:function(v,x){v.default=x}),r=i&&i.__importStar||(function(){var v=function(x){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var O in E)Object.prototype.hasOwnProperty.call(E,O)&&(I[I.length]=O);return I},v(x)};return function(x){if(x&&x.__esModule)return x;var E={};if(x!=null)for(var I=v(x),O=0;O<I.length;O++)I[O]!=="default"&&e(E,x,I[O]);return t(E,x),E}})(),s=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=s(cu()),o=Nt(),a=s(du()),l=s(mt()),c=r(xs()),u=s(Es()),d=s(Mu()),p=s(Ms()),g=s(Lu()),f=zt(),y=Ru(),b=s(Ds()),w=r(Ir()),m=globalThis.setImmediate||((...v)=>{let x=v.shift();(0,f.nextTick)(()=>{x(...v)})}),k={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 Bo extends y.TypedEventEmitter{static VERSION=f.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(x,E){super(),this.options=E||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Bo.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",E.protocol),this.log("MqttClient :: options.protocolVersion",E.protocolVersion),this.log("MqttClient :: options.username",E.username),this.log("MqttClient :: options.keepalive",E.keepalive),this.log("MqttClient :: options.reconnectPeriod",E.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",E.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",E.properties?E.properties.topicAliasMaximum:void 0),this.options.clientId=typeof E.clientId=="string"?E.clientId:Bo.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=E.protocolVersion===5&&E.customHandleAcks?E.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=x,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=E.outgoingStore||new u.default,this.incomingStore=E.incomingStore||new u.default,this.queueQoSZero=E.queueQoSZero===void 0?!0:E.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,E.properties&&E.properties.topicAliasMaximum>0&&(E.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(E.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,O=()=>{let C=I.shift();this.log("deliver :: entry %o",C);let j=null;if(!C){this._resubscribe();return}j=C.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,$=>{C.cb&&C.cb($),O()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.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(x,E){E()}handleMessage(x,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let x=new o.Writable,E=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),E.on("packet",B=>{this.log("parser :: on packet push to packets array."),O.push(B)});let C=()=>{this.log("work :: getting next packet in queue");let B=O.shift();if(B)this.log("work :: packet pulled from queue"),(0,d.default)(this,B,j);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(O.length)(0,f.nextTick)(C);else{let B=I;I=null,B()}};x._write=(B,U,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(B),C()};let T=B=>{this.log("streamErrorHandler :: error",B.message),B.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",B)):this.noop(B)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(x),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let $={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&&($.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&($.properties||($.properties={}),this.topicAliasRecv&&($.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket($),E.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let B={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(B)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(x,E,I,O){this.log("publish :: message `%s` to topic `%s`",E,x);let{options:C}=this;typeof I=="function"&&(O=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:j,retain:T,dup:$,properties:B,cbStorePut:U}=I;if(this._checkDisconnecting(O))return this;let oe=()=>{let K=0;if((j===1||j===2)&&(K=this._nextId(),K===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:x,payload:E,qos:j,retain:T,messageId:K,dup:$};switch(C.protocolVersion===5&&(W.properties=B),this.log("publish :: qos",j),j){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:O||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,U);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,O,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:I.cbStorePut,callback:O}),this}publishAsync(x,E,I){return new Promise((O,C)=>{this.publish(x,E,I,(j,T)=>{j?C(j):O(T)})})}subscribe(x,E,I){let O=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let C=!1,j=[];typeof x=="string"?(x=[x],j=x):Array.isArray(x)?j=x:typeof x=="object"&&(C=x.resubscribe,delete x.resubscribe,j=Object.keys(x));let T=c.validateTopics(j);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let $={qos:0};O===5&&($.nl=!1,$.rap=!1,$.rh=0),E={...$,...E};let{properties:B}=E,U=[],oe=(re,F)=>{if(F=F||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,re)||this._resubscribeTopics[re].qos<F.qos||C){let Z={topic:re,qos:F.qos};O===5&&(Z.nl=F.nl,Z.rap=F.rap,Z.rh=F.rh,Z.properties=B),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),U.push(Z)}};if(Array.isArray(x)?x.forEach(re=>{this.log("subscribe: array topic %s",re),oe(re)}):Object.keys(x).forEach(re=>{this.log("subscribe: object topic %s, %o",re,x[re]),oe(re,x[re])}),!U.length)return I(null,[]),this;let K=(re,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(B&&(Z.properties=B),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(ye=>{if(this.options.reconnectPeriod>0){let te={qos:ye.qos};O===5&&(te.nl=ye.nl||!1,te.rap=ye.rap||!1,te.rh=ye.rh||0,te.properties=ye.properties),this._resubscribeTopics[ye.topic]=te,Q.push(ye.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,ye)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let N=0;N<G.length;N+=1)re[N].qos=G[N]}te?ye(new f.ErrorWithSubackPacket(te.message,we)):Q(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(Z),M},W=()=>{let re=this.options.subscribeBatchSize??U.length,F=[];for(let Z=0;Z<U.length;Z+=re){let M=U.slice(Z,Z+re),Q=this._nextId();if(Q===null)return this.log("No messageId left"),!1;F.push(K(M,Q))}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||!W())&&this._storeProcessingQueue.push({invoke:W,callback:I}),this}subscribeAsync(x,E){return new Promise((I,O)=>{this.subscribe(x,E,(C,j)=>{C?O(C):I(j)})})}unsubscribe(x,E,I){typeof x=="string"&&(x=[x]),typeof E=="function"&&(I=E),I=I||this.noop;let O=c.validateTopics(x);if(O!==null)return m(I,new Error(`Invalid topic ${O}`)),this;if(this._checkDisconnecting(I))return this;let C=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof x=="string"?T.unsubscriptions=[x]:Array.isArray(x)&&(T.unsubscriptions=x),this.options.resubscribe&&T.unsubscriptions.forEach($=>{delete this._resubscribeTopics[$]}),typeof E=="object"&&E.properties&&(T.properties=E.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!C())&&this._storeProcessingQueue.push({invoke:C,callback:I}),this}unsubscribeAsync(x,E){return new Promise((I,O)=>{this.unsubscribe(x,E,(C,j)=>{C?O(C):I(j)})})}end(x,E,I){this.log("end :: (%s)",this.options.clientId),(x==null||typeof x!="boolean")&&(I=I||E,E=x,x=!1),typeof E!="object"&&(I=I||E,E=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let O=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let $=j||T;this.log("end :: closeStores: invoking callback with args"),I($)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},C=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,x),this._cleanUp(x,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(O)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!x&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,C,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),C()),this)}endAsync(x,E){return new Promise((I,O)=>{this.end(x,E,C=>{C?O(C):I()})})}removeOutgoingMessage(x){if(this.outgoing[x]){let{cb:E}=this.outgoing[x];this._removeOutgoingAndStoreMessage(x,()=>{E(new Error("Message removed"))})}return this}reconnect(x){this.log("client reconnect");let E=()=>{x?(this.options.incomingStore=x.incomingStore,this.options.outgoingStore=x.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=E:E(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(x=>{this.outgoing[x].volatile&&typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(x=>{typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_removeTopicAliasAndRecoverTopicName(x){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",E,I),I.length===0){if(typeof E>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(E),typeof I>"u")return new Error("Unregistered Topic Alias");x.topic=I}E&&delete x.properties.topicAlias}_checkDisconnecting(x){return this.disconnecting&&(x&&x!==this.noop?x(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(x,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",x),x)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let 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(),E&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",E),E())}_storeAndSend(x,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",x.cmd);let O=x,C;if(O.cmd==="publish"&&(O=(0,a.default)(x),C=this._removeTopicAliasAndRecoverTopicName(O),C))return E&&E(C);this.outgoingStore.put(O,j=>{if(j)return E&&E(j);I(),this._writePacket(x,E)})}_applyTopicAlias(x){if(this.options.protocolVersion===5&&x.cmd==="publish"){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.topicAliasSend)if(E){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,E),!this.topicAliasSend.put(I,E)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(E=this.topicAliasSend.getAliasByTopic(I),E?(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,E))));else if(E)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}}_noop(x){this.log("noop ::",x)}_writePacket(x,E){this.log("_writePacket :: packet: %O",x),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",x),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(x,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&E&&E!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",E)):E&&(this.log("_writePacket :: invoking cb"),E())}_sendPacket(x,E,I,O){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let C=this._applyTopicAlias(x);if(C){E(C);return}if(!this.connected){if(x.cmd==="auth"){this._writePacket(x,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(x,E,I);return}if(O){this._writePacket(x,E);return}switch(x.cmd){case"publish":break;case"pubrel":this._storeAndSend(x,E,I);return;default:this._writePacket(x,E);return}switch(x.qos){case 2:case 1:this._storeAndSend(x,E,I);break;default:this._writePacket(x,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(x,E,I){this.log("_storePacket :: packet: %o",x),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let O=x;if(O.cmd==="publish"){O=(0,a.default)(x);let j=this._removeTopicAliasAndRecoverTopicName(O);if(j)return E&&E(j)}let C=O.qos||0;C===0&&this.queueQoSZero||O.cmd!=="publish"?this.queue.push({packet:O,cb:E}):C>0?(E=this.outgoing[O.messageId]?this.outgoing[O.messageId].cb:null,this.outgoingStore.put(O,j=>{if(j)return E&&E(j);I()})):E&&E(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new b.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(x=!1){this.keepaliveManager&&this.options.keepalive&&(x||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let x=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&x.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<x.length;E++){let I={};I[x[E]]=this._resubscribeTopics[x[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[x[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(x){if(this.disconnected){this.emit("connect",x);return}this.connackPacket=x,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),O=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),C()},C=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",O),I.on("error",T=>{C(),this._flushStoreProcessingQueue(),this.removeListener("close",O),this.emit("error",T)});let j=()=>{if(!I)return;let T=I.read(1),$;if(!T){I.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?($=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(B,U){$&&$(B,U),j()}},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 $ in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[$]){T=!1;break}this.removeListener("close",O),T?(C(),this._invokeAllStoreProcessingQueue(),this.emit("connect",x)):E()}),j()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let x=this._storeProcessingQueue[0];if(x&&x.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let x of this._storeProcessingQueue)x.cbStorePut&&x.cbStorePut(new Error("Connection closed")),x.callback&&x.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(x,E){delete this.outgoing[x],this.outgoingStore.del({messageId:x},(I,O)=>{E(I,O),this.messageIdProvider.deallocate(x),this._invokeStoreProcessingQueue()})}};i.default=S}),ed=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Os(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};i.default=t});function td(){if(Ai)return Tr;Ai=!0;let i=2147483647,e=36,t=1,r=26,s=38,n=700,o=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,f=Math.floor,y=String.fromCharCode;function b(C){throw new RangeError(p[C])}function w(C,j){let T=[],$=C.length;for(;$--;)T[$]=j(C[$]);return T}function m(C,j){let T=C.split("@"),$="";T.length>1&&($=T[0]+"@",C=T[1]),C=C.replace(d,".");let B=C.split("."),U=w(B,j).join(".");return $+U}function k(C){let j=[],T=0,$=C.length;for(;T<$;){let B=C.charCodeAt(T++);if(B>=55296&&B<=56319&&T<$){let U=C.charCodeAt(T++);(U&64512)==56320?j.push(((B&1023)<<10)+(U&1023)+65536):(j.push(B),T--)}else j.push(B)}return j}let S=C=>String.fromCodePoint(...C),v=function(C){return C>=48&&C<58?26+(C-48):C>=65&&C<91?C-65:C>=97&&C<123?C-97:e},x=function(C,j){return C+22+75*(C<26)-((j!=0)<<5)},E=function(C,j,T){let $=0;for(C=T?f(C/n):C>>1,C+=f(C/j);C>g*r>>1;$+=e)C=f(C/g);return f($+(g+1)*C/(C+s))},I=function(C){let j=[],T=C.length,$=0,B=a,U=o,oe=C.lastIndexOf(l);oe<0&&(oe=0);for(let K=0;K<oe;++K)C.charCodeAt(K)>=128&&b("not-basic"),j.push(C.charCodeAt(K));for(let K=oe>0?oe+1:0;K<T;){let W=$;for(let F=1,Z=e;;Z+=e){K>=T&&b("invalid-input");let M=v(C.charCodeAt(K++));M>=e&&b("invalid-input"),M>f((i-$)/F)&&b("overflow"),$+=M*F;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let ye=e-Q;F>f(i/ye)&&b("overflow"),F*=ye}let re=j.length+1;U=E($-W,re,W==0),f($/re)>i-B&&b("overflow"),B+=f($/re),$%=re,j.splice($++,0,B)}return String.fromCodePoint(...j)},O=function(C){let j=[];C=k(C);let T=C.length,$=a,B=0,U=o;for(let W of C)W<128&&j.push(y(W));let oe=j.length,K=oe;for(oe&&j.push(l);K<T;){let W=i;for(let F of C)F>=$&&F<W&&(W=F);let re=K+1;W-$>f((i-B)/re)&&b("overflow"),B+=(W-$)*re,$=W;for(let F of C)if(F<$&&++B>i&&b("overflow"),F===$){let Z=B;for(let M=e;;M+=e){let Q=M<=U?t:M>=U+r?r:M-U;if(Z<Q)break;let ye=Z-Q,te=e-Q;j.push(y(x(Q+ye%te,0))),Z=f(ye/te)}j.push(y(x(Z,0))),U=E(B,re,K===oe),B=0,++K}++B,++$}return j.join("")};return Tr={version:"2.3.1",ucs2:{decode:k,encode:S},decode:I,encode:O,toASCII:function(C){return m(C,function(j){return u.test(j)?"xn--"+O(j):j})},toUnicode:function(C){return m(C,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},Tr}var Tr,Ai,xt,rd=Ye(()=>{le(),ue(),ce(),Tr={},Ai=!1,xt=td(),xt.decode,xt.encode,xt.toASCII,xt.toUnicode,xt.ucs2,xt.version});function nd(){return Pi||(Pi=!0,Ci=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var i={},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;i[e]=r;for(e in i)return!1;if(typeof Object.keys=="function"&&Object.keys(i).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(i).length!==0)return!1;var s=Object.getOwnPropertySymbols(i);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(i,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(i,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ci}function id(){return Mi||(Mi=!0,Oi=Error),Oi}function od(){return Ri||(Ri=!0,Li=EvalError),Li}function sd(){return ji||(ji=!0,Ni=RangeError),Ni}function ad(){return Bi||(Bi=!0,Ui=ReferenceError),Ui}function Fs(){return Fi||(Fi=!0,Di=SyntaxError),Di}function sr(){return qi||(qi=!0,$i=TypeError),$i}function ld(){return Wi||(Wi=!0,Hi=URIError),Hi}function cd(){if(zi)return Cr;zi=!0;var i=typeof Symbol<"u"&&Symbol,e=nd();return Cr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Cr}function ud(){if(Vi)return Pr;Vi=!0;var i={__proto__:null,foo:{}},e=Object;return Pr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Pr}function dd(){if(Ki)return Or;Ki=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},o=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Or=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(i+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var b=l.apply(this,s(c,arguments));return Object(b)===b?b:this}return l.apply(a,s(c,arguments))},p=t(0,l.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+o(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var y=function(){};y.prototype=l.prototype,u.prototype=new y,y.prototype=null}return u},Or}function Ii(){if(Gi)return Mr;Gi=!0;var i=dd();return Mr=Function.prototype.bind||i,Mr}function hd(){if(Yi)return Lr;Yi=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Ii();return Lr=t.call(i,e),Lr}function Vt(){if(Ji)return Rr;Ji=!0;var i,e=id(),t=od(),r=sd(),s=ad(),n=Fs(),o=sr(),a=ld(),l=Function,c=function(K){try{return l('"use strict"; return ('+K+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new o},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=cd()(),f=ud()(),y=Object.getPrototypeOf||(f?function(K){return K.__proto__}:null),b={},w=typeof Uint8Array>"u"||!y?i:y(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":g&&y?y([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?i:Atomics,"%BigInt%":typeof BigInt>"u"?i:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?i:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?i:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?i:Float32Array,"%Float64Array%":typeof Float64Array>"u"?i:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?i:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&y?y(y([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!y?i:y(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?i:Promise,"%Proxy%":typeof Proxy>"u"?i:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!y?i:y(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&y?y(""[Symbol.iterator]()):i,"%Symbol%":g?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?i:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?i:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?i:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?i:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?i:WeakMap,"%WeakRef%":typeof WeakRef>"u"?i:WeakRef,"%WeakSet%":typeof WeakSet>"u"?i:WeakSet};if(y)try{null.error}catch(K){var k=y(y(K));m["%Error.prototype%"]=k}var S=function K(W){var re;if(W==="%AsyncFunction%")re=c("async function () {}");else if(W==="%GeneratorFunction%")re=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")re=c("async function* () {}");else if(W==="%AsyncGenerator%"){var F=K("%AsyncGeneratorFunction%");F&&(re=F.prototype)}else if(W==="%AsyncIteratorPrototype%"){var Z=K("%AsyncGenerator%");Z&&y&&(re=y(Z.prototype))}return m[W]=re,re},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},x=Ii(),E=hd(),I=x.call(Function.call,Array.prototype.concat),O=x.call(Function.apply,Array.prototype.splice),C=x.call(Function.call,String.prototype.replace),j=x.call(Function.call,String.prototype.slice),T=x.call(Function.call,RegExp.prototype.exec),$=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,B=/\\(\\)?/g,U=function(K){var W=j(K,0,1),re=j(K,-1);if(W==="%"&&re!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(re==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return C(K,$,function(Z,M,Q,ye){F[F.length]=Q?C(ye,B,"$1"):M||Z}),F},oe=function(K,W){var re=K,F;if(E(v,re)&&(F=v[re],re="%"+F[0]+"%"),E(m,re)){var Z=m[re];if(Z===b&&(Z=S(re)),typeof Z>"u"&&!W)throw new o("intrinsic "+K+" exists, but is not available. Please file an issue!");return{alias:F,name:re,value:Z}}throw new n("intrinsic "+K+" does not exist!")};return Rr=function(K,W){if(typeof K!="string"||K.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new o('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,K)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var re=U(K),F=re.length>0?re[0]:"",Z=oe("%"+F+"%",W),M=Z.name,Q=Z.value,ye=!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 N=re[we],ne=j(N,0,1),z=j(N,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)throw new n("property names with quotes must have matching quotes");if((N==="constructor"||!G)&&(ye=!0),F+="."+N,M="%"+F+"%",E(m,M))Q=m[M];else if(Q!=null){if(!(N in Q)){if(!W)throw new o("base intrinsic for "+K+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var Y=u(Q,N);G=!!Y,G&&"get"in Y&&!("originalValue"in Y.get)?Q=Y.get:Q=Q[N]}else G=E(Q,N),Q=Q[N];G&&!ye&&(m[M]=Q)}}return Q},Rr}function Ti(){if(Qi)return Nr;Qi=!0;var i=Vt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Nr=e,Nr}function $s(){if(Xi)return jr;Xi=!0;var i=Vt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return jr=e,jr}function fd(){if(Zi)return Ur;Zi=!0;var i=Ti(),e=Fs(),t=sr(),r=$s();return Ur=function(s,n,o){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 a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(s,n);if(i)i(s,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:o,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)s[n]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Ur}function pd(){if(eo)return Br;eo=!0;var i=Ti(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Br=e,Br}function md(){if(to)return Dr;to=!0;var i=Vt(),e=fd(),t=pd()(),r=$s(),s=sr(),n=i("%Math.floor%");return Dr=function(o,a){if(typeof o!="function")throw new s("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in o&&r){var d=r(o,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(o,"length",a,!0,!0):e(o,"length",a)),o},Dr}function gd(){if(ro)return Kt;ro=!0;var i=Ii(),e=Vt(),t=md(),r=sr(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||i.call(n,s),a=Ti(),l=e("%Math.max%");Kt=function(u){if(typeof u!="function")throw new r("a function is required");var d=o(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return o(i,s,arguments)};return a?a(Kt,"apply",{value:c}):Kt.apply=c,Kt}function yd(){if(no)return Fr;no=!0;var i=Vt(),e=gd(),t=e(i("String.prototype.indexOf"));return Fr=function(r,s){var n=i(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Fr}var Ci,Pi,Oi,Mi,Li,Ri,Ni,ji,Ui,Bi,Di,Fi,$i,qi,Hi,Wi,Cr,zi,Pr,Vi,Or,Ki,Mr,Gi,Lr,Yi,Rr,Ji,Nr,Qi,jr,Xi,Ur,Zi,Br,eo,Dr,to,Kt,ro,Fr,no,bd=Ye(()=>{le(),ue(),ce(),Ci={},Pi=!1,Oi={},Mi=!1,Li={},Ri=!1,Ni={},ji=!1,Ui={},Bi=!1,Di={},Fi=!1,$i={},qi=!1,Hi={},Wi=!1,Cr={},zi=!1,Pr={},Vi=!1,Or={},Ki=!1,Mr={},Gi=!1,Lr={},Yi=!1,Rr={},Ji=!1,Nr={},Qi=!1,jr={},Xi=!1,Ur={},Zi=!1,Br={},eo=!1,Dr={},to=!1,Kt={},ro=!1,Fr={},no=!1});function io(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function vd(){!jt||!Ut||(jt=!1,Ut.length?rt=Ut.concat(rt):ar=-1,rt.length&&qs())}function qs(){if(!jt){var i=setTimeout(vd,0);jt=!0;for(var e=rt.length;e;){for(Ut=rt,rt=[];++ar<e;)Ut&&Ut[ar].run();ar=-1,e=rt.length}Ut=null,jt=!1,clearTimeout(i)}}function wd(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];rt.push(new Hs(i,e)),rt.length===1&&!jt&&setTimeout(qs,0)}function Hs(i,e){this.fun=i,this.array=e}function We(){}function kd(i){io("_linkedBinding")}function _d(i){io("dlopen")}function Sd(){return[]}function xd(){return[]}function Ed(i,e){if(!i)throw new Error(e||"assertion error")}function Ad(){return!1}function Id(){return bt.now()/1e3}function oo(i){var e=Math.floor((Date.now()-bt.now())*.001),t=bt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=qr)),[r,s]}function Et(){return ao}function Td(i){return[]}var rt,jt,Ut,ar,Ws,zs,Vs,Ks,Gs,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,$r,da,ha,fa,pa,ma,ga,ya,ba,va,wa,ka,_a,Sa,xa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,Ma,La,Ra,Na,bt,so,qr,ja,Ua,Ba,Da,Fa,$a,qa,Ha,Wa,za,Va,ao,Ka=Ye(()=>{le(),ue(),ce(),rt=[],jt=!1,ar=-1,Hs.prototype.run=function(){this.fun.apply(null,this.array)},Ws="browser",zs="x64",Vs="browser",Ks={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Gs=["/usr/bin/node"],Ys=[],Js="v16.8.0",Qs={},Xs=function(i,e){console.warn((e?e+": ":"")+i)},Zs=function(i){io("binding")},ea=function(i){return 0},ta=function(){return"/"},ra=function(i){},na={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ia=We,oa=[],sa={},aa=!1,la={},ca=We,ua=We,$r=function(){return{}},da=$r,ha=$r,fa=We,pa=We,ma=We,ga={},ya={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ba=We,va=We,wa=We,ka=We,_a=We,Sa=We,xa=We,Ea=void 0,Aa=void 0,Ia=void 0,Ta=We,Ca=2,Pa=1,Oa="/bin/usr/node",Ma=9229,La="node",Ra=[],Na=We,bt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},bt.now===void 0&&(so=Date.now(),bt.timing&&bt.timing.navigationStart&&(so=bt.timing.navigationStart),bt.now=()=>Date.now()-so),qr=1e9,oo.bigint=function(i){var e=oo(i);return typeof BigInt>"u"?e[0]*qr+e[1]:BigInt(e[0]*qr)+BigInt(e[1])},ja=10,Ua={},Ba=0,Da=Et,Fa=Et,$a=Et,qa=Et,Ha=Et,Wa=We,za=Et,Va=Et,ao={version:Js,versions:Qs,arch:zs,platform:Vs,release:na,_rawDebug:ia,moduleLoadList:oa,binding:Zs,_linkedBinding:kd,_events:Ua,_eventsCount:Ba,_maxListeners:ja,on:Et,addListener:Da,once:Fa,off:$a,removeListener:qa,removeAllListeners:Ha,emit:Wa,prependListener:za,prependOnceListener:Va,listeners:Td,domain:sa,_exiting:aa,config:la,dlopen:_d,uptime:Id,_getActiveRequests:Sd,_getActiveHandles:xd,reallyExit:ca,_kill:ua,cpuUsage:$r,resourceUsage:da,memoryUsage:ha,kill:fa,exit:pa,openStdin:ma,allowedNodeEnvironmentFlags:ga,assert:Ed,features:ya,_fatalExceptions:ba,setUncaughtExceptionCaptureCallback:va,hasUncaughtExceptionCaptureCallback:Ad,emitWarning:Xs,nextTick:wd,_tickCallback:wa,_debugProcess:ka,_debugEnd:_a,_startProfilerIdleNotifier:Sa,_stopProfilerIdleNotifier:xa,stdout:Ea,stdin:Ia,stderr:Aa,abort:Ta,umask:ea,chdir:ra,cwd:ta,env:Ks,title:Ws,argv:Gs,execArgv:Ys,pid:Ca,ppid:Pa,execPath:Oa,debugPort:Ma,hrtime:oo,argv0:La,_preload_modules:Ra,setSourceMapsEnabled:Na}});function Cd(){if(lo)return Hr;lo=!0;var i=ao;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,o){for(var a="",l=0,c=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}o&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,o){var a=o.dir||o.root,l=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+l:a+n+l:l}var s={resolve:function(){for(var n="",o=!1,a,l=arguments.length-1;l>=-1&&!o;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,o=c.charCodeAt(0)===47)}return n=t(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var o=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!o),n.length===0&&!o&&(n="."),n.length>0&&a&&(n+="/"),o?"/"+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,o=0;o<arguments.length;++o){var a=arguments[o];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":s.normalize(n)},relative:function(n,o){if(e(n),e(o),n===o||(n=s.resolve(n),o=s.resolve(o),n===o))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<o.length&&o.charCodeAt(u)===47;++u);for(var d=o.length,p=d-u,g=c<p?c:p,f=-1,y=0;y<=g;++y){if(y===g){if(p>g){if(o.charCodeAt(u+y)===47)return o.slice(u+y+1);if(y===0)return o.slice(u+y)}else c>g&&(n.charCodeAt(a+y)===47?f=y:y===0&&(f=0));break}var b=n.charCodeAt(a+y),w=o.charCodeAt(u+y);if(b!==w)break;b===47&&(f=y)}var m="";for(y=a+f+1;y<=l;++y)(y===l||n.charCodeAt(y)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+o.slice(u+f):(u+=f,o.charCodeAt(u)===47&&++u,o.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var o=n.charCodeAt(0),a=o===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(o=n.charCodeAt(u),o===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(o!==void 0&&o.length>0&&o.length<=n.length){if(o.length===n.length&&o===n)return"";var d=o.length-1,p=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(g===o.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var o=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===46?o===-1?o=d:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||l===-1||u===0||u===1&&o===l-1&&o===a+1?"":n.slice(o,l)},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 o={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return o;var a=n.charCodeAt(0),l=a===47,c;l?(o.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,f=n.length-1,y=0;f>=c;--f){if(a=n.charCodeAt(f),a===47){if(!g){d=f+1;break}continue}p===-1&&(g=!1,p=f+1),a===46?u===-1?u=f:y!==1&&(y=1):u!==-1&&(y=-1)}return u===-1||p===-1||y===0||y===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?o.base=o.name=n.slice(1,p):o.base=o.name=n.slice(d,p)):(d===0&&l?(o.name=n.slice(1,u),o.base=n.slice(1,p)):(o.name=n.slice(d,u),o.base=n.slice(d,p)),o.ext=n.slice(u,p)),d>0?o.dir=n.slice(0,d-1):l&&(o.dir="/"),o},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,Hr=s,Hr}var Hr,lo,co,Pd=Ye(()=>{le(),ue(),ce(),Ka(),Hr={},lo=!1,co=Cd()}),Ga={};$t(Ga,{URL:()=>ol,Url:()=>el,default:()=>ze,fileURLToPath:()=>Ja,format:()=>tl,parse:()=>il,pathToFileURL:()=>Qa,resolve:()=>rl,resolveObject:()=>nl});function Od(){if(ho)return Wr;ho=!0;var i=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=i&&e&&typeof e.get=="function"?e.get:null,r=i&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=s&&n&&typeof n.get=="function"?n.get:null,a=s&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,y=Object.prototype.toString,b=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,S=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,O=Array.prototype.slice,C=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,B=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===B||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,K=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(V){return V.__proto__}:null);function W(V,ie){if(V===1/0||V===-1/0||V!==V||V&&V>-1e3&&V<1e3||x.call(/e/,ie))return ie;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof V=="number"){var Te=V<0?-C(-V):C(V);if(Te!==V){var Pe=String(Te),Le=m.call(ie,Pe.length+1);return k.call(Pe,Ie,"$&_")+"."+k.call(k.call(Le,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ie,"$&_")}var re=Xa,F=re.custom,Z=Y(F)?F:null;Wr=function V(ie,Ie,Te,Pe){var Le=Ie||{};if(se(Le,"quoteStyle")&&Le.quoteStyle!=="single"&&Le.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Le,"maxStringLength")&&(typeof Le.maxStringLength=="number"?Le.maxStringLength<0&&Le.maxStringLength!==1/0:Le.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var it=se(Le,"customInspect")?Le.customInspect:!0;if(typeof it!="boolean"&&it!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Le,"indent")&&Le.indent!==null&&Le.indent!==" "&&!(parseInt(Le.indent,10)===Le.indent&&Le.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Le,"numericSeparator")&&typeof Le.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ot=Le.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 ae(ie,Le);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ve=String(ie);return ot?W(ie,Ve):Ve}if(typeof ie=="bigint"){var st=String(ie)+"n";return ot?W(ie,st):st}var Xt=typeof Le.depth>"u"?5:Le.depth;if(typeof Te>"u"&&(Te=0),Te>=Xt&&Xt>0&&typeof ie=="object")return ye(ie)?"[Array]":"[Object]";var at=X(Le,Te);if(typeof Pe>"u")Pe=[];else if(ee(Pe,ie)>=0)return"[Circular]";function Ze(lt,Pt,Ft){if(Pt&&(Pe=O.call(Pe),Pe.push(Pt)),Ft){var ct={depth:Le.depth};return se(Le,"quoteStyle")&&(ct.quoteStyle=Le.quoteStyle),V(lt,ct,Te+1,Pe)}return V(lt,Le,Te+1,Pe)}if(typeof ie=="function"&&!we(ie)){var on=q(ie),Zt=_e(ie,Ze);return"[Function"+(on?": "+on:" (anonymous)")+"]"+(Zt.length>0?" { "+I.call(Zt,", ")+" }":"")}if(Y(ie)){var hr=B?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):$.call(ie);return typeof ie=="object"&&!B?h(hr):hr}if(ve(ie)){for(var P="<"+v.call(String(ie.nodeName)),R=ie.attributes||[],ke=0;ke<R.length;ke++)P+=" "+R[ke].name+"="+M(Q(R[ke].value),"double",Le);return P+=">",ie.childNodes&&ie.childNodes.length&&(P+="..."),P+="</"+v.call(String(ie.nodeName))+">",P}if(ye(ie)){if(ie.length===0)return"[]";var xe=_e(ie,Ze);return at&&!D(xe)?"["+de(xe,at)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Ae=_e(ie,Ze);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+Ze(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&&it){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Xt-Te});if(it!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(lt,Pt){Fe.push(Ze(Pt,ie,!0)+" => "+Ze(lt,ie))}),A("Map",t.call(ie),Fe,at)}if(H(ie)){var Ge=[];return a&&a.call(ie,function(lt){Ge.push(Ze(lt,ie))}),A("Set",o.call(ie),Ge,at)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(be(ie))return _("WeakRef");if(ne(ie))return h(Ze(Number(ie)));if(J(ie))return h(Ze(j.call(ie)));if(z(ie))return h(f.call(ie));if(N(ie))return h(Ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof zr<"u"&&ie===zr)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var et=_e(ie,Ze),fr=K?K(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,pr=ie instanceof Object?"":"null prototype",mr=!fr&&U&&Object(ie)===ie&&U in ie?m.call(L(ie),8,-1):pr?"Object":"",sn=fr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Dt=sn+(mr||pr?"["+I.call(E.call([],mr||[],pr||[]),": ")+"] ":"");return et.length===0?Dt+"{}":at?Dt+"{"+de(et,at)+"}":Dt+"{ "+I.call(et,", ")+" }"}return String(ie)};function M(V,ie,Ie){var Te=(Ie.quoteStyle||ie)==="double"?'"':"'";return Te+V+Te}function Q(V){return k.call(String(V),/"/g,"&quot;")}function ye(V){return L(V)==="[object Array]"&&(!U||!(typeof V=="object"&&U in V))}function te(V){return L(V)==="[object Date]"&&(!U||!(typeof V=="object"&&U in V))}function we(V){return L(V)==="[object RegExp]"&&(!U||!(typeof V=="object"&&U in V))}function G(V){return L(V)==="[object Error]"&&(!U||!(typeof V=="object"&&U in V))}function N(V){return L(V)==="[object String]"&&(!U||!(typeof V=="object"&&U in V))}function ne(V){return L(V)==="[object Number]"&&(!U||!(typeof V=="object"&&U in V))}function z(V){return L(V)==="[object Boolean]"&&(!U||!(typeof V=="object"&&U in V))}function Y(V){if(B)return V&&typeof V=="object"&&V instanceof Symbol;if(typeof V=="symbol")return!0;if(!V||typeof V!="object"||!$)return!1;try{return $.call(V),!0}catch{}return!1}function J(V){if(!V||typeof V!="object"||!j)return!1;try{return j.call(V),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(V){return V in(this||zr)};function se(V,ie){return ge.call(V,ie)}function L(V){return y.call(V)}function q(V){if(V.name)return V.name;var ie=w.call(b.call(V),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(V,ie){if(V.indexOf)return V.indexOf(ie);for(var Ie=0,Te=V.length;Ie<Te;Ie++)if(V[Ie]===ie)return Ie;return-1}function he(V){if(!t||!V||typeof V!="object")return!1;try{t.call(V);try{o.call(V)}catch{return!0}return V instanceof Map}catch{}return!1}function fe(V){if(!c||!V||typeof V!="object")return!1;try{c.call(V,c);try{d.call(V,d)}catch{return!0}return V instanceof WeakMap}catch{}return!1}function be(V){if(!g||!V||typeof V!="object")return!1;try{return g.call(V),!0}catch{}return!1}function H(V){if(!o||!V||typeof V!="object")return!1;try{o.call(V);try{t.call(V)}catch{return!0}return V instanceof Set}catch{}return!1}function me(V){if(!d||!V||typeof V!="object")return!1;try{d.call(V,d);try{c.call(V,c)}catch{return!0}return V instanceof WeakSet}catch{}return!1}function ve(V){return!V||typeof V!="object"?!1:typeof HTMLElement<"u"&&V instanceof HTMLElement?!0:typeof V.nodeName=="string"&&typeof V.getAttribute=="function"}function ae(V,ie){if(V.length>ie.maxStringLength){var Ie=V.length-ie.maxStringLength,Te="... "+Ie+" more character"+(Ie>1?"s":"");return ae(m.call(V,0,ie.maxStringLength),ie)+Te}var Pe=k.call(k.call(V,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return M(Pe,"single",ie)}function Oe(V){var ie=V.charCodeAt(0),Ie={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ie?"\\"+Ie:"\\x"+(ie<16?"0":"")+S.call(ie.toString(16))}function h(V){return"Object("+V+")"}function _(V){return V+" { ? }"}function A(V,ie,Ie,Te){var Pe=Te?de(Ie,Te):I.call(Ie,", ");return V+" ("+ie+") {"+Pe+"}"}function D(V){for(var ie=0;ie<V.length;ie++)if(ee(V[ie],`
4
+ `)>=0)return!1;return!0}function X(V,ie){var Ie;if(V.indent===" ")Ie=" ";else if(typeof V.indent=="number"&&V.indent>0)Ie=I.call(Array(V.indent+1)," ");else return null;return{base:Ie,prev:I.call(Array(ie+1),Ie)}}function de(V,ie){if(V.length===0)return"";var Ie=`
5
+ `+ie.prev+ie.base;return Ie+I.call(V,","+Ie)+`
6
+ `+ie.prev}function _e(V,ie){var Ie=ye(V),Te=[];if(Ie){Te.length=V.length;for(var Pe=0;Pe<V.length;Pe++)Te[Pe]=se(V,Pe)?ie(V[Pe],V):""}var Le=typeof T=="function"?T(V):[],it;if(B){it={};for(var ot=0;ot<Le.length;ot++)it["$"+Le[ot]]=Le[ot]}for(var Ve in V)se(V,Ve)&&(Ie&&String(Number(Ve))===Ve&&Ve<V.length||B&&it["$"+Ve]instanceof Symbol||(x.call(/[^\w$]/,Ve)?Te.push(ie(Ve,V)+": "+ie(V[Ve],V)):Te.push(Ve+": "+ie(V[Ve],V))));if(typeof T=="function")for(var st=0;st<Le.length;st++)oe.call(V,Le[st])&&Te.push("["+ie(Le[st])+"]: "+ie(V[Le[st]],V));return Te}return Wr}function Md(){if(fo)return Vr;fo=!0;var i=Vt(),e=yd(),t=Od(),r=sr(),s=i("%WeakMap%",!0),n=i("%Map%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,w){for(var m=b,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=b.next,b.next=k,k},g=function(b,w){var m=p(b,w);return m&&m.value},f=function(b,w,m){var k=p(b,w);k?k.value=m:b.next={key:w,next:b.next,value:m}},y=function(b,w){return!!p(b,w)};return Vr=function(){var b,w,m,k={assert:function(S){if(!k.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(b)return o(b,S)}else if(n){if(w)return c(w,S)}else if(m)return g(m,S)},has:function(S){if(s&&S&&(typeof S=="object"||typeof S=="function")){if(b)return l(b,S)}else if(n){if(w)return d(w,S)}else if(m)return y(m,S);return!1},set:function(S,v){s&&S&&(typeof S=="object"||typeof S=="function")?(b||(b=new s),a(b,S,v)):n?(w||(w=new n),u(w,S,v)):(m||(m={key:{},next:null}),f(m,S,v))}};return k},Vr}function uo(){if(po)return Kr;po=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Kr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Kr}function Ya(){if(mo)return Gr;mo=!0;var i=uo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],w=0;w<256;++w)b.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return b})(),s=function(b){for(;b.length>1;){var w=b.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],S=0;S<m.length;++S)typeof m[S]<"u"&&k.push(m[S]);w.obj[w.prop]=k}}},n=function(b,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<b.length;++k)typeof b[k]<"u"&&(m[k]=b[k]);return m},o=function b(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var S=w;return t(w)&&!t(m)&&(S=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,x){if(e.call(w,x)){var E=w[x];E&&typeof E=="object"&&v&&typeof v=="object"?w[x]=b(E,v,k):w.push(v)}else w[x]=v}),w):Object.keys(m).reduce(function(v,x){var E=m[x];return e.call(v,x)?v[x]=b(v[x],E,k):v[x]=E,v},S)},a=function(b,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},b)},l=function(b,w,m){var k=b.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(b,w,m,k,S){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",E=0;E<v.length;E+=c){for(var I=v.length>=c?v.slice(E,E+c):v,O=[],C=0;C<I.length;++C){var j=I.charCodeAt(C);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||S===i.RFC1738&&(j===40||j===41)){O[O.length]=I.charAt(C);continue}if(j<128){O[O.length]=r[j];continue}if(j<2048){O[O.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){O[O.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}C+=1,j=65536+((j&1023)<<10|I.charCodeAt(C)&1023),O[O.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}x+=O.join("")}return x},d=function(b){for(var w=[{obj:{o:b},prop:"o"}],m=[],k=0;k<w.length;++k)for(var S=w[k],v=S.obj[S.prop],x=Object.keys(v),E=0;E<x.length;++E){var I=x[E],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return s(w),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},g=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,w){return[].concat(b,w)},y=function(b,w){if(t(b)){for(var m=[],k=0;k<b.length;k+=1)m.push(w(b[k]));return m}return w(b)};return Gr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:y,merge:o},Gr}function Ld(){if(go)return Yr;go=!0;var i=Md(),e=Ya(),t=uo(),r=Object.prototype.hasOwnProperty,s={brackets:function(y){return y+"[]"},comma:"comma",indices:function(y,b){return y+"["+b+"]"},repeat:function(y){return y}},n=Array.isArray,o=Array.prototype.push,a=function(y,b){o.apply(y,n(b)?b:[b])},l=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(y){return l.call(y)},skipNulls:!1,strictNullHandling:!1},d=function(y){return typeof y=="string"||typeof y=="number"||typeof y=="boolean"||typeof y=="symbol"||typeof y=="bigint"},p={},g=function y(b,w,m,k,S,v,x,E,I,O,C,j,T,$,B,U,oe,K){for(var W=b,re=K,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"?W=O(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(L){return L instanceof Date?T(L):L})),W===null){if(v)return I&&!U?I(w,u.encoder,oe,"key",$):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var Q=U?w:I(w,u.encoder,oe,"key",$);return[B(Q)+"="+B(I(W,u.encoder,oe,"value",$))]}return[B(w)+"="+B(String(W))]}var ye=[];if(typeof W>"u")return ye;var te;if(m==="comma"&&n(W))U&&I&&(W=e.maybeMap(W,I)),te=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(O))te=O;else{var we=Object.keys(W);te=C?we.sort(C):we}var G=E?w.replace(/\./g,"%2E"):w,N=k&&n(W)&&W.length===1?G+"[]":G;if(S&&n(W)&&W.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var z=te[ne],Y=typeof z=="object"&&typeof z.value<"u"?z.value:W[z];if(!(x&&Y===null)){var J=j&&E?z.replace(/\./g,"%2E"):z,ge=n(W)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");K.set(b,F);var se=i();se.set(p,K),a(ye,y(Y,ge,m,k,S,v,x,E,m==="comma"&&U&&n(W)?null:I,O,C,j,T,$,B,U,oe,se))}}return ye},f=function(y){if(!y)return u;if(typeof y.allowEmptyArrays<"u"&&typeof y.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof y.encodeDotInKeys<"u"&&typeof y.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(y.encoder!==null&&typeof y.encoder<"u"&&typeof y.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=y.charset||u.charset;if(typeof y.charset<"u"&&y.charset!=="utf-8"&&y.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof y.format<"u"){if(!r.call(t.formatters,y.format))throw new TypeError("Unknown format option provided.");w=y.format}var m=t.formatters[w],k=u.filter;(typeof y.filter=="function"||n(y.filter))&&(k=y.filter);var S;if(y.arrayFormat in s?S=y.arrayFormat:"indices"in y?S=y.indices?"indices":"repeat":S=u.arrayFormat,"commaRoundTrip"in y&&typeof y.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof y.allowDots>"u"?y.encodeDotInKeys===!0?!0:u.allowDots:!!y.allowDots;return{addQueryPrefix:typeof y.addQueryPrefix=="boolean"?y.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof y.allowEmptyArrays=="boolean"?!!y.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:S,charset:b,charsetSentinel:typeof y.charsetSentinel=="boolean"?y.charsetSentinel:u.charsetSentinel,commaRoundTrip:y.commaRoundTrip,delimiter:typeof y.delimiter>"u"?u.delimiter:y.delimiter,encode:typeof y.encode=="boolean"?y.encode:u.encode,encodeDotInKeys:typeof y.encodeDotInKeys=="boolean"?y.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof y.encoder=="function"?y.encoder:u.encoder,encodeValuesOnly:typeof y.encodeValuesOnly=="boolean"?y.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof y.serializeDate=="function"?y.serializeDate:u.serializeDate,skipNulls:typeof y.skipNulls=="boolean"?y.skipNulls:u.skipNulls,sort:typeof y.sort=="function"?y.sort:null,strictNullHandling:typeof y.strictNullHandling=="boolean"?y.strictNullHandling:u.strictNullHandling}};return Yr=function(y,b){var w=y,m=f(b),k,S;typeof m.filter=="function"?(S=m.filter,w=S("",w)):n(m.filter)&&(S=m.filter,k=S);var v=[];if(typeof w!="object"||w===null)return"";var x=s[m.arrayFormat],E=x==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=i(),O=0;O<k.length;++O){var C=k[O];m.skipNulls&&w[C]===null||a(v,g(w[C],C,x,E,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 j=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&"),j.length>0?T+j:""},Yr}function Rd(){if(yo)return Jr;yo=!0;var i=Ya(),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:i.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(g,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var f={__proto__:null},y=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;y=y.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=g.parameterLimit===1/0?void 0:g.parameterLimit,w=y.split(g.delimiter,b),m=-1,k,S=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?S="utf-8":w[k]===o&&(S="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],x=v.indexOf("]="),E=x===-1?v.indexOf("="):x+1,I,O;E===-1?(I=g.decoder(v,r.decoder,S,"key"),O=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,S,"key"),O=i.maybeMap(n(v.slice(E+1),g),function(j){return g.decoder(j,r.decoder,S,"value")})),O&&g.interpretNumericEntities&&S==="iso-8859-1"&&(O=s(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var C=e.call(f,I);C&&g.duplicates==="combine"?f[I]=i.combine(f[I],O):(!C||g.duplicates==="last")&&(f[I]=O)}return f},c=function(p,g,f,y){for(var b=y?g:n(g,f),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var S=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=f.decodeDotInKeys?S.replace(/%2E/g,"."):S,x=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(x)&&k!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,g,f,y){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=f.depth>0&&w.exec(b),S=k?b.slice(0,k.index):b,v=[];if(S){if(!f.plainObjects&&e.call(Object.prototype,S)&&!f.allowPrototypes)return;v.push(S)}for(var x=0;f.depth>0&&(k=m.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(k[1])}if(k){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(k.index)+"]")}return c(v,g,f,y)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=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 y=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:y,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:g,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"||i.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 Jr=function(p,g){var f=d(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var y=typeof p=="string"?l(p,f):p,b=f.plainObjects?Object.create(null):{},w=Object.keys(y),m=0;m<w.length;++m){var k=w[m],S=u(k,y[k],f,typeof p=="string");b=i.merge(b,S,f)}return f.allowSparse===!0?b:i.compact(b)},Jr}function Nd(){if(bo)return Qr;bo=!0;var i=Ld(),e=Rd(),t=uo();return Qr={formats:t,parse:e,stringify:i},Qr}function jd(){if(vo)return At;vo=!0;var i=xt;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
+ `," "],o=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(o),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Nd();function w(v,x,E){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,x,E),I}e.prototype.parse=function(v,x,E){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",C=v.split(O),j=/\\/g;C[0]=C[0].replace(j,"/"),v=C.join(O);var T=v;if(T=T.trim(),!E&&v.split("#").length===1){var $=s.exec(T);if($)return this.path=T,this.href=T,this.pathname=$[1],$[2]?(this.search=$[2],x?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var B=t.exec(T);if(B){B=B[0];var U=B.toLowerCase();this.protocol=U,T=T.substr(B.length)}if(E||B||T.match(/^\/\/[^@/]+@[^@/]+/)){var oe=T.substr(0,2)==="//";oe&&!(B&&f[B])&&(T=T.substr(2),this.slashes=!0)}if(!f[B]&&(oe||B&&!y[B])){for(var K=-1,W=0;W<c.length;W++){var re=T.indexOf(c[W]);re!==-1&&(K===-1||re<K)&&(K=re)}var F,Z;K===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",K),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),K=-1;for(var W=0;W<l.length;W++){var re=T.indexOf(l[W]);re!==-1&&(K===-1||re<K)&&(K=re)}K===-1&&(K=T.length),this.host=T.slice(0,K),T=T.slice(K),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),W=0,ye=Q.length;W<ye;W++){var te=Q[W];if(te&&!te.match(d)){for(var we="",G=0,N=te.length;G<N;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(d)){var ne=Q.slice(0,W),z=Q.slice(W+1),Y=te.match(p);Y&&(ne.push(Y[1]),z.unshift(Y[2])),z.length&&(T="/"+z.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=i.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var W=0,ye=a.length;W<ye;W++){var se=a[W];if(T.indexOf(se)!==-1){var L=encodeURIComponent(se);L===se&&(L=escape(se)),T=T.split(se).join(L)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),x&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):x&&(this.search="",this.query={}),T&&(this.pathname=T),y[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",he=this.search||"";this.path=J+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var x=this.protocol||"",E=this.pathname||"",I=this.hash||"",O=!1,C="";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&&(C=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||C&&"?"+C||"";return x&&x.substr(-1)!==":"&&(x+=":"),this.slashes||(!x||y[x])&&O!==!1?(O="//"+(O||""),E&&E.charAt(0)!=="/"&&(E="/"+E)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),x+O+E+j+I};function k(v,x){return w(v,!1,!0).resolve(x)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function S(v,x){return v?w(v,!1,!0).resolveObject(x):x}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var x=new e;x.parse(v,!1,!0),v=x}for(var E=new e,I=Object.keys(this),O=0;O<I.length;O++){var C=I[O];E[C]=this[C]}if(E.hash=v.hash,v.href==="")return E.href=E.format(),E;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var $=j[T];$!=="protocol"&&(E[$]=v[$])}return y[E.protocol]&&E.hostname&&!E.pathname&&(E.pathname="/",E.path=E.pathname),E.href=E.format(),E}if(v.protocol&&v.protocol!==E.protocol){if(!y[v.protocol]){for(var B=Object.keys(v),U=0;U<B.length;U++){var oe=B[U];E[oe]=v[oe]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var ye=(v.pathname||"").split("/");ye.length&&!(v.host=ye.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),ye[0]!==""&&ye.unshift(""),ye.length<2&&ye.unshift(""),E.pathname=ye.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var K=E.pathname||"",W=E.search||"";E.path=K+W}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var re=E.pathname&&E.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||E.host&&v.pathname,M=Z,Q=E.pathname&&E.pathname.split("/")||[],ye=v.pathname&&v.pathname.split("/")||[],te=E.protocol&&!y[E.protocol];if(te&&(E.hostname="",E.port=null,E.host&&(Q[0]===""?Q[0]=E.host:Q.unshift(E.host)),E.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(ye[0]===""?ye[0]=v.host:ye.unshift(v.host)),v.host=null),Z=Z&&(ye[0]===""||Q[0]==="")),F)E.host=v.host||v.host===""?v.host:E.host,E.hostname=v.hostname||v.hostname===""?v.hostname:E.hostname,E.search=v.search,E.query=v.query,Q=ye;else if(ye.length)Q||(Q=[]),Q.pop(),Q=Q.concat(ye),E.search=v.search,E.query=v.query;else if(v.search!=null){if(te){E.host=Q.shift(),E.hostname=E.host;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return E.search=v.search,E.query=v.query,(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E}if(!Q.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var G=Q.slice(-1)[0],N=(E.host||v.host||Q.length>1)&&(G==="."||G==="..")||G==="",ne=0,z=Q.length;z>=0;z--)G=Q[z],G==="."?Q.splice(z,1):G===".."?(Q.splice(z,1),ne++):ne&&(Q.splice(z,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var Y=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){E.hostname=Y?"":Q.length?Q.shift():"",E.host=E.hostname;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return Z=Z||E.host&&Q.length,Z&&!Y&&Q.unshift(""),Q.length>0?E.pathname=Q.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,x=r.exec(v);x&&(x=x[0],x!==":"&&(this.port=x.substr(1)),v=v.substr(0,v.length-x.length)),v&&(this.hostname=v)},At.parse=w,At.resolve=k,At.resolveObject=S,At.format=m,At.Url=e,At}function Ja(i){if(typeof i=="string")i=new URL(i);else if(!(i instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(i.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Xr?Ud(i):Bd(i)}function Ud(i){let e=i.hostname,t=i.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(ul,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,s=t[2];if(r<ll||r>cl||s!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Bd(i){if(i.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=i.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 Qa(i){let e=co.resolve(i),t=i.charCodeAt(i.length-1);(t===al||Xr&&t===sl)&&e[e.length-1]!==co.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(dl,"%25")),!Xr&&e.includes("\\")&&(e=e.replace(hl,"%5C")),e.includes(`
8
+ `)&&(e=e.replace(fl,"%0A")),e.includes("\r")&&(e=e.replace(pl,"%0D")),e.includes(" ")&&(e=e.replace(ml,"%09")),r.pathname=e,r}var Xa,Wr,ho,zr,Vr,fo,Kr,po,Gr,mo,Yr,go,Jr,yo,Qr,bo,At,vo,ze,Za,el,tl,rl,nl,il,ol,sl,al,ll,cl,Xr,ul,dl,hl,fl,pl,ml,Dd=Ye(()=>{le(),ue(),ce(),rd(),bd(),Pd(),Ka(),Xa=Object.freeze(Object.create(null)),Wr={},ho=!1,zr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Vr={},fo=!1,Kr={},po=!1,Gr={},mo=!1,Yr={},go=!1,Jr={},yo=!1,Qr={},bo=!1,At={},vo=!1,ze=jd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Za=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Qa,ze.fileURLToPath=Ja,el=ze.Url,tl=ze.format,rl=ze.resolve,nl=ze.resolveObject,il=ze.parse,ol=ze.URL,sl=92,al=47,ll=97,cl=122,Xr=Za==="win32",ul=/\//g,dl=/%/g,hl=/\\/g,fl=/\n/g,pl=/\r/g,ml=/\t/g}),Fd=pe((i,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")}}),wo=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=Nt(),t=(qe(),Ne($e));function r(n,o){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",o)}var s=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,a){super({objectMode:!0}),this.proxy=o,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,o,a){this.isSocketOpen?this.writeToProxy(n,o,a):this.writeQueue.push({chunk:n,encoding:o,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,a){this.proxy.write(n,o)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:a}=this.writeQueue.shift();this.writeToProxy(n,o,a)}}};i.BufferedDuplex=s}),Zr=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(i,"__esModule",{value:!0}),i.streamBuilder=i.browserStreamBuilder=void 0;var t=(qe(),Ne($e)),r=e(Fd()),s=e(mt()),n=Nt(),o=e(Ir()),a=wo(),l=(0,s.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!o.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function p(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let S=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${S}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[S],k):v=new r.default(m,[S],k.wsOptions),v}function f(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",S=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(S,[k],m):v=new WebSocket(S,[k]),v.binaryType="arraybuffer",v}var y=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let S=u(k,w),v=g(w,S,k),x=r.default.createWebSocketStream(v,k.wsOptions);return x.url=S,v.on("close",()=>{x.destroy()}),x};i.streamBuilder=y;var b=(w,m)=>{l("browserStreamBuilder");let k,S=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,E=f(w,m),I=C(m,U,oe);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{E.close()});let O=typeof E.addEventListener<"u";E.readyState===E.OPEN?(k=I,k.socket=E):(k=new a.BufferedDuplex(m,I,E),O?E.addEventListener("open",j):E.onopen=j),O?(E.addEventListener("close",T),E.addEventListener("error",$),E.addEventListener("message",B)):(E.onclose=T,E.onerror=$,E.onmessage=B);function C(K,W,re){let F=new n.Transform({objectMode:K.objectMode});return F._write=W,F._flush=re,F}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(K){l("WebSocket onClose",K),k.end(),k.destroy()}function $(K){l("WebSocket onError",K);let W=new Error("WebSocket error");W.event=K,k.destroy(W)}async function B(K){if(!I||!I.readable||!I.writable)return;let{data:W}=K;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function U(K,W,re){if(E.bufferedAmount>S){setTimeout(U,v,K,W,re);return}x&&typeof K=="string"&&(K=t.Buffer.from(K,"utf8"));try{E.send(K)}catch(F){return re(F)}re()}function oe(K){E.close(),K()}return k};i.browserStreamBuilder=b}),ko={};$t(ko,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>gl,isIP:()=>Ue,isIPv4:()=>Ue,isIPv6:()=>Ue});function Ue(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var gl,yl=Ye(()=>{le(),ue(),ce(),gl={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),bl=pe((i,e)=>{le(),ue(),ce(),e.exports={}}),vl=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(i,"__esModule",{value:!0});var t=e((yl(),Ne(ko))),r=e(mt()),s=e(bl()),n=(0,r.default)("mqttjs:tcp"),o=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,s.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};i.default=o}),wl={};$t(wl,{default:()=>kl});var kl,$d=Ye(()=>{le(),ue(),ce(),kl={}}),_l=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(i,"__esModule",{value:!0});var t=($d(),Ne(wl)),r=e((yl(),Ne(ko))),s=e(mt()),n=e(bl()),o=(0,s.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var l=(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,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};i.default=l}),Sl=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Nt(),r=wo(),s,n,o;function a(){let p=new t.Transform;return p._write=(g,f,y)=>{s.send({data:g.buffer,success(){y()},fail(b){y(new Error(b))}})},p._flush=g=>{s.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",y=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(y=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(y=p.transformWsUrl(y,p,g)),y}function u(){s.onOpen(()=>{o.socketReady()}),s.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),s.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),s.onError(p=>{let g=new Error(p.errMsg);o.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let y=c(g,p);s=wx.connectSocket({url:y,protocols:[f]}),n=a(),o=new r.BufferedDuplex(g,n,s),o._destroy=(w,m)=>{s.close({success(){m&&m(w)}})};let b=o.destroy;return o.destroy=(w,m)=>(o.destroy=b,setTimeout(()=>{s.close({fail(){o._destroy(w,m)}})},0),o),u(),o};i.default=d}),xl=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Nt(),r=wo(),s,n,o,a=!1;function l(){let g=new t.Transform;return g._write=(f,y,b)=>{s.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},g._flush=f=>{s.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let y=g.protocol==="alis"?"wss":"ws",b=`${y}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(b=`${y}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(b=g.transformWsUrl(b,g,f)),b}function d(){a||(a=!0,s.onSocketOpen(()=>{o.socketReady()}),s.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.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(g.data)}}),s.onSocketClose(()=>{o.end(),o.destroy()}),s.onSocketError(g=>{o.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let y=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let b=u(f,g);return s=f.my,s.connectSocket({url:b,protocols:y}),n=l(),o=new r.BufferedDuplex(f,n,s),d(),o};i.default=p}),qd=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(i,"__esModule",{value:!0}),i.connectAsync=u;var t=e(mt()),r=e((Dd(),Ne(Ga))),s=e(Ei()),n=e(Ir());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;d.username=g,d.password=f}else d.username=d.auth}function c(d,p){if(o("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let y=r.default.parse(d,!0),b={};if(y.port!=null&&(b.port=Number(y.port)),b.host=y.hostname,b.query=y.query,b.auth=y.auth,b.protocol=y.protocol,b.path=y.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,l(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 je<"u"&&(p.socksProxy=je.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(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=Zr().streamBuilder,a.wss=Zr().streamBuilder,a.mqtt=vl().default,a.tcp=vl().default,a.ssl=_l().default,a.tls=a.ssl,a.mqtts=_l().default):(a.ws=Zr().browserStreamBuilder,a.wss=Zr().browserStreamBuilder,a.wx=Sl().default,a.wxs=Sl().default,a.ali=xl().default,a.alis=xl().default)),!a[p.protocol]){let y=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,w)=>y&&w%2===0?!1:typeof a[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(y){return p.servers&&((!y._reconnectCount||y._reconnectCount===p.servers.length)&&(y._reconnectCount=0),p.host=p.servers[y._reconnectCount].host,p.port=p.servers[y._reconnectCount].port,p.protocol=p.servers[y._reconnectCount].protocol?p.servers[y._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,y._reconnectCount++),o("calling streambuilder for",p.protocol),a[p.protocol](y,p)}let f=new s.default(g,p);return f.on("error",()=>{}),f}function u(d,p,g=!0){return new Promise((f,y)=>{let b=c(d,p),w={connect:k=>{m(),f(b)},end:()=>{m(),f(b)},error:k=>{m(),b.end(),y(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{b.off(k,w[k])})}Object.keys(w).forEach(k=>{b.on(k,w[k])})})}i.default=c}),El=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,f,y,b){b===void 0&&(b=y);var w=Object.getOwnPropertyDescriptor(f,y);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[y]}}),Object.defineProperty(g,b,w)}:function(g,f,y,b){b===void 0&&(b=y),g[b]=f[y]}),t=i&&i.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=i&&i.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(y){var b=[];for(var w in y)Object.prototype.hasOwnProperty.call(y,w)&&(b[b.length]=w);return b},g(f)};return function(f){if(f&&f.__esModule)return f;var y={};if(f!=null)for(var b=g(f),w=0;w<b.length;w++)b[w]!=="default"&&e(y,f,b[w]);return t(y,f),y}})(),s=i&&i.__exportStar||function(g,f){for(var y in g)y!=="default"&&!Object.prototype.hasOwnProperty.call(f,y)&&e(f,g,y)},n=i&&i.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=i.KeepaliveManager=i.UniqueMessageIdProvider=i.DefaultMessageIdProvider=i.Store=i.MqttClient=i.connectAsync=i.connect=i.Client=void 0;var o=n(Ei());i.MqttClient=o.default;var a=n(Ms());i.DefaultMessageIdProvider=a.default;var l=n(ed());i.UniqueMessageIdProvider=l.default;var c=n(Es());i.Store=c.default;var u=r(qd());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ds());i.KeepaliveManager=d.default,i.Client=o.default,s(Ei(),i),s(zt(),i),s(xs(),i);var p=Er();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Hd=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(o,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(o,c,u)}:function(o,a,l,c){c===void 0&&(c=l),o[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(o,a){Object.defineProperty(o,"default",{enumerable:!0,value:a})}:function(o,a){o.default=a}),r=i&&i.__importStar||(function(){var o=function(a){return o=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},o(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=o(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),s=i&&i.__exportStar||function(o,a){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,o,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(El());i.default=n,s(El(),i)});const Wd=Hd();const zd={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}/#"},Vd=300,Kd={templateId:"7",type:"link",isDeepLink:!0},Gd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Al{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={...zd,...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,o)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>o(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Wd.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.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={...Kd,...this.config.fileTemplate??{},...Yd(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??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Vd){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??"",d=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:d,raw:s};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(s,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),a=o?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof s.message_id=="string"?s.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,l))}buildOutgoingEnvelope(e,t){const r={...Gd,...this.config.messageDefaults??{}},s=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={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:o}}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 o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=o[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Yd(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function Il(i,e){return(i.sender??"").toString()===e}function Tl(i,e){const t=(i.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 _o(i){const e={raw:i},t=i.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 i.text=="string"&&i.text.trim().startsWith("{"))try{const s=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(s);typeof n.message=="string"&&(e.innerMessage=n.message);const o=n.metadata;o&&typeof o=="object"&&(typeof o.contentType=="string"&&(e.contentType=o.contentType),typeof o.templateId=="string"&&(e.templateId=o.templateId),o.payload!==void 0&&(e.payload=o.payload))}catch{}const r=i.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 Cl(i){const e=_o(i);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,o=n&&typeof n.url=="string"?n.url:void 0,a=typeof s.description=="string"?s.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!o&&!a?null:{fileName:a,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function Pl(i,e,t){const r=Tl(i,t),s=_o(i),n=Cl(i);let o="";s.innerMessage?o=s.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?s.contentType!=="300"&&(o=i.text):o=i.text);const a=typeof i.message_id=="string"?i.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof i.timestamp=="number"?new Date(i.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof i.status=="number"?Jd(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:o,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return s.contentType&&(d.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:s}}function Jd(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class Ol extends yr{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 Ho(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Wo,this.conversationManager=new Yo(e.conversationId),this.usesAikaara()&&(this.connection=new qo(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.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),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 Al({...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(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const s=r.map(l=>Pl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=s.map(l=>l.message),o=this.messageStore.messages,a=[...n,...o.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of s){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}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=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const s=t.conversationId??r;if(!s)return;const n=this.config.tiledeskIdentity?.userId??"",{message:o,template:a}=Pl(e,s,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&o.role==="assistant")return;if(Il(e,n)){const u=this.messageStore.reconcileOptimistic(o);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(o);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:s,role:o.role==="tool"?"system":o.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(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{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}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 Qd extends yr{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 Xd(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function Zd(i,e,t){const r=Xd(i.name||"");if(r&&e&&e[r])return e[r];const s=i.type;return s&&s.trim().length>0?s:r&&Ml[r]?Ml[r]:t}function So(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function eh(i,e){const t=e.split(".");let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function Ll(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=Zd(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),o={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=i.authHeader?await i.authHeader():void 0,l={accept:"application/json",...i.extraHeaders??{},...a?{authorization:a}:{}};let c=i.signEndpoint.includes("{")?i.signEndpoint:`${i.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=So(c,o),d=await fetch(u,{method:i.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=eh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,y=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!y.ok){const w=await y.text().catch(()=>"");throw new Error(`S3 PUT failed: ${y.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(So(JSON.stringify(i.registerBody??{}),o)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?So(i.viewerTemplate,o):g.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function xo(i){return{async upload(e,t){const r=new FormData,s=i.fieldName??"file";r.append(s,e,e.name);const n=typeof i.extraFields=="function"?i.extraFields(t):i.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:o,credentials:i.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(i.parseResponse)return i.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,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 th="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Rl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??th;return{async fetchMessages(s,n){const o=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)),a=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,l={accept:"application/json","content-type":"application/json",...i.extraHeaders??{}};if(i.getToken){const p=await i.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(i.parseResponse&&u)return i.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const rh=[{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)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],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},{id:"familyPension",type:"number",label:"Family Pension",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:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name",required:!0},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account No.",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],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:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No."}]},{id:"section80ccd2",type:"group",title:"Section 80CCD(2)",fields:[{id:"us80ccd2Amount",type:"number",label:"Amount",currency:"₹",min:0}]},{id:"section80g",type:"group",title:"Section 80G — Donations",fields:[{id:"us80gDonationAmount",type:"number",label:"Donation Amount",currency:"₹",min:0},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN"},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:"^[0-9]{6}$"}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eBankName",type:"text",label:"Bank Name"},{id:"us80eLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80ee",type:"group",title:"Section 80EEB — Electric Vehicle Loan Interest",fields:[{id:"us80eeLoanTakenFrom",type:"text",label:"Loan Taken From"},{id:"us80eeBankName",type:"text",label:"Bank Name"},{id:"us80eeLoanAccountNumber",type:"text",label:"Loan Account Number"},{id:"us80eeLoanSanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"us80eeLoanAmount",type:"number",label:"Loan Amount",currency:"₹",min:0},{id:"us80eeOutstandingLoan",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"us80eeVehicleRegistrationNumber",type:"text",label:"Vehicle Registration Number"},{id:"us80eeInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Self — Amount",currency:"₹",min:0,max:25e3},{id:"us80dForSelfAndFamilyPolicyCompany",type:"text",label:"Self — Policy Company Name"},{id:"us80dForSelfAndFamilyPolicyNumber",type:"text",label:"Self — Policy Number"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function nh(i,e){const t=i||{},r={userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:gh()};r.us80cAmount=Se(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Se(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Se(t.us80dForParentsAmount),r.hasParentOverSixty=lr(t.hasParentOverSixty),r.preventiveHealthCheckUp=Se(t.preventiveHealthCheckUp),r.medicalExpenditure=Se(t.medicalExpenditure),r.savingBankInterest=Se(t.savingBankInterest),r.fdInterest=Se(t.fdInterest),r.dividend=Se(t.dividend),r.anyOtherIncome=Se(t.anyOtherIncome),r.cryptoSellValue=Se(t.cryptoSellPrice),r.cryptoPurchaseAmount=Se(t.cryptoPurchasePrice),r.vdaPurchaseCost=Se(t.cryptoPurchasePrice);const s=(Se(t.bizReceiptsBank)??0)+(Se(t.bizReceiptsCash)??0),n=(Se(t.profReceiptsBank)??0)+(Se(t.profReceiptsCash)??0),o=Ee(t.bizName)!==void 0||s>0;r.businessName=Ee(o?t.bizName:t.profName),r.businessAnnualTurnOver=o?s||void 0:n||void 0,r.agricultureDetails={income:Se(t.agricultureIncome)},r.exemptIncomeAmount=Se(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),Se(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(Se(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const a={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:Se(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=Eo(t.hpDetails,ih);l.length&&(r.hpDetails=l);const c=Eo(t.salaryDetails,oh);if(c.length){r.salaryIncome=c;const u=Eo(t.salaryDetails,p=>({grossSalary:Se(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=tn(t.salaryDetails)[0]??{};r.hraAmount=Se(d.hraReceived),r.leaveTravelAllowanceAmount=Se(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Se(d.leaveEncashment),r.anyOtherAllowanceAmount=Se(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return vt(r)}function ih(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:en(i.sanctionDate),totalLoanAmount:Se(i.totalLoanAmount),loanOutstandingAmount:Se(i.outstandingAmount),interest:Se(i.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Ee(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:lr(i.hasRentalIncome),homeLoanInterest:Se(i.homeLoanInterest),homeLoanPrinciple:Se(i.homeLoanPrinciple),housePropertyAddress:Ee(i.housePropertyAddress),housePropertyPincode:Ee(i.housePropertyPincode),rentalIncome:Se(i.rentalIncome),nameOfTenant:Ee(i.nameOfTenant),propertyTax:Se(i.propertyTax),hasCoOwnedProperty:lr(i.hasCoOwnedProperty),coOwnerName:Ee(i.coOwnerName),coOwnerPan:Ee(i.coOwnerPan),coOwnerShare:Ee(i.coOwnerShare),loanDetails:t?[e]:void 0}}function oh(i){return{grossSalaryIncome:Se(i.grossSalary),salary:Se(i.basicSalary),employer:{employerName:Ee(i.employerName),employerTan:Ee(i.employerTan)},allowance:{hraAmount:Se(i.hraReceived),leaveTravelAllowanceAmount:Se(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Se(i.leaveEncashment),anyOtherAllowanceAmount:Se(i.anyOtherAllowance)}}}function sh(i,e){const t=[];for(const r of i){const s=Ee(r.employerName),n=Ee(r.employerTan),o=Se(r.grossSalary),a=Se(r.basicSalary),l=Se(r.totalTdsDeposited);s===void 0&&n===void 0&&o===void 0&&a===void 0&&l===void 0||t.push({grossSalary:o??0,basicSalary:a??0,employerName:s??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function ah(i,e){const t=Ee(i.aadhaarNumber),r=Ee(i.bankAccountNumber),s=Ee(i.bankIfscCode);return t===void 0&&r===void 0&&s===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:s}]}}function lh(i,e){return{userId:nt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Se(i.savingBankInterest)??0,fdInterest:Se(i.fdInterest)??0,dividend:Se(i.dividend)??0,anyOtherIncome:Se(i.anyOtherIncome)??0,familyPension:Se(i.familyPension)??0}}function ch(i,e){const t=Se(i.cryptoSellPrice),r=Se(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function uh(i,e){const t=(s,n,o,a)=>{const l=Ee(i[s]),c=Ee(i[n]),u=Se(i[o]),d=Se(i[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(s=>s!==null);return r.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function dh(i){return Ee(i.lenderName)!==void 0||Ee(i.loanAccountNumber)!==void 0||Se(i.totalLoanAmount)!==void 0||Se(i.outstandingAmount)!==void 0||Se(i.homeLoanInterest)!==void 0}function Nl(i){const e=Ee(i.typeOfHouseProperty)?.toUpperCase();return Se(i.rentalIncome)!==void 0||Ee(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function hh(i,e){const t=tn(i.hpDetails).filter(dh).map(r=>{const s=vt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:en(r.sanctionDate),totalLoanAmount:Se(r.totalLoanAmount),loanOutstandingAmount:Se(r.outstandingAmount),interest:Se(r.homeLoanInterest)});return vt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:Se(r.homeLoanInterest),homeLoanPrinciple:Se(r.homeLoanPrinciple),propertyTax:Se(r.propertyTax),eligible80EEAAmount:Se(r.eligible80EEAAmount),eligible80EEAmount:Se(r.eligible80EEAmount),hasCoOwnedProperty:lr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Nl(r),loanDetails:[s]})});return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function fh(i,e){const t=tn(i.hpDetails).filter(Nl).map(r=>vt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:Se(r.rentalIncome),propertyTax:Se(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:Se(r.homeLoanInterest)}));return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function ph(i,e){const t=i||{},r=g=>({userId:nt(e.userId),assessmentYear:e.assessmentYear,deductions:vt(g)}),s=[],n=Se(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?s.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const o=Ee(t.us80ccd1bPanNo),a=Se(t.us80ccd1bAmount);a!==void 0&&s.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:o}));const l=Se(t.us80ccd2Amount);l!==void 0&&s.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:o}));const c=Se(t.us80eInterest);c!==void 0&&s.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:en(t.us80eLoanSanctionDate),totalLoanAmount:Se(t.us80eLoanAmount),loanOutstandingAmount:Se(t.us80eOutstandingLoan)}));const u=Se(t.us80eeInterest);u!==void 0&&s.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:en(t.us80eeLoanSanctionDate),totalLoanAmount:Se(t.us80eeLoanAmount),loanOutstandingAmount:Se(t.us80eeOutstandingLoan),vehicleRegistrationNumber:Ee(t.us80eeVehicleRegistrationNumber)}));const d=Se(t.us80dForSelfAndFamilyAmount);d!==void 0&&s.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=Se(t.us80dForParentsAmount);return p!==void 0&&s.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:lr(t.hasParentOverSixty)??!1})),s}function mh(i,e){const t=i||{},r=Se(t.us80gDonationAmount),s=Ee(t.us80gNameOfCharity);return r===void 0&&s===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,donations80g:[vt({name:s,panNumber:Ee(t.us80gCharityPan),amountOtherThanCash:r,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode)})]}}function nt(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function Se(i){if(i==null||i==="")return;const e=typeof i=="number"?i:Number(i);return Number.isFinite(e)?e:void 0}function Ee(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function lr(i){return i===!0||i===!1?i:void 0}function gh(){const i=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}T${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${e(i.getMilliseconds(),3)}`}function en(i){const e=Ee(i);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function tn(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Eo(i,e){return tn(i).map(t=>vt(e(t))).filter(t=>t!==void 0)}function vt(i){if(Array.isArray(i)){const e=i.map(vt).filter(t=>t!==void 0);return e.length?e:void 0}if(i&&typeof i=="object"){const e={};for(const[t,r]of Object.entries(i)){const s=vt(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return i}function yh(i){const e=i&&typeof i=="object"?i:{},t={},r=Be(e.employers),s=Be(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(C=>{const j=Ao(C.salary),T=Ao(C.perquisites),$=Ao(C.profitsInLieuOfSalaryType),B=j+T+$,U=vh(C.allowance);return{employerName:Ce(C.employerName),employerTan:Ce(C.employerTAN),basicSalary:j||void 0,grossSalary:B||void 0,hraReceived:U.hra,leaveTravelAllowance:U.lta,leaveEncashment:U.leaveEncashment,anyOtherAllowance:U.other,totalTdsDeposited:bh(C,s,r)??Re(C.totalTdsDeposited)}}));const n=Be(e.houseProperties);n.length&&(t.hpDetails=n.map(C=>{const j=Be(C.loanDetails),T=j.length?j[0]:void 0,$=Re(C.grossAnnualRentReceived),B=j.length?j.reduce((re,F)=>re+(Re(F.interest)??0),0):void 0,U=Be(C.tenant),oe=Be(C.coOwners),K=U[0],W=oe[0];return{typeOfHouseProperty:Ce(C.propertyType),loanTakenFrom:Ce(T?.loanTakenFrom),lenderName:Ce(T?.bankOrInstituteName),loanAccountNumber:Ce(T?.loanAccountNo),sanctionDate:jl(T?.loanSanctionDate),totalLoanAmount:Re(T?.totalLoanAmount),outstandingAmount:Re(T?.loanOutstandingAmount),homeLoanInterest:B,homeLoanPrinciple:void 0,housePropertyAddress:Ce(C.address),housePropertyPincode:Ce(C.pinCode),rentalIncome:$,nameOfTenant:Ce(K?.name),tenantPanNumber:Ce(K?.panNumber),eligible80EEAmount:Re(C.eligible80EEAmount),eligible80EEAAmount:Re(C.eligible80EEAAmount),propertyTax:Re(C.propertyTax),hasCoOwnedProperty:oe.length>0,coOwnerName:Ce(W?.name),coOwnerPan:Ce(W?.panNumber),coOwnerShare:Re(W?.share)?.toString()}}));const o=Be(e.deductionUS80CDetails),a=It(o.map(C=>Re(C.amount))),l=o.find(C=>Ce(C.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=Be(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=Be(e.deductionUS80DDetails),p=d.find(C=>Ce(C.policyFor)?.toUpperCase()==="DEPENDANT")??Be(e.insurances).find(C=>Ce(C.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(C=>Ce(C.policyFor)?.toUpperCase()==="PARENTS")??Be(e.insurances).find(C=>Ce(C.policyFor)?.toUpperCase()==="PARENTS"),f=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,y=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Re(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??f?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??f?.accountNo),t.us80dForParentsAmount=Re(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??y?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??y?.accountNo),t.hasParentOverSixty=wh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=Be(e.donations)[0];t.us80gDonationAmount=Re(w?.amount??w?.donationAmount),t.us80gNameOfCharity=Ce(w?.nameOfCharity??w?.donorName??w?.trustName),t.us80gCharityPan=Ce(w?.panNumber??w?.charityPan),t.us80gTrustAddress=Ce(w?.address??w?.charityAddress),t.us80gPincode=Ce(w?.pinCode??w?.pincode);const k=Be(e.houseProperties?.[0]?.loanDetails)[0];t.us80eLoanTakenFrom=void 0,t.us80eBankName=void 0,t.us80eLoanAccountNumber=void 0,t.us80eLoanSanctionDate=void 0,t.us80eLoanAmount=void 0,t.us80eeLoanTakenFrom=Ce(k?.loanTakenFrom),t.us80eeBankName=Ce(k?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(k?.loanAccountNo),t.us80eeLoanSanctionDate=jl(k?.loanSanctionDate),t.us80eeLoanAmount=Re(k?.totalLoanAmount),t.us80eeOutstandingLoan=Re(k?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(k?.vehicleRegistrationNo);const S=Be(e.insurances);t.preventiveHealthCheckUp=It(S.map(C=>Re(C.preventiveCheckUp))),t.medicalExpenditure=It(S.map(C=>Re(C.medicalExpenditure)));const v=Be(e.incomes),x=C=>It(v.filter(j=>Ce(j.incomeType)===C).map(j=>Re(j.amount)));t.savingBankInterest=x("SAVING_INTEREST"),t.fdInterest=x("FD_RD_INTEREST"),t.anyOtherIncome=x("ANY_OTHER"),t.familyPension=x("FAMILY_PENSION"),t.dividend=It(Be(e.dividendIncomes).map(C=>Re(C.income)));const E=e.business;if(E){const C=Be(E.presumptiveIncomes),j=B=>{const U=Be(B.incomes),oe=K=>Re(U.find(W=>Ce(W.incomeType)===K)?.receipts)??0;return oe("ANY_OTHER")>0?!0:oe("BANK")>0||oe("CASH")>0?!1:!!Ce(B.businessType)?.toUpperCase().includes("PROFESSION")},T=B=>C.find(U=>j(U)===B),$=(B,U)=>{if(!B)return;const oe=Be(B.incomes),K=re=>Re(oe.find(F=>Ce(F.incomeType)===re)?.receipts),W=K("BANK")||K("ANY_OTHER");t[U.name]=Ce(B.businessType),t[U.nature]=Ce(B.natureOfBusiness),t[U.bank]=W||void 0,t[U.cash]=K("CASH")||void 0,t[U.net]=It(oe.map(re=>Re(re.presumptiveIncome)))||void 0};$(T(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),$(T(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const I=Be(e.capitalGain).filter(C=>Ce(C.assetType)?.toUpperCase()==="VDA").flatMap(C=>Be(C.assetDetails));I.length&&(t.cryptoSellPrice=It(I.map(C=>Re(C.sellValue))),t.cryptoPurchasePrice=It(I.map(C=>Re(C.purchaseCost)))),t.agricultureIncome=Re(e.agriculturalDetails?.income),t.aadhaarNumber=Ce(e.aadharNumber);const O=Be(e.bankDetails)[0];return O&&(t.bankAccountNumber=Ce(O.accountNumber),t.bankIfscCode=Ce(O.ifsCode)),Ul(t)}function jl(i){const e=Ce(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Ao(i){return Be(i).reduce((e,t)=>e+(Re(t.taxableAmount)??0),0)}function bh(i,e,t){if(!e.length)return;const r=Ce(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Re(n.totalTdsDeposited)}const s=Ce(i.employerName)?.trim().toLowerCase();if(s){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===s)return Re(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Re(e[0].totalTdsDeposited)}function vh(i){const e=Be(i);if(!e.length)return{};let t,r,s,n;for(const o of e){const a=Re(o.exemptAmount)??Re(o.allowanceAmount);switch(Ce(o.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":s=a;break;default:n=(n??0)+(Re(o.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:s,other:n}}function It(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function Be(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Re(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Ce(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function wh(i){if(typeof i=="boolean")return i;if(typeof i=="string"){const e=i.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof i=="number")return i===1?!0:i===0?!1:void 0}function Ul(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(s=>s&&typeof s=="object"?Ul(s):s):e[t]=r);return e}function Io(){if(typeof window>"u")return null;const i=window,e=i.__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=i.__aikaara_descriptor__??{},r=Ph(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const s=Oh(e.slug),n=typeof s?.tenantJwt=="string"?s.tenantJwt:"",o=e.getChatJwt,a=async()=>n||await o(),l=(s&&s.userId!=null&&s.userId!==""?String(s.userId):Lh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Mh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Rh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function kh(i){const e=await i.getToken(),t=i.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${i.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...i.headers}});if(!r.ok){const s=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${s.slice(0,200)}`)}return yh(To(await r.json().catch(()=>({}))))}async function _h(i,e){const t=await i.getToken(),r=i.userId,s={...nh(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(o["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const a=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(s)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return To(await a.json().catch(()=>({})))}async function Sh(i,e){return Tt(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function xh(i,e){return Tt(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Bl(i,e){return Tt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Eh(i,e){return Tt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Ah(i,e){return Tt(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function Ih(i,e){return Tt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Th(i,e){return Tt(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Ch(i,e){return Tt(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function Tt(i,e,t){const s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:s,body:JSON.stringify(t)});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${o.slice(0,200)}`)}return To(await n.json().catch(()=>({})))}function Ph(i){const e=[i.cloud?.listEndpoint,i.cloud?.downloadEndpoint,i.upload?.signEndpoint,i.login?.pan?.basicPanEndpoint,i.login?.pan?.panDetailEndpoint,i.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function Oh(i){if(!i||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${i}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function Mh(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(i))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function Lh(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function To(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Rh(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}class Nh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Ol(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),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),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),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);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();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)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),s=r(e);return t.some(n=>typeof n=="string"&&r(n)===s)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:rh,data:{}});const t=Io();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-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=Io();if(!r)return;const s={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],o=sh(n,s);o&&await Sh(r,o)}else if(e==="bank-details"){const n=ah(t,s);n&&await xh(r,n)}else if(e==="other-sources")await Bl(r,lh(t,s));else if(e==="business-profession"){const n=uh(t,s);n&&await Eh(r,n)}else if(e==="crypto-income"){const n=ch(t,s);n&&await Ch(r,n)}else if(e==="deductions"){for(const o of ph(t,s))await Ah(r,o);const n=mh(t,s);n&&await Bl(r,n)}else if(e==="house-property"){const n=hh(t,s);n&&await Ih(r,n);const o=fh(t,s);o&&await Th(r,o)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Io();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await _h(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 Dl 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||Nc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Fo,position:this.getAttribute("position")||this._config.position||Rc,width:Number(this.getAttribute("width"))||this._config.width||Pc,height:Number(this.getAttribute("height"))||this._config.height||Oc,fontFamily:this._config.fontFamily||Lc,borderRadius:this._config.borderRadius??Mc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||$o,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,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||jc,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,o=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??s),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("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;
@@ -41,7 +41,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
41
41
  <style>
42
42
  :host {
43
43
  --aikaara-primary: ${e.primaryColor};
44
- --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||Do)};
44
+ --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||Fo)};
45
45
  /* Cascade through descriptor.theme.surface / surfaceMuted /
46
46
  * text / textMuted / border when those are present (themeVars
47
47
  * sets the canonical token below). When the descriptor doesn't
@@ -112,14 +112,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
112
112
  ></aikaara-chat-header>`}
113
113
  <aikaara-message-list></aikaara-message-list>
114
114
  <aikaara-chat-input
115
- placeholder="${e.placeholder||Fo}"
115
+ placeholder="${e.placeholder||$o}"
116
116
  ${this._config.uploadAdapter?"":"disable-attach"}
117
117
  ${e.input?.attachPosition==="right"?'attach-position="right"':""}
118
118
  ${e.input?.sendButtonShape==="square"?'send-shape="square"':""}
119
119
  ></aikaara-chat-input>
120
120
  <aikaara-error-banner></aikaara-error-banner>
121
121
  </div>
122
- `;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new Mh(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),s=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|s<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Dl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
122
+ `;const a=this.shadow.querySelector("aikaara-message-list");if(a){e.hideSystemMessages?.length&&a.setHideSystemMessages?.(e.hideSystemMessages),e.timestampFormat&&a.setTimestampFormat?.(e.timestampFormat),typeof e.showTimestamps=="boolean"&&a.setShowTimestamps?.(e.showTimestamps);const l=e.templateLayout;l&&a.setTemplateLayout?.(l)}}async initController(){const e=this.getConfig(),t=e.transport??"aikaara";(t==="aikaara"||t==="dual")&&(!e.baseUrl||!e.userToken)||(this.controller?.disconnect(),this.controller=new Nh(e,this.shadow,{uploadAdapter:this._config.uploadAdapter,historyAdapter:this._config.historyAdapter}),await this.controller.connect())}sendUserEvent(e,t,r){this.controller?.sendUserEvent(e,t,r)}getClient(){return this.controller?.getClient()??null}darkenColor(e){try{const t=parseInt(e.replace("#",""),16),r=Math.max(0,(t>>16)-20),s=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|s<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Fl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.shadow.querySelector(".bubble")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
123
123
  <style>
124
124
  .bubble {
125
125
  width: var(--aikaara-bubble-size, 60px);
@@ -154,7 +154,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
154
154
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
155
155
  </svg>
156
156
  </button>
157
- `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const Rh=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Fl extends HTMLElement{shadow;actions=Rh;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const s=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:s,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),s=this.getAttribute("status")||"connected",n=s==="connected"?"#10b981":s==="connecting"||s==="reconnecting"?"#f59e0b":"#ef4444",o=this.actions.map(a=>`
157
+ `}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const jh=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class $l extends HTMLElement{shadow;actions=jh;menuOpen=!1;outsideClickHandler=null;static get observedAttributes(){return["title","subtitle","avatar-url","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.bindHandlers()}disconnectedCallback(){this.outsideClickHandler&&document.removeEventListener("click",this.outsideClickHandler,!0)}attributeChangedCallback(){this.render(),this.bindHandlers()}setActions(e){this.actions=e,this.render(),this.bindHandlers()}bindHandlers(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("header-close",{bubbles:!0,composed:!0}))}),this.shadow.querySelector(".menu-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.toggleMenu()}),this.shadow.querySelectorAll(".menu-item").forEach(t=>{t.addEventListener("click",r=>{r.stopPropagation();const s=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:s,label:n},bubbles:!0,composed:!0}))})}),this.outsideClickHandler||(this.outsideClickHandler=t=>{!this.menuOpen||t.composedPath().includes(this)||this.closeMenu()},document.addEventListener("click",this.outsideClickHandler,!0))}toggleMenu(){this.menuOpen=!this.menuOpen;const e=this.shadow.querySelector(".menu");e&&e.classList.toggle("open",this.menuOpen)}closeMenu(){if(!this.menuOpen)return;this.menuOpen=!1;const e=this.shadow.querySelector(".menu");e&&e.classList.remove("open")}iconSvg(e){return e==="edit"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>':e==="mail"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>':e==="star"?'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>':""}render(){const e=this.getAttribute("title")||"Chat",t=this.getAttribute("subtitle")||"",r=this.getAttribute("avatar-url"),s=this.getAttribute("status")||"connected",n=s==="connected"?"#10b981":s==="connecting"||s==="reconnecting"?"#f59e0b":"#ef4444",o=this.actions.map(a=>`
158
158
  <button class="menu-item" type="button" data-action-id="${a.id}" data-action-label="${a.label}">
159
159
  <span class="menu-item-icon">${this.iconSvg(a.icon)}</span>
160
160
  <span class="menu-item-label">${a.label}</span>
@@ -314,7 +314,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
314
314
  </button>
315
315
  </div>
316
316
  </div>
317
- `}setStatus(e){this.setAttribute("status",e)}}const Lh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Nh=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,jh={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function Uh(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>jh[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&amp;/gi,"&")}function Gt(i){if(Lh.test(i))return i;const e=Nh.test(i)?Uh(i):i;let t=Bh(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,s,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,s,n)=>{const o=/[.,!?;:]+$/.exec(n),a=o?o[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${s}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function Bh(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return i.replace(/[&<>"']/g,t=>e[t])}const Dh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Fh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Yt(i){const e=document.createElement("template");return e.innerHTML=i,$l(e.content),e.innerHTML}function $l(i){const e=Array.from(i.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,s=r.tagName.toLowerCase();if(!Dh.has(s)){const a=document.createTextNode(r.textContent||"");i.replaceChild(a,t);continue}const n=Fh[s]||new Set,o=Array.from(r.attributes);for(const a of o)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}$l(t)}}function ql(i,e={}){const{width:t=600,height:r=700,closeOnTypes:s}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),o=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(i,"aikaara_popup",`width=${t},height=${r},left=${n},top=${o},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const d=u.data?.type;s&&typeof d=="string"&&!s.includes(d)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function $h(i){const e=Date.now()-i.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const s=Math.round(r/60);if(s<24)return`${s} hr ago`;const n=Math.round(s/24);return n===1?"Yesterday":n<7?`${n} d ago`:i.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Hl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(s=>r.includes(s)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(o=>o&&o.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const s=this.linkHandlers.some(o=>Wl(r.href,o.match));r.target==="_self"&&!s||t.some(o=>{if(!o||!o.classList)return!1;const a=o.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
317
+ `}setStatus(e){this.setAttribute("status",e)}}const Uh=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Bh=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Dh={"&quot;":'"',"&apos;":"'","&lt;":"<","&gt;":">","&amp;":"&","&nbsp;":" "};function Fh(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Dh[e.toLowerCase()]??e).replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(parseInt(t,16))).replace(/&amp;/gi,"&")}function Gt(i){if(Uh.test(i))return i;const e=Bh.test(i)?Fh(i):i;let t=$h(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,s,n)=>`<pre><code>${n.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_self" rel="noopener noreferrer">$1</a>'),t=t.replace(/(^|[^"'>=(])(https?:\/\/[^\s<]+)/g,(r,s,n)=>{const o=/[.,!?;:]+$/.exec(n),a=o?o[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${s}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function $h(i){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return i.replace(/[&<>"']/g,t=>e[t])}const qh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Hh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Yt(i){const e=document.createElement("template");return e.innerHTML=i,ql(e.content),e.innerHTML}function ql(i){const e=Array.from(i.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,s=r.tagName.toLowerCase();if(!qh.has(s)){const a=document.createTextNode(r.textContent||"");i.replaceChild(a,t);continue}const n=Hh[s]||new Set,o=Array.from(r.attributes);for(const a of o)n.has(a.name)||r.removeAttribute(a.name);if(r.hasAttribute("href")){const a=r.getAttribute("href")||"";!a.startsWith("http://")&&!a.startsWith("https://")&&!a.startsWith("/")&&r.removeAttribute("href")}ql(t)}}function Hl(i,e={}){const{width:t=600,height:r=700,closeOnTypes:s}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),o=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(i,"aikaara_popup",`width=${t},height=${r},left=${n},top=${o},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const d=u.data?.type;s&&typeof d=="string"&&!s.includes(d)||(a.close(),window.removeEventListener("message",l))};window.addEventListener("message",l);const c=setInterval(()=>{a.closed&&(window.removeEventListener("message",l),clearInterval(c))},500);return a}function Wh(i){const e=Date.now()-i.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const s=Math.round(r/60);if(s<24)return`${s} hr ago`;const n=Math.round(s/24);return n===1?"Yesterday":n<7?`${n} d ago`:i.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class Wl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(e.template?.contentType)return!1;const t=e.content;if(!t)return!1;const r=t.trim().toLowerCase();return r==="chat_initiated"||r==="group created"||r==="file_uploaded"||r==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(s=>r.includes(s)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(o=>o&&o.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const s=this.linkHandlers.some(o=>zl(r.href,o.match));r.target==="_self"&&!s||t.some(o=>{if(!o||!o.classList)return!1;const a=o.classList;return a.contains("bubble")&&a.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
318
318
  <style>
319
319
  :host {
320
320
  display: flex;
@@ -475,7 +475,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
475
475
  }
476
476
  </style>
477
477
  <div class="message-list"></div>
478
- `,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">${Yt(Gt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const s=r.externalId??r.id;this.appendMessageElement(r,t.get(s))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;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 o=n.metadata?.attributes?.action;if(o){const a=qh(o);if(o.message_id&&t.set(o.message_id,a),Object.keys(a).length>0)for(let l=s-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,d=t.get(u);(!d||Object.keys(d).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&s<r){const o=n.externalId??n.id;t.has(o)||t.set(o,{})}}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=Yt(Gt(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){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 d=document.createElement("div");d.classList.add("message-wrap","system"),d.dataset.messageId=e.id,e.externalId&&(d.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),d.appendChild(p),this.container.appendChild(d);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 o=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?s.classList.add("attachment-only"):s.textContent=e.content:o?e.content&&(s.innerHTML=Yt(Gt(e.content))):(s.innerHTML=Yt(Gt(e.content||"")),e.status==="streaming"&&s.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const d=document.createElement("aikaara-template-renderer");d.setAttribute("content-type",e.template.contentType),e.template.templateId&&d.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&d.setAttribute("message-id",p),d.setPayload(e.template.payload),t!==void 0&&(d.dataset.consumed="true",Object.keys(t).length>0&&d.setConsumedValues?.(t)),this.templateLayout==="outside"?(d.classList.add("template-outside"),a=d):s.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const y=document.createElement("aikaara-template-renderer");y.setAttribute("content-type","300"),y.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};y.setPayload(f,""),d.appendChild(y)}s.appendChild(d)}const u=!(s.childNodes.length===0&&(s.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(s),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const d=document.createElement("div");if(d.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(d.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(p)}r.appendChild(d)}r.childNodes.length>0&&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 $h(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=>Wl(e,y.match)),s=r?.target??"iframe";if(s==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(s==="popup"){ql(e);return}const n=this.getOrCreateModal(),o=r?.title??t??"Link";if(s==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,o));return}const a=Hh(e),l=zl(r.fetch.url,a),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 d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify(To(r.fetch.body,a)));let p=null;try{const y=await fetch(l,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,o,y=>{const f=r.props??{setData:p};for(const[b,w]of Object.entries(f)){const m=y[b];typeof m=="function"&&m.call(y,w)}const g=b=>{const w=b,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.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 qh(i){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,s]of Object.entries(i))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}function Wl(i,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(i)}function Hh(i){try{const e=new URL(i),t={};return e.searchParams.forEach((r,s)=>{t[s]=r}),t}catch{return{}}}function zl(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function To(i,e){if(typeof i=="string")return zl(i,e);if(Array.isArray(i))return i.map(t=>To(t,e));if(i&&typeof i=="object"){const t={};for(const[r,s]of Object.entries(i))t[r]=To(s,e);return t}return i}class Vl 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")||"",o=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Yt(Gt(t)),c=e==="user"&&s,u=s==="sending"?"○":s==="sent"?"✓":s==="delivered"||s==="read"?"✓✓":"";this.shadow.innerHTML=`
478
+ `,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">${Yt(Gt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const s=r.externalId??r.id;this.appendMessageElement(r,t.get(s))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;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 o=n.metadata?.attributes?.action;if(o){const a=zh(o);if(o.message_id&&t.set(o.message_id,a),Object.keys(a).length>0)for(let l=s-1;l>=0;l--){const c=e[l];if(c.role!=="user"&&c.template?.contentType){const u=c.externalId??c.id,d=t.get(u);(!d||Object.keys(d).length===0)&&t.set(u,a);break}}}}if(n.role!=="user"&&n.template?.contentType&&s<r){const o=n.externalId??n.id;t.has(o)||t.set(o,{})}}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=Yt(Gt(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){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 d=document.createElement("div");d.classList.add("message-wrap","system"),d.dataset.messageId=e.id,e.externalId&&(d.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),d.appendChild(p),this.container.appendChild(d);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 o=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?s.classList.add("attachment-only"):s.textContent=e.content:o?e.content&&(s.innerHTML=Yt(Gt(e.content))):(s.innerHTML=Yt(Gt(e.content||"")),e.status==="streaming"&&s.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const d=document.createElement("aikaara-template-renderer");d.setAttribute("content-type",e.template.contentType),e.template.templateId&&d.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&d.setAttribute("message-id",p),d.setPayload(e.template.payload),t!==void 0&&(d.dataset.consumed="true",Object.keys(t).length>0&&d.setConsumedValues?.(t)),this.templateLayout==="outside"?(d.classList.add("template-outside"),a=d):s.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const f={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(f,""),d.appendChild(g)}s.appendChild(d)}const u=!(s.childNodes.length===0&&(s.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(s),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const d=document.createElement("div");if(d.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(d.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(p)}r.appendChild(d)}r.childNodes.length>0&&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 Wh(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(g=>zl(e,g.match)),s=r?.target??"iframe";if(s==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(s==="popup"){Hl(e);return}const n=this.getOrCreateModal(),o=r?.title??t??"Link";if(s==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,o));return}const a=Vh(e),l=Vl(r.fetch.url,a),c={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const g=await this.getLinkBearer(u);g&&(c.authorization=`Bearer ${g}`)}const d={method:r.fetch.method??"GET",headers:c};r.fetch.body&&(c["content-type"]="application/json",d.body=JSON.stringify(Co(r.fetch.body,a)));let p=null;try{const g=await fetch(l,d);g.ok&&(p=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,o,g=>{const f=r.props??{setData:p};for(const[b,w]of Object.entries(f)){const m=g[b];typeof m=="function"&&m.call(g,w)}const y=b=>{const w=b,m=w.detail?.message??w.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...w.detail?.attributes??{}}},bubbles:!0,composed:!0})))};g.addEventListener("aikaara-plan-select",y),g.addEventListener("aikaara-select",y)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function zh(i){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,s]of Object.entries(i))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}function zl(i,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(i)}function Vh(i){try{const e=new URL(i),t={};return e.searchParams.forEach((r,s)=>{t[s]=r}),t}catch{return{}}}function Vl(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Co(i,e){if(typeof i=="string")return Vl(i,e);if(Array.isArray(i))return i.map(t=>Co(t,e));if(i&&typeof i=="object"){const t={};for(const[r,s]of Object.entries(i))t[r]=Co(s,e);return t}return i}class Kl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",s=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",o=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Yt(Gt(t)),c=e==="user"&&s,u=s==="sending"?"○":s==="sent"?"✓":s==="delivered"||s==="read"?"✓✓":"";this.shadow.innerHTML=`
479
479
  <style>
480
480
  :host { display: flex; flex-direction: column; }
481
481
  :host([role="user"]) { align-items: flex-end; }
@@ -543,7 +543,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
543
543
  ${n?`<aikaara-template-renderer
544
544
  content-type="${n}"
545
545
  template-id="${o}"
546
- inner-message="${Kl(a)}"
546
+ inner-message="${Gl(a)}"
547
547
  ></aikaara-template-renderer>`:""}
548
548
  ${this.renderAttachments()}
549
549
  </div>
@@ -552,9 +552,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
552
552
  ${r}${c?`<span class="status">${u}</span>`:""}
553
553
  </div>
554
554
  `:""}
555
- `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Kl(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
- 📎 ${Wh(t.fileName)}
557
- </a>`).join("")}</div>`:""}}function Kl(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Wh(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Gl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",s=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",o=this.getAttribute("send-shape")==="square",a=t?`
555
+ `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${Gl(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
556
+ 📎 ${Kh(t.fileName)}
557
+ </a>`).join("")}</div>`:""}}function Gl(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Kh(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Yl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",s=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",o=this.getAttribute("send-shape")==="square",a=t?`
558
558
  <button class="attach-btn" aria-label="Attach file" type="button">
559
559
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
560
560
  <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
@@ -632,7 +632,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
632
632
  ${n?a:""}
633
633
  ${l}
634
634
  </div>
635
- `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class Yl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
635
+ `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.attachBtn=this.shadow.querySelector(".attach-btn"),this.fileInput=this.shadow.querySelector('input[type="file"]'),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.refreshSendDisabled()}),this.textarea.addEventListener("keydown",u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend()),this.attachBtn?.addEventListener("click",()=>{this._disabled||this._uploading||this.fileInput?.click()}),this.fileInput?.addEventListener("change",()=>{const u=this.fileInput?.files;if(u?.length){for(const d of Array.from(u))this.dispatchEvent(new CustomEvent("file-pick",{detail:{file:d},bubbles:!0,composed:!0}));this.fileInput&&(this.fileInput.value="")}})}set disabled(e){this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.attachBtn&&(this.attachBtn.disabled=e||this._uploading),this.refreshSendDisabled()}get disabled(){return this._disabled}set uploading(e){this._uploading=e,this.attachBtn&&(this.attachBtn.dataset.uploading=String(e),this.attachBtn.disabled=this._disabled||e)}get uploading(){return this._uploading}focus(){this.textarea?.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.refreshSendDisabled())}refreshSendDisabled(){this.sendBtn&&(this.sendBtn.disabled=this._disabled||this._uploading||!this.textarea.value.trim())}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class Jl extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
636
636
  <style>
637
637
  :host { display: none; }
638
638
  :host([visible]) { display: block; }
@@ -666,7 +666,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
666
666
  <span class="dot"></span>
667
667
  <span class="dot"></span>
668
668
  </div>
669
- `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Jl extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
669
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class Ql extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
670
670
  <style>
671
671
  :host {
672
672
  display: flex;
@@ -715,7 +715,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
715
715
  }
716
716
  </style>
717
717
  <div class="bubble cursor"></div>
718
- `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Yt(Gt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Ql extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
718
+ `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Yt(Gt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class Xl extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
719
719
  <style>
720
720
  .banner {
721
721
  display: none;
@@ -743,7 +743,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
743
743
  <span class="message"></span>
744
744
  <button class="dismiss">Dismiss</button>
745
745
  </div>
746
- `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const Co=new Map;function Xl(i){const e=Co.get(i);if(e)return e;const t=new Promise((r,s)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(i)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>s(new Error(`Failed to load ${i}`)),{once:!0}));return}const o=document.createElement("script");o.src=i,o.async=!0,o.crossOrigin="anonymous",o.dataset.aikaaraSrc=i,o.addEventListener("load",()=>{o.dataset.aikaaraReady="1",r()},{once:!0}),o.addEventListener("error",()=>{Co.delete(i),s(new Error(`Failed to load ${i}`))},{once:!0}),document.head.appendChild(o)});return Co.set(i,t),t}function zh(i,e=5e3){return new Promise((t,r)=>{const s=setTimeout(()=>r(new Error(`Custom element <${i}> not registered within ${e}ms`)),e);customElements.whenDefined(i).then(()=>{clearTimeout(s),t()})})}const Vh={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>Kf).then(({registerAikaaraPaymentLink:i})=>i())};function Kh(i){const e=`template:${i}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[i]}class Gh extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const s=Qh(t.attributes.action);if(Object.keys(s).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(s))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const s=localStorage.getItem(`aikaara_form:${r}`);s&&(e=JSON.parse(s))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s,o=n.getName?.();o&&r[o]?.length&&n.setPreSelected?.(r[o])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
746
+ `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const Po=new Map;function Zl(i){const e=Po.get(i);if(e)return e;const t=new Promise((r,s)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(i)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>s(new Error(`Failed to load ${i}`)),{once:!0}));return}const o=document.createElement("script");o.src=i,o.async=!0,o.crossOrigin="anonymous",o.dataset.aikaaraSrc=i,o.addEventListener("load",()=>{o.dataset.aikaaraReady="1",r()},{once:!0}),o.addEventListener("error",()=>{Po.delete(i),s(new Error(`Failed to load ${i}`))},{once:!0}),document.head.appendChild(o)});return Po.set(i,t),t}function Gh(i,e=5e3){return new Promise((t,r)=>{const s=setTimeout(()=>r(new Error(`Custom element <${i}> not registered within ${e}ms`)),e);customElements.whenDefined(i).then(()=>{clearTimeout(s),t()})})}const Yh={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>Jf).then(({registerAikaaraPaymentLink:i})=>i())};function Jh(i){const e=`template:${i}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[i]}class Qh extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;_consumedValues=null;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",e=>{const t=e.detail,r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const s=ef(t.attributes.action);if(Object.keys(s).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(s))}catch{}}this.dataset.consumed="true",this._applyConsumedToChildren()})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}setConsumedValues(e){this._consumedValues=e,this._applyConsumedToChildren()}_applyConsumedToChildren(){let e=this._consumedValues;if(!e){const r=this.getAttribute("message-id");if(r)try{const s=localStorage.getItem(`aikaara_form:${r}`);s&&(e=JSON.parse(s))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s,o=n.getName?.();o&&r[o]?.length&&n.setPreSelected?.(r[o])})}this.querySelectorAll("aikaara-submit-action, aikaara-modal-action, aikaara-link-button").forEach(r=>{r.style.display="none"});const t=new Set(["aikaara-option-list","aikaara-submit-action","aikaara-modal-action","aikaara-link-button"]);this.querySelectorAll("*").forEach(r=>{if(t.has(r.tagName.toLowerCase()))return;e&&r.setConsumedValues?.(e),r.dataset.consumed="true"})}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
747
747
  <style>
748
748
  :host { display: block; }
749
749
  ::slotted(*) { display: block; }
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
757
757
  }
758
758
  </style>
759
759
  <slot></slot>
760
- `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Kh(t):void 0,s=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Vh[s];if(n&&!customElements.get(s)?n().then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] native template ${s} failed to load`,o)):r?.scriptUrl&&!customElements.get(s)&&Xl(r.scriptUrl).then(()=>zh(s)).then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,o)),customElements.get(s)){const o=document.createElement(s);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof o[a]=="function")try{o[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${s}>`,c)}}o.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(o),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&o.setConsumedValues?.(this._consumedValues),o.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const o=this.payloadData;if(o.length>0&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:o.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of o)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const o=this.payloadData;typeof o.message=="string"&&(o.okLabel||o.action||o.ok)&&this.mountModal(o)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const s=document.createElement("aikaara-text-input");s.setPayload(r),this.appendChild(s);return}if(t==="checkbox"||t==="radio"||t==="button"){const s=document.createElement("aikaara-option-list");s.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(s);return}if(t==="submit"){const s=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;s.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(s);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>Qf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:s})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Jh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Yh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Jh(i){const e={};for(const[t,r]of Object.entries(i))Yh.has(t)||(e[t]=r);return e}function Qh(i){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,s]of Object.entries(i))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}class Xh extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
760
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Jh(t):void 0,s=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Yh[s];if(n&&!customElements.get(s)?n().then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] native template ${s} failed to load`,o)):r?.scriptUrl&&!customElements.get(s)&&Zl(r.scriptUrl).then(()=>Gh(s)).then(()=>this.render()).catch(o=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,o)),customElements.get(s)){const o=document.createElement(s);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof o[a]=="function")try{o[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${s}>`,c)}}o.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(o),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&o.setConsumedValues?.(this._consumedValues),o.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const o=this.payloadData;if(o.length>0&&o.every(l=>l&&typeof l=="object"&&!Array.isArray(l)&&!("type"in l)&&!("data"in l)&&typeof l.message=="string")){const l=document.createElement("aikaara-option-list");l.setPayload({name:"quick-reply",type:"button",options:o.map(c=>{const u=typeof c.title=="string"?c.title:"",d=c.message;return{label:u||d,value:d}})}),this.appendChild(l);return}for(const l of o)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const o=this.payloadData;typeof o.message=="string"&&(o.okLabel||o.action||o.ok)&&this.mountModal(o)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const s=document.createElement("aikaara-text-input");s.setPayload(r),this.appendChild(s);return}if(t==="checkbox"||t==="radio"||t==="button"){const s=document.createElement("aikaara-option-list");s.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(s);return}if(t==="submit"){const s=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;s.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(s);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>ep).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:s})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Zh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Xh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Zh(i){const e={};for(const[t,r]of Object.entries(i))Xh.has(t)||(e[t]=r);return e}function ef(i){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,s]of Object.entries(i))e.has(r)||(Array.isArray(s)&&s.every(n=>typeof n=="string")?t[r]=s:typeof s=="string"&&(t[r]=[s]));return t}class tf extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
761
761
  <style>
762
762
  :host {
763
763
  display: flex;
@@ -782,9 +782,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
782
782
  color: var(--aikaara-text-secondary, #9ca3af);
783
783
  }
784
784
  </style>
785
- <span class="pill">${Zl(e)}</span>
786
- ${t?`<span class="sub">${Zl(t)}</span>`:""}
787
- `}}function Zl(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Zh extends HTMLElement{shadow;data=null;selected=new Set;preSelectedDisabled=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.preSelectedDisabled=!1,this.render()}getName(){return this.data?.name??""}setPreSelected(e){this.selected=new Set(e),this.preSelectedDisabled=!0,this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,s=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const o=t[0],a=this.selected.has(o.value),l=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
785
+ <span class="pill">${ec(e)}</span>
786
+ ${t?`<span class="sub">${ec(t)}</span>`:""}
787
+ `}}function ec(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class rf extends HTMLElement{shadow;data=null;selected=new Set;preSelectedDisabled=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.preSelectedDisabled=!1,this.render()}getName(){return this.data?.name??""}setPreSelected(e){this.selected=new Set(e),this.preSelectedDisabled=!0,this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,s=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const o=t[0],a=this.selected.has(o.value),l=this.preSelectedDisabled?"cursor: default; pointer-events: none;":"cursor: pointer;";if(this.shadow.innerHTML=`
788
788
  <style>
789
789
  :host { display: block; margin: 8px 0; }
790
790
  .row {
@@ -819,7 +819,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
819
819
  .row[aria-checked="true"] .check { opacity: 1; }
820
820
  .text { flex: 1; }
821
821
  </style>
822
- <div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}" data-value="${Po(o.value)}">
822
+ <div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}" data-value="${Oo(o.value)}">
823
823
  <span class="box" aria-hidden="true">
824
824
  <svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
825
825
  <path d="M3 8 L7 12 L13 4" />
@@ -872,7 +872,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
872
872
  ${t.map(a=>{const l=this.selected.has(a.value);return`
873
873
  <div class="row" role="radio" tabindex="${this.preSelectedDisabled?"-1":"0"}"
874
874
  aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}"
875
- data-value="${Po(a.value)}">
875
+ data-value="${Oo(a.value)}">
876
876
  <span class="circle" aria-hidden="true"><span class="dot"></span></span>
877
877
  <span class="label">${Bt(a.label)}</span>
878
878
  </div>`}).join("")}
@@ -914,14 +914,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
914
914
  <div class="grid" role="${s?"group":"radiogroup"}" aria-label="${Bt(e??this.data.name)}">
915
915
  ${t.map(o=>`
916
916
  <button class="opt" type="button"
917
- data-value="${Po(o.value)}"
917
+ data-value="${Oo(o.value)}"
918
918
  role="${s?"checkbox":"radio"}"
919
919
  aria-pressed="${this.selected.has(o.value)}"
920
920
  ${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
921
921
  ${Bt(o.label)}
922
922
  </button>`).join("")}
923
923
  </div>
924
- `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(o=>{o.addEventListener("click",()=>this.toggle(o.dataset.value||""))})}}function Bt(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Po(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class ef extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;if(!t)return e;let r=!0;return t.querySelectorAll("aikaara-text-input").forEach(s=>{(s.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(s=>{const n=s.getValues?.();n?.name&&(e[n.name]=n.values[0]??"")}),e):null}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues();if(t===null)return;const r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
924
+ `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(o=>{o.addEventListener("click",()=>this.toggle(o.dataset.value||""))})}}function Bt(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Oo(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class nf extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;if(!t)return e;let r=!0;return t.querySelectorAll("aikaara-text-input").forEach(s=>{(s.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(s=>{const n=s.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(s=>{const n=s.getValues?.();n?.name&&(e[n.name]=n.values[0]??"")}),e):null}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues();if(t===null)return;const r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
925
925
  <style>
926
926
  :host { display: block; margin: 12px 0 4px; }
927
927
  button {
@@ -939,8 +939,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
939
939
  button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
940
940
  button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
941
941
  </style>
942
- <button type="button">${tf(e)}</button>
943
- `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function tf(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class rf extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
942
+ <button type="button">${of(e)}</button>
943
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function of(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class sf extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
944
944
  <style>
945
945
  :host { all: initial; }
946
946
  .overlay {
@@ -981,14 +981,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
981
981
  </style>
982
982
  <div class="overlay" role="dialog" aria-modal="true">
983
983
  <div class="modal">
984
- <div class="msg">${Oo(this.data.message)}</div>
984
+ <div class="msg">${Mo(this.data.message)}</div>
985
985
  <div class="actions">
986
- ${t?`<button class="cancel" type="button">${Oo(t)}</button>`:""}
987
- <button class="ok" type="button">${Oo(e)}</button>
986
+ ${t?`<button class="cancel" type="button">${Mo(t)}</button>`:""}
987
+ <button class="ok" type="button">${Mo(e)}</button>
988
988
  </div>
989
989
  </div>
990
990
  </div>
991
- `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Oo(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class nf extends HTMLElement{shadow;data=null;_value="";_error="";_touched=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}getValues(){return{name:this.data?.label??"",values:[this._value],type:"text"}}validate(){this._touched=!0;const e=this._computeError(this._value);return this._error=e,this._updateError(),!e}_computeError(e){if(!this.data)return"";if(this.data.required&&!e.trim())return this.data.validation?.errorText??`${this.data.label} is required`;if(e&&this.data.validation?.regex)try{if(!new RegExp(this.data.validation.regex).test(e))return this.data.validation.errorText}catch{}return""}_updateError(){const e=this.shadow.querySelector(".error");e&&(e.textContent=this._error);const t=this.shadow.querySelector("input");t&&t.setAttribute("aria-invalid",this._error?"true":"false")}render(){if(!this.data){this.shadow.innerHTML="";return}const{label:e,placeholder:t="",required:r=!1}=this.data,s=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
991
+ `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Mo(i){return String(i).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class af extends HTMLElement{shadow;data=null;_value="";_error="";_touched=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}getValues(){return{name:this.data?.label??"",values:[this._value],type:"text"}}validate(){this._touched=!0;const e=this._computeError(this._value);return this._error=e,this._updateError(),!e}_computeError(e){if(!this.data)return"";if(this.data.required&&!e.trim())return this.data.validation?.errorText??`${this.data.label} is required`;if(e&&this.data.validation?.regex)try{if(!new RegExp(this.data.validation.regex).test(e))return this.data.validation.errorText}catch{}return""}_updateError(){const e=this.shadow.querySelector(".error");e&&(e.textContent=this._error);const t=this.shadow.querySelector("input");t&&t.setAttribute("aria-invalid",this._error?"true":"false")}render(){if(!this.data){this.shadow.innerHTML="";return}const{label:e,placeholder:t="",required:r=!1}=this.data,s=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
992
992
  <style>
993
993
  :host { display: block; margin-bottom: 12px; }
994
994
  label {
@@ -1022,16 +1022,16 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1022
1022
  }
1023
1023
  :host([data-consumed]) input { pointer-events: none; opacity: 0.65; background: var(--aikaara-input-bg, #f9fafb); }
1024
1024
  </style>
1025
- <label>${lr(e)}${s}</label>
1025
+ <label>${cr(e)}${s}</label>
1026
1026
  <input
1027
1027
  type="text"
1028
- placeholder="${lr(t)}"
1029
- value="${lr(this._value)}"
1030
- aria-label="${lr(e)}"
1028
+ placeholder="${cr(t)}"
1029
+ value="${cr(this._value)}"
1030
+ aria-label="${cr(e)}"
1031
1031
  aria-invalid="false"
1032
1032
  />
1033
- <div class="error" role="alert">${lr(this._error)}</div>
1034
- `;const n=this.shadow.querySelector("input");n.addEventListener("input",()=>{this._value=n.value,this._touched&&(this._error=this._computeError(this._value),this._updateError())}),n.addEventListener("blur",()=>{!this._touched&&this._value&&(this._touched=!0,this._error=this._computeError(this._value),this._updateError())})}}function lr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class of extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),s=this.tokenGetter??r;if(!s){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},o=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(o?n[o]:void 0);a&&(o&&o!=="X-Api-Key"&&delete n[o],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await pc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:l,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:s,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class sf extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let s=!1;this.iframe.addEventListener("load",()=>{s=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{s||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const s=this.shadow.querySelector(".modal-title");s&&(s.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const o=document.createElement(e);n.appendChild(o),requestAnimationFrame(()=>r?.(o))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
1033
+ <div class="error" role="alert">${cr(this._error)}</div>
1034
+ `;const n=this.shadow.querySelector("input");n.addEventListener("input",()=>{this._value=n.value,this._touched&&(this._error=this._computeError(this._value),this._updateError())}),n.addEventListener("blur",()=>{!this._touched&&this._value&&(this._touched=!0,this._error=this._computeError(this._value),this._updateError())})}}function cr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class lf extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),s=this.tokenGetter??r;if(!s){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},o=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(o?n[o]:void 0);a&&(o&&o!=="X-Api-Key"&&delete n[o],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await mc({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:l,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:s,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:c=>this.dispatchEvent(new CustomEvent("error",{detail:c}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(c){this.dispatchEvent(new CustomEvent("error",{detail:c}))}finally{this.mountInflight=null}})(),this.mountInflight}}class cf extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let s=!1;this.iframe.addEventListener("load",()=>{s=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{s||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const s=this.shadow.querySelector(".modal-title");s&&(s.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const o=document.createElement(e);n.appendChild(o),requestAnimationFrame(()=>r?.(o))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
1035
1035
  <style>
1036
1036
  :host { display: block; }
1037
1037
  .backdrop {
@@ -1081,7 +1081,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1081
1081
  <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
1082
1082
  </div>
1083
1083
  </div>
1084
- `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const af=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],lf=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class cf extends HTMLElement{shadow;data=null;columns=lf;features=af;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
1084
+ `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const uf=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],df=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class hf extends HTMLElement{shadow;data=null;columns=df;features=uf;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
1085
1085
  <style>
1086
1086
  :host {
1087
1087
  display: block;
@@ -1137,13 +1137,13 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1137
1137
  <thead>
1138
1138
  <tr>
1139
1139
  <th>Feature</th>
1140
- ${e.map(r=>`<th>${Mo(r.label)}</th>`).join("")}
1140
+ ${e.map(r=>`<th>${Lo(r.label)}</th>`).join("")}
1141
1141
  </tr>
1142
1142
  </thead>
1143
1143
  <tbody>
1144
1144
  ${t.map((r,s)=>`
1145
1145
  <tr>
1146
- <td>${Mo(r.label)}</td>
1146
+ <td>${Lo(r.label)}</td>
1147
1147
  ${e.map(n=>n.features[s]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
1148
1148
  </tr>`).join("")}
1149
1149
  <tr class="price-row">
@@ -1154,18 +1154,18 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1154
1154
  </table>
1155
1155
  <div class="actions">
1156
1156
  ${e.map((r,s)=>{const n=this.priceFor(r),o=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${s}" type="button">
1157
- <span>${Mo(o)}</span>
1157
+ <span>${Lo(o)}</span>
1158
1158
  <small>Tap to select</small>
1159
1159
  </button>`}).join("")}
1160
1160
  </div>
1161
- `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const s=Number(r.dataset.col),n=e[s];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Mo(i){return i.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class uf extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),s=r?t.slice(0,-2):t,n=this.data[s];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(s=>s.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
1161
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const s=Number(r.dataset.col),n=e[s];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function Lo(i){return i.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class ff extends HTMLElement{shadow;root=null;schemas=[];data={};view="picker";activeSectionId=null;keydownHandler=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.renderShell()}disconnectedCallback(){this.keydownHandler&&(document.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null)}open(e){this.root||this.renderShell(),this.root&&(this.schemas=e.schemas,this.data=e.data?{...e.data}:{},e.activeSectionId&&this.schemas.some(t=>t.id===e.activeSectionId)?(this.activeSectionId=e.activeSectionId,this.view="form"):(this.activeSectionId=null,this.view="picker"),this.renderView(),this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("smart-edit-open",{bubbles:!0,composed:!0})))}close(){this.root&&(this.root.classList.remove("open"),this.dispatchEvent(new CustomEvent("smart-edit-close",{bubbles:!0,composed:!0})))}setData(e){this.data={...e},this.view==="form"&&this.mountActiveForm()}openSection(e){this.activeSectionId=e,this.view="form",this.renderView()}backToPicker(){this.activeSectionId=null,this.view="picker",this.renderView()}extractSlice(e){const t=e.dataPath;if(!t)return this.data;const r=t.endsWith("[]"),s=r?t.slice(0,-2):t,n=this.data[s];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(s=>s.id===e);if(r){if(r.dataPath){const n=r.dataPath.endsWith("[]")?r.dataPath.slice(0,-2):r.dataPath;this.data={...this.data,[n]:t}}else t&&typeof t=="object"&&(this.data={...this.data,...t});this.dispatchEvent(new CustomEvent("smart-edit-submit",{detail:{sectionId:e,record:this.data},bubbles:!0,composed:!0})),this.backToPicker()}}handleRecalculate(){this.dispatchEvent(new CustomEvent("smart-edit-recalculate",{detail:{record:this.data},bubbles:!0,composed:!0})),this.close()}renderView(){this.view==="form"?this.renderForm():this.renderPicker()}renderPicker(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-form"),e.classList.add("view-picker");const t=this.shadow.querySelector(".modal-header");t.innerHTML=`
1162
1162
  <span class="header-spacer"></span>
1163
1163
  <div class="modal-title">Correct Your ITR Details</div>
1164
- <button class="icon-btn close-btn" type="button" aria-label="Close">${ec}</button>
1164
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${tc}</button>
1165
1165
  `;const r=this.shadow.querySelector(".modal-body"),s=this.schemas.map(o=>`
1166
- <button class="chip" type="button" data-section-id="${hf(o.id)}">
1166
+ <button class="chip" type="button" data-section-id="${mf(o.id)}">
1167
1167
  <span class="chip-icon">${o.icon??"📄"}</span>
1168
- <span class="chip-label">${tc(o.title)}</span>
1168
+ <span class="chip-label">${rc(o.title)}</span>
1169
1169
  </button>`).join("");r.innerHTML=`
1170
1170
  <div class="picker">
1171
1171
  <div class="intro-card">
@@ -1180,9 +1180,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1180
1180
  `;const n=this.shadow.querySelector(".modal-footer");n.style.display="",n.innerHTML=`
1181
1181
  <button class="primary-btn" type="button" data-action="recalculate">Save &amp; Recalculate</button>
1182
1182
  `,this.bindCommon(),r.querySelectorAll(".chip").forEach(o=>{o.addEventListener("click",()=>{const a=o.dataset.sectionId;a&&this.openSection(a)})}),n.querySelector('[data-action="recalculate"]')?.addEventListener("click",()=>this.handleRecalculate())}renderForm(){const e=this.shadow.querySelector(".modal");if(!e)return;e.classList.remove("view-picker"),e.classList.add("view-form");const t=this.schemas.find(n=>n.id===this.activeSectionId),r=this.shadow.querySelector(".modal-header");r.innerHTML=`
1183
- <button class="icon-btn back-btn" type="button" aria-label="Back">${df}</button>
1184
- <div class="modal-title">${tc(t?.title??"Edit")}</div>
1185
- <button class="icon-btn close-btn" type="button" aria-label="Close">${ec}</button>
1183
+ <button class="icon-btn back-btn" type="button" aria-label="Back">${pf}</button>
1184
+ <div class="modal-title">${rc(t?.title??"Edit")}</div>
1185
+ <button class="icon-btn close-btn" type="button" aria-label="Close">${tc}</button>
1186
1186
  `;const s=this.shadow.querySelector(".modal-footer");s.style.display="none",s.innerHTML="",this.bindCommon(),r.querySelector(".back-btn")?.addEventListener("click",()=>this.backToPicker()),this.mountActiveForm()}mountActiveForm(){const e=this.shadow.querySelector(".modal-body");if(!e)return;e.innerHTML="";const t=this.schemas.find(s=>s.id===this.activeSectionId);if(!t){e.innerHTML='<div class="empty">Section not found.</div>';return}const r=document.createElement("aikaara-schema-form");r.addEventListener("aikaara-form-submit",(s=>{const n=s.detail;this.handleSectionSubmit(n.sectionId,n.value)})),e.appendChild(r),requestAnimationFrame(()=>{r.setSchema(t),r.setValue(this.extractSlice(t))})}bindCommon(){this.shadow.querySelector(".close-btn")?.addEventListener("click",()=>this.close())}renderShell(){this.shadow.innerHTML=`
1187
1187
  <style>${this.css()}</style>
1188
1188
  <div class="backdrop" part="backdrop">
@@ -1321,7 +1321,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1321
1321
  border-radius: 16px 16px 0 0;
1322
1322
  }
1323
1323
  }
1324
- `}}const ec='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',df='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';function hf(i){return i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function tc(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class ff extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const s=this.getEntries(),n={...s[e]||{}};n[t]=r,s[e]=n,this.isRepeatable()?this.value=s:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=o=>{if(!o)return null;const a=t[o.field];return"equals"in o?a===o.equals:Array.isArray(o.in)?o.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],s=>{if(!this.fieldVisible(s,t)||s.type==="group")return;const n=t[s.id],o=`${r}.${s.id}`;if(s.required&&(n==null||n==="")){this.errors.set(o,"Required");return}if(s.type==="text"&&typeof n=="string"&&(s.pattern&&n&&!new RegExp(s.pattern).test(n)?this.errors.set(o,"Invalid format"):s.maxLength&&n.length>s.maxLength&&this.errors.set(o,`Max ${s.maxLength} characters`)),s.type==="textarea"&&typeof n=="string"&&s.maxLength&&n.length>s.maxLength&&this.errors.set(o,`Max ${s.maxLength} characters`),s.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=s;Number.isNaN(a)?this.errors.set(o,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(o,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(o,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((s,n)=>this.renderEntry(s,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1324
+ `}}const tc='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',pf='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>';function mf(i){return i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function rc(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}class gf extends HTMLElement{shadow;schema=null;value={};errors=new Map;collapsed=new Set;collapseSeeded=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setSchema(e){this.collapsed.clear(),this.collapseSeeded.clear(),this.schema=e,this.isRepeatable()&&!Array.isArray(this.value)?this.value=[]:!this.isRepeatable()&&Array.isArray(this.value)&&(this.value={}),this.render()}setValue(e){this.isRepeatable()?(this.value=Array.isArray(e)?[...e]:[],this.value.length===0&&this.value.push({})):this.value=e&&typeof e=="object"?{...e}:{},this.render()}isRepeatable(){return!!this.schema?.repeatable&&this.schema.repeatable.maxCount>0}getEntries(){return this.isRepeatable()?this.value:[this.value]}setEntry(e,t,r){this.setEntryNoRender(e,t,r),this.render()}setEntryNoRender(e,t,r){const s=this.getEntries(),n={...s[e]||{}};n[t]=r,s[e]=n,this.isRepeatable()?this.value=s:this.value=n}addEntry(){if(!this.isRepeatable()||!this.schema?.repeatable)return;const e=this.getEntries();e.length>=this.schema.repeatable.maxCount||(e.push({}),this.value=e,this.render())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.render())}fieldVisible(e,t){const r=o=>{if(!o)return null;const a=t[o.field];return"equals"in o?a===o.equals:Array.isArray(o.in)?o.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}validate(){return this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],s=>{if(!this.fieldVisible(s,t)||s.type==="group")return;const n=t[s.id],o=`${r}.${s.id}`;if(s.required&&(n==null||n==="")){this.errors.set(o,"Required");return}if(s.type==="text"&&typeof n=="string"&&(s.pattern&&n&&!new RegExp(s.pattern).test(n)?this.errors.set(o,"Invalid format"):s.maxLength&&n.length>s.maxLength&&this.errors.set(o,`Max ${s.maxLength} characters`)),s.type==="textarea"&&typeof n=="string"&&s.maxLength&&n.length>s.maxLength&&this.errors.set(o,`Max ${s.maxLength} characters`),s.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=s;Number.isNaN(a)?this.errors.set(o,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(o,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(o,`Maximum ${l.max.toLocaleString("en-IN")}`)}})}),this.errors.size===0}walkFields(e,t){for(const r of e)t(r),r.type==="group"&&this.walkFields(r.fields,t)}handleSubmit(){if(!this.schema)return;if(!this.validate()){this.render(),this.shadow.querySelector(".field.has-error")?.scrollIntoView({behavior:"smooth",block:"center"});return}const e=this.isRepeatable()?this.getEntries():this.value;this.dispatchEvent(new CustomEvent("aikaara-form-submit",{detail:{sectionId:this.schema.id,value:e},bubbles:!0,composed:!0}))}render(){if(!this.schema){this.shadow.innerHTML="<style>:host{display:block;}</style>";return}const e=this.getEntries(),t=e.map((s,n)=>this.renderEntry(s,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
1325
1325
  <style>${this.css()}</style>
1326
1326
  <div class="container">
1327
1327
  <div class="scroll">
@@ -1347,14 +1347,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1347
1347
  ${Qe(s)}
1348
1348
  </span>
1349
1349
  ${n}
1350
- </div>`:""}<div class="entry-body">${o}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const d=e,p=d.fields.map(g=>this.renderField(g,t,r)).join("");if(!d.collapsible)return`
1350
+ </div>`:""}<div class="entry-body">${o}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const d=e,p=d.fields.map(y=>this.renderField(y,t,r)).join("");if(!d.collapsible)return`
1351
1351
  <fieldset class="group">
1352
1352
  ${d.title?`<legend class="group-title">${Qe(d.title)}</legend>`:""}
1353
1353
  ${d.hint?`<div class="group-hint">${Qe(d.hint)}</div>`:""}
1354
1354
  <div class="group-body">${p}</div>
1355
- </fieldset>`;const y=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(y)&&(this.collapseSeeded.add(y),this.collapsed.add(y));const f=this.collapsed.has(y);return`
1355
+ </fieldset>`;const g=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(g)&&(this.collapseSeeded.add(g),this.collapsed.add(g));const f=this.collapsed.has(g);return`
1356
1356
  <fieldset class="group group--collapsible ${f?"is-collapsed":""}">
1357
- <button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${It(y)}" aria-expanded="${!f}">
1357
+ <button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${Ct(g)}" aria-expanded="${!f}">
1358
1358
  <span class="group-title">${Qe(d.title??"")}</span>
1359
1359
  <span class="group-chevron" aria-hidden="true"></span>
1360
1360
  </button>
@@ -1365,15 +1365,15 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1365
1365
  ${l}
1366
1366
  ${c}
1367
1367
  ${u}
1368
- </div>`}renderInput(e,t,r){const s=t[e.id],n=this.fieldHtmlId(e,r),o=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const a=e,l=a.readOnly?"input--readonly":"",c=a.readOnly?"disabled":"";return`<input type="text" class="input ${l}" id="${n}" ${o} value="${It(String(s??""))}" placeholder="${It(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""} ${c}/>`}if(e.type==="textarea"){const a=e;return`<textarea class="input textarea" id="${n}" ${o} rows="${a.rows??4}" placeholder="${It(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Qe(String(s??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Qe(a.currency)}</span>`:"",c=a.readOnly?"disabled":"",u=a.readOnly?"input--readonly":"";return`
1368
+ </div>`}renderInput(e,t,r){const s=t[e.id],n=this.fieldHtmlId(e,r),o=`data-field-id="${e.id}" data-entry-index="${r}"`;if(e.type==="text"){const a=e,l=a.readOnly?"input--readonly":"",c=a.readOnly?"disabled":"";return`<input type="text" class="input ${l}" id="${n}" ${o} value="${Ct(String(s??""))}" placeholder="${Ct(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""} ${c}/>`}if(e.type==="textarea"){const a=e;return`<textarea class="input textarea" id="${n}" ${o} rows="${a.rows??4}" placeholder="${Ct(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Qe(String(s??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Qe(a.currency)}</span>`:"",c=a.readOnly?"disabled":"",u=a.readOnly?"input--readonly":"";return`
1369
1369
  <div class="input-with-prefix">
1370
1370
  ${l}
1371
- <input type="number" class="input ${u}" id="${n}" ${o} value="${It(String(s??""))}" placeholder="${It(a.placeholder??"")}" ${a.min!==void 0?`min="${a.min}"`:""} ${a.max!==void 0?`max="${a.max}"`:""} ${c}/>
1372
- </div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${o} value="${It(String(s??""))}"/>`;if(e.type==="radio")return`
1371
+ <input type="number" class="input ${u}" id="${n}" ${o} value="${Ct(String(s??""))}" placeholder="${Ct(a.placeholder??"")}" ${a.min!==void 0?`min="${a.min}"`:""} ${a.max!==void 0?`max="${a.max}"`:""} ${c}/>
1372
+ </div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${o} value="${Ct(String(s??""))}"/>`;if(e.type==="radio")return`
1373
1373
  <div class="radio-group">
1374
1374
  ${e.options.map(l=>{const c=s===l.value?"checked":"",u=`${n}-${l.value}`;return`
1375
1375
  <label class="radio-item ${c?"selected":""}" for="${u}">
1376
- <input type="radio" id="${u}" ${o} name="${n}" value="${It(l.value)}" ${c}/>
1376
+ <input type="radio" id="${u}" ${o} name="${n}" value="${Ct(l.value)}" ${c}/>
1377
1377
  <span class="radio-label">${Qe(l.label)}</span>
1378
1378
  </label>`}).join("")}
1379
1379
  </div>`;if(e.type==="yes-no"){const a=s===!0?"checked":"",l=s===!1?"checked":"";return`
@@ -1596,7 +1596,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1596
1596
  }
1597
1597
  .save-btn:hover { filter: brightness(1.07); }
1598
1598
  .save-btn:active { filter: brightness(0.95); }
1599
- `}}function It(i){return i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ro(){const i=[["aikaara-chat-widget",Bl],["aikaara-chat-bubble",Dl],["aikaara-chat-header",Fl],["aikaara-message-list",Hl],["aikaara-message-bubble",Vl],["aikaara-chat-input",Gl],["aikaara-typing-indicator",Yl],["aikaara-streaming-message",Jl],["aikaara-error-banner",Ql],["aikaara-template-renderer",Gh],["aikaara-system-pill",Xh],["aikaara-option-list",Zh],["aikaara-submit-action",ef],["aikaara-modal-action",rf],["aikaara-text-input",nf],["aikaara-chat",of],["aikaara-link-modal",sf],["aikaara-compare-plans",cf],["aikaara-smart-edit-modal",uf],["aikaara-schema-form",ff]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Ro();function tn(i,e,t=""){if(!e)return t;const r=e.split(".");let s=i;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 rc(i){try{const e=i.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 Jt(i){return typeof i=="function"?await i():i}class nc{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=rc(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 Jt(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",o={method:n,headers:s};n==="POST"&&(s["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,o);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=tn(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const p=tn(l,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=tn(l,this.descriptor.fullNamePath??"data.fullName"),g=tn(l,this.descriptor.userPath??"data.userId"),b=rc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ic(i){const e={};for(const t of i.spec){const r=await pf(t,i.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 pf(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return mf(t);case"localStorage":return rn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return rn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return rn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return rn(()=>document.querySelector(`meta[name="${gf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function mf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function rn(i){try{return i()}catch{return}}function gf(i){return i.replace(/["\\]/g,"\\$&")}const yf=1800;class oc{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 ic({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 d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??yf;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 bf=3e4,vf=2e3,wf=100;async function sc(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:i.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=kf(r);if(!s)throw new Xe("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=_f(r);if(!s)throw new Xe("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=If(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:bf;return{token:await Af({type:r,key:s,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const s=xf(r);if(!s)throw new Xe("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 Xe("storage","storage.key not configured");const o=Sf(r,s,n);if(!o)throw new Xe("storage",`${r}Storage["${s}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:vf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:wf,o=await Ef(r,s,n);if(!o)throw new Xe("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class ac{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await sc(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 Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function kf(i){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===i)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function _f(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function xf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Sf(i,e,t){if(!(typeof window>"u"))try{const s=(i==="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 o=lc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Ef(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=lc(window,i);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 Af(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=o=>{if(i.origins.length>0&&!i.origins.includes(o.origin))return;const a=o.data;if(!a||typeof a!="object")return;const l=a;if(i.type&&l.type!==i.type)return;const c=l[i.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function If(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function lc(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Tf(){const i=typeof crypto<"u"?crypto:null;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const e=new Uint8Array(16);i.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 Cf="aikaara_chat:requestId";function Lo(i,e,t){const r=`${Cf}:${i}:${e}`;return t?`${r}:${t}`:r}function cc(i,e,t){try{return localStorage.getItem(Lo(i,e,t))}catch{return null}}function Pf(i,e,t,r){try{localStorage.setItem(Lo(i,e,r),t)}catch{}}function Of(i,e,t){try{localStorage.removeItem(Lo(i,e,t))}catch{}}async function No(i,e,t="before-chat"){const r=i.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const s={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(s[u]=d);typeof e.serviceType=="string"&&(s.serviceType=e.serviceType),typeof e.userType=="string"&&(s.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in s?s[p]:""),o=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(o);if(u&&typeof u=="object"){const d={};for(const[p,y]of Object.entries(u))d[p]=o(y);return d}return u},a=await Jt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),y=d.method??(d.body?"POST":"GET"),f={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",a)}const g={method:y,headers:f};d.body&&(f["content-type"]="application/json",g.body=JSON.stringify(o(d.body)));let b=0,w="",m=0,k=null;for(;;)try{const x=await fetch(p,g);if(x.ok){k=x;break}if(b=x.status,w=await x.text().catch(()=>""),m<c.length&&Rf(b,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${y} ${p} → ${b} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${y} ${p} → ${b} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(x){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,x),await new Promise(E=>setTimeout(E,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const E of d.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;d.capture.stripPrefix&&E.startsWith(d.capture.stripPrefix)&&(E=E.slice(d.capture.stripPrefix.length)),l[d.capture.as]=E,s[d.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${E.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Mf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await No(e,{sessionToken:i.sessionToken,userId:i.userId,projectId:i.projectId??"",slug:i.slug??"",identity:i.identity,serviceType:i.serviceType,userType:i.userType},"on-method-select")).captured:{}}function Rf(i,e){if(i===503||i===504||i===502)return!0;if(i===401||i===403)return e.trim().length===0;if(i===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function uc(i,e){const t=await fetch(i,{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 dc(i,e){return i.replace("{projectId}",e).replace("{uuid}",Tf().replace(/-/g,""))}function hc(i){const e=i._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=>Xl(r)))}async function fc(i){const e={...i.config??(i.configUrl?await uc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};hc(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=i.identity.userId,o=i.conversationScope||void 0,a=i.forceNewConversation?null:cc(n,s,o),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??dc(l,s);(i.conversationId||!a||i.forceNewConversation)&&s&&Pf(n,s,c,o);const u=await i.tokenProvider(),d=i.tokenProvider,p=i.historyTokenProvider??d,y=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:i.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,...i.identity.departmentId?{departmentId:i.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:i.identity.senderFullname??i.identity.userName,tokenProvider:d}:void 0,f=i.uploadAdapter??(e.uploadEndpoint?xo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),g=i.historyAdapter??(e.historyApiBase?Rl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),b={transport:t,baseUrl:"",userToken:i.userToken??n,conversationId:c,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:i.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,chatActions:e.chatActions,tiledesk:y,tiledeskIdentity:{userId:n,userName:i.identity.userName,departmentId:i.identity.departmentId,senderFullname:i.identity.senderFullname??i.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:g,onError:i.onError,onMessage:i.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(b),b.title&&w.setAttribute("title",b.title),b.primaryColor&&w.setAttribute("primary-color",b.primaryColor),b.display&&w.setAttribute("display",b.display),b.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),i.container.appendChild(w),{widget:w,requestId:c,config:b,destroy(){w.remove()}}}function Lf(i){if(typeof i!="string")return i;const e=document.querySelector(i);if(!e)throw new Error(`mountFromSlug: container "${i}" not found`);return e}async function pc(i){const e=(i.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(i.slug)}`;let r=null;try{r=await uc(t,i.configHeaders)}catch(A){if(!i.fallbackConfig)throw A;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${i.slug}" — using fallbackConfig.`,A)}const s={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(hc(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[A,C]of Object.entries(s.templates)){const O=`template:${A}`;s.components[O]||!C?.scriptUrl||!C?.render||(s.components[O]={kind:"iife-element",scriptUrl:C.scriptUrl,tag:C.render,...C.props?{props:C.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/${i.slug} descriptor must include "auth" block`);let o=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const p=await Jt(i.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&s.sso?.tokenSource){d=new ac({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:i.user.partnerToken});const A=await d.get();u=async()=>(await d.get()).token,i.user.identity&&!i.user.identity.partnerToken&&(i.user.identity.partnerToken=A.token)}else if(!y&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const A=`${e}/api/v1/projects/by-slug/${encodeURIComponent(i.slug)}/sso_exchange`;o=await new oc({descriptor:s.sso,providers:i.user.credentialProviders,exchangeUrl:A}).get(),a=o.extUid||a,l=l??o.displayName,c=o.userToken}let f="",g="";if(s.preflight&&s.preflight.length){const A=await No(s.preflight,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(A.captured.sessionToken){f=A.captured.sessionToken;const C=f;u=()=>C}A.captured.userId&&(a=A.captured.userId),A.captured.requestId&&(g=A.captured.requestId)}const b=new nc(s.auth,u);if(f){const A=s.tiledesk?.projectId??"",C=A?cc(a,A):null,O=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=C??(A?dc(O,A):"");b.prime(f,{requestId:j,fullName:l})}const w=await b.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,getSessionToken:()=>Jt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=d&&s.sso?.autoRefresh?async()=>{try{return await d.refresh(),b.reset(),(await b.get()).token}catch(A){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",A),null}}:null,x=s.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Jt(i.user.token)}`,E=i.hooks?.upload??(x&&x.mode==="presigned-3step"?Ml({...x,authHeader:v}):x&&x.mode==="direct"?xo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await fc({container:Lf(i.container),config:s,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:i.hooks?.history,conversationId:w.requestId||g||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async A=>A==="none"?null:A==="chat"?(await b.get()).token:Jt(i.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:s,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(A){const C=s.preflight;return!C||!C.length?{}:C.some(j=>j.trigger==="on-method-select")?(await No(C,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...A?.identity??{}},serviceType:A?.serviceType,userType:A?.userType},"on-method-select")).captured:{}}})}function Nf(i){Ro();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=i[r];n!=null&&e.setAttribute(s,String(n))}return e.configure(i),document.body.appendChild(e),e}function jf(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Uf="https://checkout.razorpay.com/v1/checkout.js";let cr=null;function ur(){return window}class mc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,s)=>{const n=r.name||"Open link",o=!!this.paidIdx[s];return`<button class="link${o?" paid":""}" data-i="${s}" type="button"${o?" disabled":""}><span class="lbl">${Bf(o?"Paid":n)}</span>`+(o?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const s=Number(r.dataset.i||0),n=e[s];n&&this.handleClick(s,n)})})}handleClick(e,t){const r=Df(t),s=ur().__aikaara_descriptor__,n=s?.partnerPayment,o=s?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!o?.keyId){zf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}$f(o.preferredBanksUrl,r,o.preferredBanksMethod,o.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Ff().then(()=>this.openRazorpay(e,r,o,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,s){qf(t,s).then(n=>{if(!n){Qt("Failed to generate payment link, please try again later");return}const o=(n.paymentStatus??"").toLowerCase();if(o==="paid"||o==="success"||o==="completed"){this.paidIdx[e]=!0,this.render(),Qt("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){Qt("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Hf(a);if(!u){window.open(a,"_blank"),Qt("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Wf(u,s.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{Qt(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),Qt("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,s){const n=ur(),o=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof o.mobile=="string"?a.prefill.contact=o.mobile:typeof o.phone=="string"&&(a.prefill.contact=o.phone),typeof o.email=="string"&&(a.prefill.email=o.email),typeof o.name=="string"?a.prefill.name=o.name:typeof o.userName=="string"&&(a.prefill.name=o.userName),Array.isArray(s)&&s.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:s}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Bf(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&amp;":e==="<"?"&lt;":"&gt;")}function Df(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),s=r.get("orderId")||r.get("order_id");if(s)return s}}catch{}return null}function Ff(){return typeof ur().Razorpay=="function"?Promise.resolve():cr||(cr=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Uf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{cr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),cr)}function $f(i,e,t,r){if(!i)return Promise.resolve([]);const s=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),o=ur().__aikaara_runtime__??{};return(typeof o.getSessionToken=="function"?o.getSessionToken():typeof o.getChatJwt=="function"?o.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:s,headers:c,credentials:"omit"};return s==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(p=>{if(typeof p=="string")return p;if(p&&typeof p=="object"){const y=p;return y.code||y.bankCode||y.bank_code||null}return null}).filter(p=>!!p)})}async function qf(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,s=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=ur().__aikaara_runtime__??{},o=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};o&&(a.Authorization=`Bearer ${o}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(s,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Hf(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),s=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${s},scrollbars=yes,resizable=yes`)}function Wf(i,e,t){let r=!1;function s(){clearInterval(a),window.removeEventListener("message",o)}function n(l){r||(r=!0,s(),l())}function o(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",o)}function Qt(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function zf(i,e){if(!i)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(i,e):window.open(i,"_blank","noopener,noreferrer")}function Vf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",mc)}const Kf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:mc,registerAikaaraPaymentLink:Vf},Symbol.toStringTag,{value:"Module"}));class gc 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=`
1599
+ `}}function Ct(i){return i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ro(){const i=[["aikaara-chat-widget",Dl],["aikaara-chat-bubble",Fl],["aikaara-chat-header",$l],["aikaara-message-list",Wl],["aikaara-message-bubble",Kl],["aikaara-chat-input",Yl],["aikaara-typing-indicator",Jl],["aikaara-streaming-message",Ql],["aikaara-error-banner",Xl],["aikaara-template-renderer",Qh],["aikaara-system-pill",tf],["aikaara-option-list",rf],["aikaara-submit-action",nf],["aikaara-modal-action",sf],["aikaara-text-input",af],["aikaara-chat",lf],["aikaara-link-modal",cf],["aikaara-compare-plans",hf],["aikaara-smart-edit-modal",ff],["aikaara-schema-form",gf]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Ro();function rn(i,e,t=""){if(!e)return t;const r=e.split(".");let s=i;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 nc(i){try{const e=i.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 Jt(i){return typeof i=="function"?await i():i}class ic{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=nc(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 Jt(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",o={method:n,headers:s};n==="POST"&&(s["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,o);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=rn(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const p=rn(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=rn(l,this.descriptor.fullNamePath??"data.fullName"),y=rn(l,this.descriptor.userPath??"data.userId"),b=nc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:f,userId:y,expiresAt:b},this.cache}}async function oc(i){const e={};for(const t of i.spec){const r=await yf(t,i.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 yf(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return bf(t);case"localStorage":return nn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nn(()=>document.querySelector(`meta[name="${vf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function bf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function nn(i){try{return i()}catch{return}}function vf(i){return i.replace(/["\\]/g,"\\$&")}const wf=1800;class sc{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 oc({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 d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??wf;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 kf=3e4,_f=2e3,Sf=100;async function ac(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:i.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=xf(r);if(!s)throw new Xe("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Ef(r);if(!s)throw new Xe("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=Pf(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:kf;return{token:await Cf({type:r,key:s,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const s=Af(r);if(!s)throw new Xe("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 Xe("storage","storage.key not configured");const o=If(r,s,n);if(!o)throw new Xe("storage",`${r}Storage["${s}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:_f,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Sf,o=await Tf(r,s,n);if(!o)throw new Xe("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class lc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await ac(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 Xe extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function xf(i){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===i)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Ef(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function Af(i){if(typeof document>"u")return;const e=encodeURIComponent(i),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===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function If(i,e,t){if(!(typeof window>"u"))try{const s=(i==="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 o=cc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Tf(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=cc(window,i);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 Cf(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=o=>{if(i.origins.length>0&&!i.origins.includes(o.origin))return;const a=o.data;if(!a||typeof a!="object")return;const l=a;if(i.type&&l.type!==i.type)return;const c=l[i.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Pf(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function cc(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function Of(){const i=typeof crypto<"u"?crypto:null;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const e=new Uint8Array(16);i.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 Mf="aikaara_chat:requestId";function No(i,e,t){const r=`${Mf}:${i}:${e}`;return t?`${r}:${t}`:r}function uc(i,e,t){try{return localStorage.getItem(No(i,e,t))}catch{return null}}function Lf(i,e,t,r){try{localStorage.setItem(No(i,e,r),t)}catch{}}function Rf(i,e,t){try{localStorage.removeItem(No(i,e,t))}catch{}}async function jo(i,e,t="before-chat"){const r=i.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const s={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(s[u]=d);typeof e.serviceType=="string"&&(s.serviceType=e.serviceType),typeof e.userType=="string"&&(s.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in s?s[p]:""),o=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(o);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=o(g);return d}return u},a=await Jt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),g=d.method??(d.body?"POST":"GET"),f={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const S=d.authHeaderTemplate??"Bearer {token}";f.authorization=S.replace("{token}",a)}const y={method:g,headers:f};d.body&&(f["content-type"]="application/json",y.body=JSON.stringify(o(d.body)));let b=0,w="",m=0,k=null;for(;;)try{const S=await fetch(p,y);if(S.ok){k=S;break}if(b=S.status,w=await S.text().catch(()=>""),m<c.length&&jf(b,w)){const x=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${b} (transient). Retry #${m} in ${x}ms.`),await new Promise(E=>setTimeout(E,x));continue}const v=`Preflight #${u} ${g} ${p} → ${b} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(S){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,S),await new Promise(x=>setTimeout(x,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,S);break}throw S}if(k&&d.capture&&d.capture.as)try{const S=await k.clone().text();let v=S;try{v=JSON.parse(S)}catch{}if(d.capture.path)for(const x of d.capture.path.split("."))if(v&&typeof v=="object"&&x in v)v=v[x];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let x=v;d.capture.stripPrefix&&x.startsWith(d.capture.stripPrefix)&&(x=x.slice(d.capture.stripPrefix.length)),l[d.capture.as]=x,s[d.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${x.slice(0,24)}…)`)}}catch(S){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,S)}}return{captured:l}}async function Nf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await jo(e,{sessionToken:i.sessionToken,userId:i.userId,projectId:i.projectId??"",slug:i.slug??"",identity:i.identity,serviceType:i.serviceType,userType:i.userType},"on-method-select")).captured:{}}function jf(i,e){if(i===503||i===504||i===502)return!0;if(i===401||i===403)return e.trim().length===0;if(i===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function dc(i,e){const t=await fetch(i,{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 hc(i,e){return i.replace("{projectId}",e).replace("{uuid}",Of().replace(/-/g,""))}function fc(i){const e=i._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=>Zl(r)))}async function pc(i){const e={...i.config??(i.configUrl?await dc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};fc(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=i.identity.userId,o=i.conversationScope||void 0,a=i.forceNewConversation?null:uc(n,s,o),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??hc(l,s);(i.conversationId||!a||i.forceNewConversation)&&s&&Lf(n,s,c,o);const u=await i.tokenProvider(),d=i.tokenProvider,p=i.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:i.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,...i.identity.departmentId?{departmentId:i.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:i.identity.senderFullname??i.identity.userName,tokenProvider:d}:void 0,f=i.uploadAdapter??(e.uploadEndpoint?xo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),y=i.historyAdapter??(e.historyApiBase?Rl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),b={transport:t,baseUrl:"",userToken:i.userToken??n,conversationId:c,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:i.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,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:i.identity.userName,departmentId:i.identity.departmentId,senderFullname:i.identity.senderFullname??i.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:y,onError:i.onError,onMessage:i.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(b),b.title&&w.setAttribute("title",b.title),b.primaryColor&&w.setAttribute("primary-color",b.primaryColor),b.display&&w.setAttribute("display",b.display),b.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),i.container.appendChild(w),{widget:w,requestId:c,config:b,destroy(){w.remove()}}}function Uf(i){if(typeof i!="string")return i;const e=document.querySelector(i);if(!e)throw new Error(`mountFromSlug: container "${i}" not found`);return e}async function mc(i){const e=(i.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(i.slug)}`;let r=null;try{r=await dc(t,i.configHeaders)}catch(I){if(!i.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${i.slug}" — using fallbackConfig.`,I)}const s={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(fc(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[I,O]of Object.entries(s.templates)){const C=`template:${I}`;s.components[C]||!O?.scriptUrl||!O?.render||(s.components[C]={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/${i.slug} descriptor must include "auth" block`);let o=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const p=await Jt(i.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&s.sso?.tokenSource){d=new lc({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:i.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,i.user.identity&&!i.user.identity.partnerToken&&(i.user.identity.partnerToken=I.token)}else if(!g&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(i.slug)}/sso_exchange`;o=await new sc({descriptor:s.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=o.extUid||a,l=l??o.displayName,c=o.userToken}let f="",y="";if(s.preflight&&s.preflight.length){const I=await jo(s.preflight,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(y=I.captured.requestId)}const b=new ic(s.auth,u);if(f){const I=s.tiledesk?.projectId??"",O=I?uc(a,I):null,C=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?hc(C,I):"");b.prime(f,{requestId:j,fullName:l})}const w=await b.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,getSessionToken:()=>Jt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=d&&s.sso?.autoRefresh?async()=>{try{return await d.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,S=s.upload,v=async()=>`Bearer ${S&&"tokenSource"in S&&S.tokenSource==="chat"?(await b.get()).token:await Jt(i.user.token)}`,x=i.hooks?.upload??(S&&S.mode==="presigned-3step"?Ll({...S,authHeader:v}):S&&S.mode==="direct"?xo({endpoint:S.endpoint,fieldName:S.fieldName,extraFields:S.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await pc({container:Uf(i.container),config:s,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:x,historyAdapter:i.hooks?.history,conversationId:w.requestId||y||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Jt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:s,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const O=s.preflight;return!O||!O.length?{}:O.some(j=>j.trigger==="on-method-select")?(await jo(O,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Bf(i){Ro();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=i[r];n!=null&&e.setAttribute(s,String(n))}return e.configure(i),document.body.appendChild(e),e}function Df(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Ff="https://checkout.razorpay.com/v1/checkout.js";let ur=null;function dr(){return window}class gc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,s)=>{const n=r.name||"Open link",o=!!this.paidIdx[s];return`<button class="link${o?" paid":""}" data-i="${s}" type="button"${o?" disabled":""}><span class="lbl">${$f(o?"Paid":n)}</span>`+(o?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const s=Number(r.dataset.i||0),n=e[s];n&&this.handleClick(s,n)})})}handleClick(e,t){const r=qf(t),s=dr().__aikaara_descriptor__,n=s?.partnerPayment,o=s?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!o?.keyId){t.openLinkInNewTab?window.open(t.url,"_blank","noopener,noreferrer"):Gf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}Wf(o.preferredBanksUrl,r,o.preferredBanksMethod,o.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Hf().then(()=>this.openRazorpay(e,r,o,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,s){zf(t,s).then(n=>{if(!n){Qt("Failed to generate payment link, please try again later");return}const o=(n.paymentStatus??"").toLowerCase();if(o==="paid"||o==="success"||o==="completed"){this.paidIdx[e]=!0,this.render(),Qt("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){Qt("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Vf(a);if(!u){window.open(a,"_blank"),Qt("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Kf(u,s.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{Qt(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),Qt("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,s){const n=dr(),o=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof o.mobile=="string"?a.prefill.contact=o.mobile:typeof o.phone=="string"&&(a.prefill.contact=o.phone),typeof o.email=="string"&&(a.prefill.email=o.email),typeof o.name=="string"?a.prefill.name=o.name:typeof o.userName=="string"&&(a.prefill.name=o.userName),Array.isArray(s)&&s.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:s}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function $f(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&amp;":e==="<"?"&lt;":"&gt;")}function qf(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),s=r.get("orderId")||r.get("order_id");if(s)return s}}catch{}return null}function Hf(){return typeof dr().Razorpay=="function"?Promise.resolve():ur||(ur=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Ff,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{ur=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),ur)}function Wf(i,e,t,r){if(!i)return Promise.resolve([]);const s=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),o=dr().__aikaara_runtime__??{};return(typeof o.getSessionToken=="function"?o.getSessionToken():typeof o.getChatJwt=="function"?o.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:s,headers:c,credentials:"omit"};return s==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(p=>{if(typeof p=="string")return p;if(p&&typeof p=="object"){const g=p;return g.code||g.bankCode||g.bank_code||null}return null}).filter(p=>!!p)})}async function zf(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,s=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=dr().__aikaara_runtime__??{},o=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};o&&(a.Authorization=`Bearer ${o}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(s,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Vf(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),s=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${s},scrollbars=yes,resizable=yes`)}function Kf(i,e,t){let r=!1;function s(){clearInterval(a),window.removeEventListener("message",o)}function n(l){r||(r=!0,s(),l())}function o(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",o)}function Qt(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function Gf(i,e){if(!i)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(i,e):window.open(i,"_blank","noopener,noreferrer")}function Yf(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",gc)}const Jf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:gc,registerAikaaraPaymentLink:Yf},Symbol.toStringTag,{value:"Module"}));class yc 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=`
1600
1600
  <style>
1601
1601
  :host { display: block; margin-top: 8px; }
1602
1602
  button {
@@ -1617,7 +1617,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1617
1617
  button[disabled] { opacity: 0.5; cursor: not-allowed; }
1618
1618
  </style>
1619
1619
  <button type="button" ${e?"":"disabled"}>
1620
- ${Gf(e?.name??"Open")}
1620
+ ${Qf(e?.name??"Open")}
1621
1621
  <span aria-hidden="true">↗</span>
1622
1622
  </button>
1623
- `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:s,orderId:n,extra:o,messageId:a}=this.payload,l=s?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:o,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(s)ql(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=Yf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:l,...o??{}},...a?{message_id:a}:{}}},bubbles:!0,composed:!0}))}}function Gf(i){return i.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Yf(){if(typeof document>"u")return null;let i=document.querySelector("aikaara-link-modal");if(!i){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),i=e}return i}function Jf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",gc)}const Qf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:gc,registerAikaaraLinkButton:Jf},Symbol.toStringTag,{value:"Module"}));return Me.ActionCableClient=sn,Me.AikaaraChatBubble=Dl,Me.AikaaraChatClient=Pl,Me.AikaaraChatHeader=Fl,Me.AikaaraChatInput=Gl,Me.AikaaraChatWidget=Bl,Me.AikaaraErrorBanner=Ql,Me.AikaaraMessageBubble=Vl,Me.AikaaraMessageList=Hl,Me.AikaaraStreamingMessage=Jl,Me.AikaaraTypingIndicator=Yl,Me.ApiClient=qo,Me.ChannelSubscription=Bo,Me.ConnectionManager=$o,Me.ConversationManager=Go,Me.EventEmitter=gr,Me.FormBridge=Jd,Me.MessageStore=Ho,Me.SessionAuthAdapter=nc,Me.SsoExchangeAdapter=oc,Me.TiledeskTransport=El,Me.TokenDiscoveryError=Xe,Me.TokenDiscoveryReader=ac,Me.clearPersistedConversationId=Of,Me.collectSsoCredentials=ic,Me.createFetchUploadAdapter=xo,Me.createPresigned3StepUploadAdapter=Ml,Me.createTiledeskHistoryAdapter=Rl,Me.discoverToken=sc,Me.extractTiledeskFileEnvelope=Tl,Me.inferTiledeskRole=Il,Me.isTiledeskSelfEcho=Al,Me.mount=Nf,Me.mountFromSlug=pc,Me.mountTenantWidget=fc,Me.parseTiledeskTemplate=ko,Me.registerComponents=Ro,Me.runMethodSelectPreflight=Mf,Me.unmount=jf,Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"}),Me})({});
1623
+ `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:s,orderId:n,extra:o,messageId:a}=this.payload,l=s?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:o,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(s)Hl(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=Xf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:l,...o??{}},...a?{message_id:a}:{}}},bubbles:!0,composed:!0}))}}function Qf(i){return i.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Xf(){if(typeof document>"u")return null;let i=document.querySelector("aikaara-link-modal");if(!i){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),i=e}return i}function Zf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",yc)}const ep=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:yc,registerAikaaraLinkButton:Zf},Symbol.toStringTag,{value:"Module"}));return Me.ActionCableClient=an,Me.AikaaraChatBubble=Fl,Me.AikaaraChatClient=Ol,Me.AikaaraChatHeader=$l,Me.AikaaraChatInput=Yl,Me.AikaaraChatWidget=Dl,Me.AikaaraErrorBanner=Xl,Me.AikaaraMessageBubble=Kl,Me.AikaaraMessageList=Wl,Me.AikaaraStreamingMessage=Ql,Me.AikaaraTypingIndicator=Jl,Me.ApiClient=Ho,Me.ChannelSubscription=Do,Me.ConnectionManager=qo,Me.ConversationManager=Yo,Me.EventEmitter=yr,Me.FormBridge=Qd,Me.MessageStore=Wo,Me.SessionAuthAdapter=ic,Me.SsoExchangeAdapter=sc,Me.TiledeskTransport=Al,Me.TokenDiscoveryError=Xe,Me.TokenDiscoveryReader=lc,Me.clearPersistedConversationId=Rf,Me.collectSsoCredentials=oc,Me.createFetchUploadAdapter=xo,Me.createPresigned3StepUploadAdapter=Ll,Me.createTiledeskHistoryAdapter=Rl,Me.discoverToken=ac,Me.extractTiledeskFileEnvelope=Cl,Me.inferTiledeskRole=Tl,Me.isTiledeskSelfEcho=Il,Me.mount=Bf,Me.mountFromSlug=mc,Me.mountTenantWidget=pc,Me.parseTiledeskTemplate=_o,Me.registerComponents=Ro,Me.runMethodSelectPreflight=Nf,Me.unmount=Df,Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"}),Me})({});