@aikaara/chat-sdk 1.5.10 → 1.5.12
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.
- package/dist/{AikaaraLinkButton-D8fSaZEy.cjs → AikaaraLinkButton-8s80ku63.cjs} +1 -1
- package/dist/{AikaaraLinkButton-JBlryxQu.mjs → AikaaraLinkButton-DLHFN3om.mjs} +1 -1
- package/dist/{AikaaraPaymentLink-CL4O6gbc.mjs → AikaaraPaymentLink-ZYn2r5t-.mjs} +1 -1
- package/dist/AikaaraPaymentLink-mK1C7vwW.cjs +1 -0
- package/dist/{MountTenant-JKJpnHQ4.cjs → MountTenant-AF0sGJUq.cjs} +59 -59
- package/dist/{MountTenant-BK9Zg0Gy.mjs → MountTenant-SRVHyGJ7.mjs} +4189 -4083
- package/dist/cdn/aikaara-chat.iife.js +48 -48
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
- package/dist/AikaaraPaymentLink-D_SZ081m.cjs +0 -1
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";class ia{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 pn{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 ia(t,i=>{this.send({command:"message",identifier:t,data:JSON.stringify(i)})});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((i,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>i(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 mo{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(i){console.error(`Error in event handler for "${e}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const Rc=1e3,Nc=10,Lc=400,jc=600,No="#6366f1",Uc=12,Dc="system-ui, -apple-system, sans-serif",Lo="Type a message...",Bc="bottom-right",Fc="light",$c={x:20,y:20},tn="aikaara_conversation_id";class oa extends mo{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 pn(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,i){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Nc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Rc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new pn(i),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const i=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${i}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class sa{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,i){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=i}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 i=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(i,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(i,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 s=await n.json();if(s&&typeof s=="object"&&"success"in s){if(!s.success)throw new Error(`API error: ${s.message||"Request failed"}`);return s.data}return s}async fetchWithHeaders(e,t,r){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey),this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:i};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class aa{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(i=>i.status==="sending"&&i.role===e.role&&i.content===e.content&&i.conversationId===e.conversationId&&Date.now()-new Date(i.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 i=jo(this._messages,e);return i?(Object.assign(i,e,{id:i.id}),{message:i,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(i=>i.externalId===e||i.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 i=jo(t,r);if(i){const n=Wr(i),s=Wr(r);!n&&s&&Object.assign(i,r,{id:i.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function jo(o,e,t=15e3){const r=e.attachments&&e.attachments[0],i=(e.metadata??{}).attributes;if(!(!!r||!!(i&&i.fileMessage)))return null;const s=Wr(e),a=Uo(e),l=Do(e);if(!s&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=o.length-1;u>=0;u--){const d=o[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=Wr(d);if(s&&y&&s===y)return d;const w=Uo(d);if(a&&w&&a===w)return d;const m=Do(d);if(l&&m&&l===m)return d}return null}function Uo(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=la(o);if(t)return t}function Do(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(o.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=o.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function Wr(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(o.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=la(o);if(r){const i=/[?&]cloudFileId=([^&]+)/.exec(r);if(i)return decodeURIComponent(i[1])}}function la(o){const e=o.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class ca{_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(tn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(tn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(tn,e)}catch{}}}var go=Object.defineProperty,qc=Object.getOwnPropertyDescriptor,Hc=Object.getOwnPropertyNames,Wc=Object.prototype.hasOwnProperty,Je=(o,e)=>()=>(o&&(e=o(o=0)),e),pe=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Gt=(o,e)=>{for(var t in e)go(o,t,{get:e[t],enumerable:!0})},zc=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hc(e))!Wc.call(o,i)&&i!==t&&go(o,i,{get:()=>e[i],enumerable:!(r=qc(e,i))||r.enumerable});return o},Ne=o=>zc(go({},"__esModule",{value:!0}),o),le=Je(()=>{}),Le={};Gt(Le,{_debugEnd:()=>Gn,_debugProcess:()=>Kn,_events:()=>ci,_eventsCount:()=>ui,_exiting:()=>Rn,_fatalExceptions:()=>Wn,_getActiveHandles:()=>ga,_getActiveRequests:()=>ma,_kill:()=>jn,_linkedBinding:()=>fa,_maxListeners:()=>li,_preload_modules:()=>si,_rawDebug:()=>Pn,_startProfilerIdleNotifier:()=>Yn,_stopProfilerIdleNotifier:()=>Jn,_tickCallback:()=>Vn,abort:()=>ei,addListener:()=>di,allowedNodeEnvironmentFlags:()=>qn,arch:()=>gn,argv:()=>vn,argv0:()=>oi,assert:()=>ba,binding:()=>Sn,browser:()=>Cn,chdir:()=>In,config:()=>Nn,cpuUsage:()=>nr,cwd:()=>An,debugPort:()=>ii,default:()=>yo,dlopen:()=>pa,domain:()=>Mn,emit:()=>gi,emitWarning:()=>xn,env:()=>yn,execArgv:()=>wn,execPath:()=>ni,exit:()=>Fn,features:()=>Hn,hasUncaughtExceptionCaptureCallback:()=>ya,hrtime:()=>vr,kill:()=>Bn,listeners:()=>wa,memoryUsage:()=>Dn,moduleLoadList:()=>On,nextTick:()=>da,off:()=>fi,on:()=>ut,once:()=>hi,openStdin:()=>$n,pid:()=>ti,platform:()=>bn,ppid:()=>ri,prependListener:()=>bi,prependOnceListener:()=>yi,reallyExit:()=>Ln,release:()=>Tn,removeAllListeners:()=>mi,removeListener:()=>pi,resourceUsage:()=>Un,setSourceMapsEnabled:()=>ai,setUncaughtExceptionCaptureCallback:()=>zn,stderr:()=>Xn,stdin:()=>Zn,stdout:()=>Qn,title:()=>mn,umask:()=>En,uptime:()=>va,version:()=>_n,versions:()=>kn});function bo(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function Vc(){!Lt||!Rt||(Lt=!1,Rt.length?st=Rt.concat(st):ar=-1,st.length&&ua())}function ua(){if(!Lt){var o=setTimeout(Vc,0);Lt=!0;for(var e=st.length;e;){for(Rt=st,st=[];++ar<e;)Rt&&Rt[ar].run();ar=-1,e=st.length}Rt=null,Lt=!1,clearTimeout(o)}}function da(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];st.push(new ha(o,e)),st.length===1&&!Lt&&setTimeout(ua,0)}function ha(o,e){this.fun=o,this.array=e}function He(){}function fa(o){bo("_linkedBinding")}function pa(o){bo("dlopen")}function ma(){return[]}function ga(){return[]}function ba(o,e){if(!o)throw new Error(e||"assertion error")}function ya(){return!1}function va(){return ht.now()/1e3}function vr(o){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return o&&(r=r-o[0],i=i-o[1],i<0&&(r--,i+=wr)),[r,i]}function ut(){return yo}function wa(o){return[]}var st,Lt,Rt,ar,mn,gn,bn,yn,vn,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,Pn,On,Mn,Rn,Nn,Ln,jn,nr,Un,Dn,Bn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,ht,rn,wr,li,ci,ui,di,hi,fi,pi,mi,gi,bi,yi,yo,Kc=Je(()=>{le(),ue(),ce(),st=[],Lt=!1,ar=-1,ha.prototype.run=function(){this.fun.apply(null,this.array)},mn="browser",gn="x64",bn="browser",yn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},vn=["/usr/bin/node"],wn=[],_n="v16.8.0",kn={},xn=function(o,e){console.warn((e?e+": ":"")+o)},Sn=function(o){bo("binding")},En=function(o){return 0},An=function(){return"/"},In=function(o){},Tn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Cn=!0,Pn=He,On=[],Mn={},Rn=!1,Nn={},Ln=He,jn=He,nr=function(){return{}},Un=nr,Dn=nr,Bn=He,Fn=He,$n=He,qn={},Hn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Wn=He,zn=He,Vn=He,Kn=He,Gn=He,Yn=He,Jn=He,Qn=void 0,Xn=void 0,Zn=void 0,ei=He,ti=2,ri=1,ni="/bin/usr/node",ii=9229,oi="node",si=[],ai=He,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(rn=Date.now(),ht.timing&&ht.timing.navigationStart&&(rn=ht.timing.navigationStart),ht.now=()=>Date.now()-rn),wr=1e9,vr.bigint=function(o){var e=vr(o);return typeof BigInt>"u"?e[0]*wr+e[1]:BigInt(e[0]*wr)+BigInt(e[1])},li=10,ci={},ui=0,di=ut,hi=ut,fi=ut,pi=ut,mi=ut,gi=He,bi=ut,yi=ut,yo={version:_n,versions:kn,arch:gn,platform:bn,browser:Cn,release:Tn,_rawDebug:Pn,moduleLoadList:On,binding:Sn,_linkedBinding:fa,_events:ci,_eventsCount:ui,_maxListeners:li,on:ut,addListener:di,once:hi,off:fi,removeListener:pi,removeAllListeners:mi,emit:gi,prependListener:bi,prependOnceListener:yi,listeners:wa,domain:Mn,_exiting:Rn,config:Nn,dlopen:pa,uptime:va,_getActiveRequests:ma,_getActiveHandles:ga,reallyExit:Ln,_kill:jn,cpuUsage:nr,resourceUsage:Un,memoryUsage:Dn,kill:Bn,exit:Fn,openStdin:$n,allowedNodeEnvironmentFlags:qn,assert:ba,features:Hn,_fatalExceptions:Wn,setUncaughtExceptionCaptureCallback:zn,hasUncaughtExceptionCaptureCallback:ya,emitWarning:xn,nextTick:da,_tickCallback:Vn,_debugProcess:Kn,_debugEnd:Gn,_startProfilerIdleNotifier:Yn,_stopProfilerIdleNotifier:Jn,stdout:Qn,stdin:Zn,stderr:Xn,abort:ei,umask:En,chdir:In,cwd:An,env:yn,title:mn,argv:vn,execArgv:wn,pid:ti,ppid:ri,execPath:ni,debugPort:ii,hrtime:vr,argv0:oi,_preload_modules:si,setSourceMapsEnabled:ai}}),ce=Je(()=>{Kc()});function Gc(){if(vi)return qt;vi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var o=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,n=r.length;i<n;++i)o[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function s(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=f);var y=b===f?0:4-b%4;return[b,y]}function a(g){var f=s(g),b=f[0],y=f[1];return(b+y)*3/4-y}function l(g,f,b){return(f+b)*3/4-b}function c(g){var f,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;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[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=f&255),m}function u(g){return o[g>>18&63]+o[g>>12&63]+o[g>>6&63]+o[g&63]}function d(g,f,b){for(var y,w=[],m=f;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function p(g){for(var f,b=g.length,y=b%3,w=[],m=16383,_=0,x=b-y;_<x;_+=m)w.push(d(g,_,_+m>x?x:_+m));return y===1?(f=g[b-1],w.push(o[f>>2]+o[f<<4&63]+"==")):y===2&&(f=(g[b-2]<<8)+g[b-1],w.push(o[f>>10]+o[f>>4&63]+o[f<<2&63]+"=")),w.join("")}return qt}function Yc(){return wi?ir:(wi=!0,ir.read=function(o,e,t,r,i){var n,s,a=i*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?i-1:0,p=t?-1:1,g=o[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+o[e+d],d+=p,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+o[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,r),n=n-c}return(g?-1:1)*s*Math.pow(2,n-r)},ir.write=function(o,e,t,r,i,n){var s,a,l,c=n*8-i-1,u=(1<<c)-1,d=u>>1,p=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,i),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;o[t+g]=a&255,g+=f,a/=256,i-=8);for(s=s<<i|a,c+=i;c>0;o[t+g]=s&255,g+=f,s/=256,c-=8);o[t+g-f]|=b*128},ir)}function Jc(){if(_i)return St;_i=!0;let o=Gc(),e=Yc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;St.Buffer=s,St.SlowBuffer=w,St.INSPECT_MAX_BYTES=50;let r=2147483647;St.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=i(),!s.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 i(){try{let h=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(h,k),h.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let k=new Uint8Array(h);return Object.setPrototypeOf(k,s.prototype),k}function s(h,k,A){if(typeof h=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,k,A)}s.poolSize=8192;function a(h,k,A){if(typeof h=="string")return d(h,k);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,k,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=h.valueOf&&h.valueOf();if(B!=null&&B!==h)return s.from(B,k,A);let X=b(h);if(X)return X;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return s.from(h[Symbol.toPrimitive]("string"),k,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}s.from=function(h,k,A){return a(h,k,A)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,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,k,A){return l(h),h<=0?n(h):k!==void 0?typeof A=="string"?n(h).fill(k,A):n(h).fill(k):n(h)}s.alloc=function(h,k,A){return c(h,k,A)};function u(h){return l(h),n(h<0?0:y(h)|0)}s.allocUnsafe=function(h){return u(h)},s.allocUnsafeSlow=function(h){return u(h)};function d(h,k){if((typeof k!="string"||k==="")&&(k="utf8"),!s.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(h,k)|0,B=n(A),X=B.write(h,k);return X!==A&&(B=B.slice(0,X)),B}function p(h){let k=h.length<0?0:y(h.length)|0,A=n(k);for(let B=0;B<k;B+=1)A[B]=h[B]&255;return A}function g(h){if(H(h,Uint8Array)){let k=new Uint8Array(h);return f(k.buffer,k.byteOffset,k.byteLength)}return p(h)}function f(h,k,A){if(k<0||h.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<k+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return k===void 0&&A===void 0?B=new Uint8Array(h):A===void 0?B=new Uint8Array(h,k):B=new Uint8Array(h,k,A),Object.setPrototypeOf(B,s.prototype),B}function b(h){if(s.isBuffer(h)){let k=y(h.length)|0,A=n(k);return A.length===0||h.copy(A,0,0,k),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 y(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),s.alloc(+h)}s.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==s.prototype},s.compare=function(h,k){if(H(h,Uint8Array)&&(h=s.from(h,h.offset,h.byteLength)),H(k,Uint8Array)&&(k=s.from(k,k.offset,k.byteLength)),!s.isBuffer(h)||!s.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===k)return 0;let A=h.length,B=k.length;for(let X=0,de=Math.min(A,B);X<de;++X)if(h[X]!==k[X]){A=h[X],B=k[X];break}return A<B?-1:B<A?1:0},s.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}},s.concat=function(h,k){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return s.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<h.length;++A)k+=h[A].length;let B=s.allocUnsafe(k),X=0;for(A=0;A<h.length;++A){let de=h[A];if(H(de,Uint8Array))X+de.length>B.length?(s.isBuffer(de)||(de=s.from(de)),de.copy(B,X)):Uint8Array.prototype.set.call(B,de,X);else if(s.isBuffer(de))de.copy(B,X);else throw new TypeError('"list" argument must be an Array of Buffers');X+=de.length}return B};function m(h,k){if(s.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,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let X=!1;for(;;)switch(k){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 B?-1:q(h).length;k=(""+k).toLowerCase(),X=!0}}s.byteLength=m;function _(h,k,A){let B=!1;if((k===void 0||k<0)&&(k=0),k>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,k>>>=0,A<=k))return"";for(h||(h="utf8");;)switch(h){case"hex":return W(this,k,A);case"utf8":case"utf-8":return $(this,k,A);case"ascii":return oe(this,k,A);case"latin1":case"binary":return K(this,k,A);case"base64":return T(this,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return re(this,k,A);default:if(B)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),B=!0}}s.prototype._isBuffer=!0;function x(h,k,A){let B=h[k];h[k]=h[A],h[A]=B}s.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 k=0;k<h;k+=2)x(this,k,k+1);return this},s.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 k=0;k<h;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},s.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 k=0;k<h;k+=8)x(this,k,k+7),x(this,k+1,k+6),x(this,k+2,k+5),x(this,k+3,k+4);return this},s.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?$(this,0,h):_.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(h){if(!s.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:s.compare(this,h)===0},s.prototype.inspect=function(){let h="",k=St.INSPECT_MAX_BYTES;return h=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(h+=" ... "),"<Buffer "+h+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(h,k,A,B,X){if(H(h,Uint8Array)&&(h=s.from(h,h.offset,h.byteLength)),!s.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(k===void 0&&(k=0),A===void 0&&(A=h?h.length:0),B===void 0&&(B=0),X===void 0&&(X=this.length),k<0||A>h.length||B<0||X>this.length)throw new RangeError("out of range index");if(B>=X&&k>=A)return 0;if(B>=X)return-1;if(k>=A)return 1;if(k>>>=0,A>>>=0,B>>>=0,X>>>=0,this===h)return 0;let de=X-B,ke=A-k,V=Math.min(de,ke),ie=this.slice(B,X),Ie=h.slice(k,A);for(let Te=0;Te<V;++Te)if(ie[Te]!==Ie[Te]){de=ie[Te],ke=Ie[Te];break}return de<ke?-1:ke<de?1:0};function v(h,k,A,B,X){if(h.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=X?0: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 k=="string"&&(k=s.from(k,B)),s.isBuffer(k))return k.length===0?-1:S(h,k,A,B,X);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?X?Uint8Array.prototype.indexOf.call(h,k,A):Uint8Array.prototype.lastIndexOf.call(h,k,A):S(h,[k],A,B,X);throw new TypeError("val must be string, number or Buffer")}function S(h,k,A,B,X){let de=1,ke=h.length,V=k.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(h.length<2||k.length<2)return-1;de=2,ke/=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<ke;Ie++)if(ie(h,Ie)===ie(k,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>ke&&(A=ke-V),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Pe=0;Pe<V;Pe++)if(ie(h,Ie+Pe)!==ie(k,Pe)){Te=!1;break}if(Te)return Ie}return-1}s.prototype.includes=function(h,k,A){return this.indexOf(h,k,A)!==-1},s.prototype.indexOf=function(h,k,A){return v(this,h,k,A,!0)},s.prototype.lastIndexOf=function(h,k,A){return v(this,h,k,A,!1)};function E(h,k,A,B){A=Number(A)||0;let X=h.length-A;B?(B=Number(B),B>X&&(B=X)):B=X;let de=k.length;B>de/2&&(B=de/2);let ke;for(ke=0;ke<B;++ke){let V=parseInt(k.substr(ke*2,2),16);if(me(V))return ke;h[A+ke]=V}return ke}function I(h,k,A,B){return ye(q(k,h.length-A),h,A,B)}function O(h,k,A,B){return ye(ee(k),h,A,B)}function C(h,k,A,B){return ye(fe(k),h,A,B)}function j(h,k,A,B){return ye(he(k,h.length-A),h,A,B)}s.prototype.write=function(h,k,A,B){if(k===void 0)B="utf8",A=this.length,k=0;else if(A===void 0&&typeof k=="string")B=k,A=this.length,k=0;else if(isFinite(k))k=k>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let X=this.length-k;if((A===void 0||A>X)&&(A=X),h.length>0&&(A<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return E(this,h,k,A);case"utf8":case"utf-8":return I(this,h,k,A);case"ascii":case"latin1":case"binary":return O(this,h,k,A);case"base64":return C(this,h,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,h,k,A);default:if(de)throw new TypeError("Unknown encoding: "+B);B=(""+B).toLowerCase(),de=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,k,A){return k===0&&A===h.length?o.fromByteArray(h):o.fromByteArray(h.slice(k,A))}function $(h,k,A){A=Math.min(h.length,A);let B=[],X=k;for(;X<A;){let de=h[X],ke=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&&(ke=de);break;case 2:ie=h[X+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(ke=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)&&(ke=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&&(ke=Pe))}}ke===null?(ke=65533,V=1):ke>65535&&(ke-=65536,B.push(ke>>>10&1023|55296),ke=56320|ke&1023),B.push(ke),X+=V}return U(B)}let D=4096;function U(h){let k=h.length;if(k<=D)return String.fromCharCode.apply(String,h);let A="",B=0;for(;B<k;)A+=String.fromCharCode.apply(String,h.slice(B,B+=D));return A}function oe(h,k,A){let B="";A=Math.min(h.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(h[X]&127);return B}function K(h,k,A){let B="";A=Math.min(h.length,A);for(let X=k;X<A;++X)B+=String.fromCharCode(h[X]);return B}function W(h,k,A){let B=h.length;(!k||k<0)&&(k=0),(!A||A<0||A>B)&&(A=B);let X="";for(let de=k;de<A;++de)X+=ve[h[de]];return X}function re(h,k,A){let B=h.slice(k,A),X="";for(let de=0;de<B.length-1;de+=2)X+=String.fromCharCode(B[de]+B[de+1]*256);return X}s.prototype.slice=function(h,k){let A=this.length;h=~~h,k=k===void 0?A:~~k,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<h&&(k=h);let B=this.subarray(h,k);return Object.setPrototypeOf(B,s.prototype),B};function F(h,k,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+k>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h],X=1,de=0;for(;++de<k&&(X*=256);)B+=this[h+de]*X;return B},s.prototype.readUintBE=s.prototype.readUIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h+--k],X=1;for(;k>0&&(X*=256);)B+=this[h+--k]*X;return B},s.prototype.readUint8=s.prototype.readUInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]|this[h+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]<<8|this[h+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},s.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=k+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(B)+(BigInt(X)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=k*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(B)<<BigInt(32))+BigInt(X)}),s.prototype.readIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=this[h],X=1,de=0;for(;++de<k&&(X*=256);)B+=this[h+de]*X;return X*=128,B>=X&&(B-=Math.pow(2,8*k)),B},s.prototype.readIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let B=k,X=1,de=this[h+--B];for(;B>0&&(X*=256);)de+=this[h+--B]*X;return X*=128,de>=X&&(de-=Math.pow(2,8*k)),de},s.prototype.readInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},s.prototype.readInt16LE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},s.prototype.readInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},s.prototype.readBigInt64LE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),s.prototype.readBigInt64BE=ae(function(h){h=h>>>0,J(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let B=(k<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(B)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A)}),s.prototype.readFloatLE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!0,23,4)},s.prototype.readFloatBE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!1,23,4)},s.prototype.readDoubleLE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!0,52,8)},s.prototype.readDoubleBE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!1,52,8)};function Z(h,k,A,B,X,de){if(!s.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(k>X||k<de)throw new RangeError('"value" argument is out of bounds');if(A+B>h.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(h,k,A,B){if(h=+h,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,h,k,A,ke,0)}let X=1,de=0;for(this[k]=h&255;++de<A&&(X*=256);)this[k+de]=h/X&255;return k+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(h,k,A,B){if(h=+h,k=k>>>0,A=A>>>0,!B){let ke=Math.pow(2,8*A)-1;Z(this,h,k,A,ke,0)}let X=A-1,de=1;for(this[k+X]=h&255;--X>=0&&(de*=256);)this[k+X]=h/de&255;return k+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,1,255,0),this[k]=h&255,k+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,65535,0),this[k]=h&255,this[k+1]=h>>>8,k+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,65535,0),this[k]=h>>>8,this[k+1]=h&255,k+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,4,4294967295,0),this[k+3]=h>>>24,this[k+2]=h>>>16,this[k+1]=h>>>8,this[k]=h&255,k+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,4,4294967295,0),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4};function M(h,k,A,B,X){Y(k,B,X,h,A,7);let de=Number(k&BigInt(4294967295));h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,A}function Q(h,k,A,B,X){Y(k,B,X,h,A,7);let de=Number(k&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 ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A+3]=ke,ke=ke>>8,h[A+2]=ke,ke=ke>>8,h[A+1]=ke,ke=ke>>8,h[A]=ke,A+8}s.prototype.writeBigUInt64LE=ae(function(h,k=0){return M(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(h,k=0){return Q(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(h,k,A,B){if(h=+h,k=k>>>0,!B){let V=Math.pow(2,8*A-1);Z(this,h,k,A,V-1,-V)}let X=0,de=1,ke=0;for(this[k]=h&255;++X<A&&(de*=256);)h<0&&ke===0&&this[k+X-1]!==0&&(ke=1),this[k+X]=(h/de>>0)-ke&255;return k+A},s.prototype.writeIntBE=function(h,k,A,B){if(h=+h,k=k>>>0,!B){let V=Math.pow(2,8*A-1);Z(this,h,k,A,V-1,-V)}let X=A-1,de=1,ke=0;for(this[k+X]=h&255;--X>=0&&(de*=256);)h<0&&ke===0&&this[k+X+1]!==0&&(ke=1),this[k+X]=(h/de>>0)-ke&255;return k+A},s.prototype.writeInt8=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,1,127,-128),h<0&&(h=255+h+1),this[k]=h&255,k+1},s.prototype.writeInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,32767,-32768),this[k]=h&255,this[k+1]=h>>>8,k+2},s.prototype.writeInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,2,32767,-32768),this[k]=h>>>8,this[k+1]=h&255,k+2},s.prototype.writeInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,4,2147483647,-2147483648),this[k]=h&255,this[k+1]=h>>>8,this[k+2]=h>>>16,this[k+3]=h>>>24,k+4},s.prototype.writeInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||Z(this,h,k,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4},s.prototype.writeBigInt64LE=ae(function(h,k=0){return M(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(h,k=0){return Q(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(h,k,A,B,X,de){if(A+B>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(h,k,A,B,X){return k=+k,A=A>>>0,X||be(h,k,A,4),e.write(h,k,A,B,23,4),A+4}s.prototype.writeFloatLE=function(h,k,A){return te(this,h,k,!0,A)},s.prototype.writeFloatBE=function(h,k,A){return te(this,h,k,!1,A)};function we(h,k,A,B,X){return k=+k,A=A>>>0,X||be(h,k,A,8),e.write(h,k,A,B,52,8),A+8}s.prototype.writeDoubleLE=function(h,k,A){return we(this,h,k,!0,A)},s.prototype.writeDoubleBE=function(h,k,A){return we(this,h,k,!1,A)},s.prototype.copy=function(h,k,A,B){if(!s.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),k>=h.length&&(k=h.length),k||(k=0),B>0&&B<A&&(B=A),B===A||h.length===0||this.length===0)return 0;if(k<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),h.length-k<B-A&&(B=h.length-k+A);let X=B-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,B):Uint8Array.prototype.set.call(h,this.subarray(A,B),k),X},s.prototype.fill=function(h,k,A,B){if(typeof h=="string"){if(typeof k=="string"?(B=k,k=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!s.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(h.length===1){let de=h.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(k<0||this.length<k||this.length<A)throw new RangeError("Out of range index");if(A<=k)return this;k=k>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let X;if(typeof h=="number")for(X=k;X<A;++X)this[X]=h;else{let de=s.isBuffer(h)?h:s.from(h,B),ke=de.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(X=0;X<A-k;++X)this[X+k]=de[X%ke]}return this};let G={};function L(h,k,A){G[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}L("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(h,k){return`The "${h}" argument must be of type number. Received type ${typeof k}`},TypeError),L("ERR_OUT_OF_RANGE",function(h,k,A){let B=`The value of "${h}" is out of range.`,X=A;return Number.isInteger(A)&&Math.abs(A)>2**32?X=ne(String(A)):typeof A=="bigint"&&(X=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(X=ne(X)),X+="n"),B+=` It must be ${k}. Received ${X}`,B},RangeError);function ne(h){let k="",A=h.length,B=h[0]==="-"?1:0;for(;A>=B+4;A-=3)k=`_${h.slice(A-3,A)}${k}`;return`${h.slice(0,A)}${k}`}function z(h,k,A){J(k,"offset"),(h[k]===void 0||h[k+A]===void 0)&&ge(k,h.length-(A+1))}function Y(h,k,A,B,X,de){if(h>A||h<k){let ke=typeof k=="bigint"?"n":"",V;throw k===0||k===BigInt(0)?V=`>= 0${ke} and < 2${ke} ** ${(de+1)*8}${ke}`:V=`>= -(2${ke} ** ${(de+1)*8-1}${ke}) and < 2 ** ${(de+1)*8-1}${ke}`,new G.ERR_OUT_OF_RANGE("value",V,h)}z(B,X,de)}function J(h,k){if(typeof h!="number")throw new G.ERR_INVALID_ARG_TYPE(k,"number",h)}function ge(h,k,A){throw Math.floor(h)!==h?(J(h,A),new G.ERR_OUT_OF_RANGE("offset","an integer",h)):k<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,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,k){k=k||1/0;let A,B=h.length,X=null,de=[];for(let ke=0;ke<B;++ke){if(A=h.charCodeAt(ke),A>55295&&A<57344){if(!X){if(A>56319){(k-=3)>-1&&de.push(239,191,189);continue}else if(ke+1===B){(k-=3)>-1&&de.push(239,191,189);continue}X=A;continue}if(A<56320){(k-=3)>-1&&de.push(239,191,189),X=A;continue}A=(X-55296<<10|A-56320)+65536}else X&&(k-=3)>-1&&de.push(239,191,189);if(X=null,A<128){if((k-=1)<0)break;de.push(A)}else if(A<2048){if((k-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((k-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((k-=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 k=[];for(let A=0;A<h.length;++A)k.push(h.charCodeAt(A)&255);return k}function he(h,k){let A,B,X,de=[];for(let ke=0;ke<h.length&&!((k-=2)<0);++ke)A=h.charCodeAt(ke),B=A>>8,X=A%256,de.push(X),de.push(B);return de}function fe(h){return o.toByteArray(R(h))}function ye(h,k,A,B){let X;for(X=0;X<B&&!(X+A>=k.length||X>=h.length);++X)k[X+A]=h[X];return X}function H(h,k){return h instanceof k||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===k.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",k=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let X=0;X<16;++X)k[B+X]=h[A]+h[X]}return k})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return St}var qt,vi,ir,wi,St,_i,Qc=Je(()=>{le(),ue(),ce(),qt={},vi=!1,ir={},wi=!1,St={},_i=!1}),Fe={};Gt(Fe,{Buffer:()=>zr,INSPECT_MAX_BYTES:()=>_a,default:()=>dt,kMaxLength:()=>ka});var dt,zr,_a,ka,$e=Je(()=>{le(),ue(),ce(),Qc(),dt=Jc(),dt.Buffer,dt.SlowBuffer,dt.INSPECT_MAX_BYTES,dt.kMaxLength,zr=dt.Buffer,_a=dt.INSPECT_MAX_BYTES,ka=dt.kMaxLength}),ue=Je(()=>{$e()}),De=pe((o,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 i="";for(let n=0;n<r.length;n++)i+=` ${r[n].stack}
|
|
2
|
-
`;super(i),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,i){return r.includes(i)},ArrayPrototypeIndexOf(r,i){return r.indexOf(i)},ArrayPrototypeJoin(r,i){return r.join(i)},ArrayPrototypeMap(r,i){return r.map(i)},ArrayPrototypePop(r,i){return r.pop(i)},ArrayPrototypePush(r,i){return r.push(i)},ArrayPrototypeSlice(r,i,n){return r.slice(i,n)},Error,FunctionPrototypeCall(r,i,...n){return r.call(i,...n)},FunctionPrototypeSymbolHasInstance(r,i){return Function.prototype[Symbol.hasInstance].call(r,i)},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,i){return Object.defineProperties(r,i)},ObjectDefineProperty(r,i,n){return Object.defineProperty(r,i,n)},ObjectGetOwnPropertyDescriptor(r,i){return Object.getOwnPropertyDescriptor(r,i)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,i){return Object.setPrototypeOf(r,i)},Promise,PromisePrototypeCatch(r,i){return r.catch(i)},PromisePrototypeThen(r,i,n){return r.then(i,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,i){return r.test(i)},SafeSet:Set,String,StringPrototypeSlice(r,i,n){return r.slice(i,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,i,n){return r.set(i,n)},Boolean,Uint8Array}}),xa=pe((o,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[i,n]){let s=r.shift();return n==="f"?s.toFixed(6):n==="j"?JSON.stringify(s):n==="s"&&typeof s=="object"?`${s.constructor!==Object?s.constructor.name:""} {}`.trim():s.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((o,e)=>{le(),ue(),ce();var{format:t,inspect:r}=xa(),{AggregateError:i}=De(),n=globalThis.AggregateError||i,s=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,_){if(!m)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(m){let _="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)_=`_${m.slice(x-3,x)}${_}`;return`${m.slice(0,x)}${_}`}function g(m,_,x){if(typeof _=="function")return d(_.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${_.length}).`),_(...x);let v=(_.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?_:t(_,...x)}function f(m,_,x){x||(x=Error);class v extends x{constructor(...E){super(g(m,_,E))}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[s]=!0,u[m]=v}function b(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function y(m,_){if(m&&_&&m!==_){if(Array.isArray(_.errors))return _.errors.push(m),_;let x=new n([_,m],_.message);return x.code=_.code,x}return m||_}var w=class extends Error{constructor(m="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(m,_),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,_,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let S=[],E=[],I=[];for(let C of _)d(typeof C=="string","All expected entries have to be of type string"),a.includes(C)?S.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=S.indexOf("object");C!==-1&&(S.splice(S,C,1),E.push("Object"))}if(S.length>0){switch(S.length){case 1:v+=`of type ${S[0]}`;break;case 2:v+=`one of type ${S[0]} or ${S[1]}`;break;default:{let C=S.pop();v+=`one of type ${S.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(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var O;if((O=x.constructor)!==null&&O!==void 0&&O.name)v+=`. Received an instance of ${x.constructor.name}`;else{let C=r(x,{depth:-1});v+=`. Received ${C}`}}else{let C=r(x,{colors:!1});C.length>25&&(C=`${C.slice(0,25)}...`),v+=`. Received type ${typeof x} (${C})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,_,x="is invalid")=>{let v=r(_);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,_,x)=>{var v;let S=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 "${_}" function but got ${S}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let _,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:_+=`The ${m[0]} argument`;break;case 2:_+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();_+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,_,x)=>{d(_,'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 S=BigInt(2)**BigInt(32);(x>S||x<-S)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${_}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),cr=pe((o,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}),It={};Gt(It,{EventEmitter:()=>Sa,default:()=>Ht,defaultMaxListeners:()=>Ea,init:()=>Aa,listenerCount:()=>Ia,on:()=>Ta,once:()=>Ca});function Xc(){if(ki)return or;ki=!0;var o=typeof Reflect=="object"?Reflect:null,e=o&&typeof o.apply=="function"?o.apply:function(x,v,S){return Function.prototype.apply.call(x,v,S)},t;o&&typeof o.ownKeys=="function"?t=o.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 i=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}or=n,or.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var s=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 s},set:function(x){if(typeof x!="number"||x<0||i(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");s=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||i(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=[],S=1;S<arguments.length;S++)v.push(arguments[S]);var E=x==="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[x];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,$=f(j,T),S=0;S<T;++S)e($[S],this,v);return!0};function c(x,v,S,E){var I,O,C;if(a(S),O=x._events,O===void 0?(O=x._events=Object.create(null),x._eventsCount=0):(O.newListener!==void 0&&(x.emit("newListener",v,S.listener?S.listener:S),O=x._events),C=O[v]),C===void 0)C=O[v]=S,++x._eventsCount;else if(typeof C=="function"?C=O[v]=E?[S,C]:[C,S]:E?C.unshift(S):C.push(S),I=l(x),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=x,j.type=v,j.count=C.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,S){var E={fired:!1,wrapFn:void 0,target:x,type:v,listener:S},I=u.bind(E);return I.listener=S,E.wrapFn=I,I}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 S,E,I,O,C;if(a(v),E=this._events,E===void 0)return this;if(S=E[x],S===void 0)return this;if(S===v||S.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[x],E.removeListener&&this.emit("removeListener",x,S.listener||v));else if(typeof S!="function"){for(I=-1,O=S.length-1;O>=0;O--)if(S[O]===v||S[O].listener===v){C=S[O].listener,I=O;break}if(I<0)return this;I===0?S.shift():b(S,I),S.length===1&&(E[x]=S[0]),E.removeListener!==void 0&&this.emit("removeListener",x,C||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,S,E;if(S=this._events,S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[x]),this;if(arguments.length===0){var I=Object.keys(S),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=S[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(x,v[E]);return this};function p(x,v,S){var E=x._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?y(I):f(I,I.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var S=v[x];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var S=new Array(v),E=0;E<v;++E)S[E]=x[E];return S}function b(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),S=0;S<v.length;++S)v[S]=x[S].listener||x[S];return v}function w(x,v){return new Promise(function(S,E){function I(C){x.removeListener(v,O),E(C)}function O(){typeof x.removeListener=="function"&&x.removeListener("error",I),S([].slice.call(arguments))}_(x,v,O,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,S){typeof x.on=="function"&&_(x,"error",v,S)}function _(x,v,S,E){if(typeof x.on=="function")E.once?x.once(v,S):x.on(v,S);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(O){E.once&&x.removeEventListener(v,I),S(O)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return or}var or,ki,Ht,Sa,Ea,Aa,Ia,Ta,Ca,Ut=Je(()=>{le(),ue(),ce(),or={},ki=!1,Ht=Xc(),Ht.once,Ht.once=function(o,e){return new Promise((t,r)=>{function i(...s){n!==void 0&&o.removeListener("error",n),t(s)}let n;e!=="error"&&(n=s=>{o.removeListener(name,i),r(s)},o.once("error",n)),o.once(e,i)})},Ht.on=function(o,e){let t=[],r=[],i=null,n=!1,s={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(i){let u=Promise.reject(i);return i=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){o.removeListener(e,a),o.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){i=c,o.removeListener(e,a),o.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return o.on(e,a),o.on("error",l),s;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):i=c,s.return()}},{EventEmitter:Sa,defaultMaxListeners:Ea,init:Aa,listenerCount:Ia,on:Ta,once:Ca}=Ht}),Ye=pe((o,e)=>{le(),ue(),ce();var t=($e(),Ne(Fe)),{format:r,inspect:i}=xa(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=De(),c=globalThis.AbortSignal||cr().AbortSignal,u=globalThis.AbortController||cr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},f=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,_)=>{y=m,w=_}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:i,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Ut(),Ne(It)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(_=>{f(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),dr=pe((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:i,ArrayPrototypeMap:n,NumberIsInteger:s,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:b}=De(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:S}=Ye(),{isAsyncFunction:E,isArrayBufferView:I}=Ye().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 D(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new _(me,H,$);H=u(H,8)}return K(H,me),H}var U=y((H,me,ve=c,ae=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!s(H))throw new x(me,"an integer",H);if(H<ve||H>ae)throw new x(me,`>= ${ve} && <= ${ae}`,H)}),oe=y((H,me,ve=-2147483648,ae=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!s(H))throw new x(me,"an integer",H);if(H<ve||H>ae)throw new x(me,`>= ${ve} && <= ${ae}`,H)}),K=y((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!s(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 F=y((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+i(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:g(Oe)),", ");throw new _(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=y((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)}),be=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),te=y((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let ae=`must be longer than ${ve}`;throw new _(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 L(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=y((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function Y(H,me){let ve=S(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new _("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"&&b(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ge=y((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),se=y((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=y((H,me)=>{if(typeof H!="function"||E(H))throw new m(me,"Function",H)}),q=y((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function ee(H,me,ve){if(!r(ve,H))throw new m(me,`('${i(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(he,H))throw new _(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let ae=0;ae<me;ae++){let Oe=H[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new _("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:C,isUint32:j,parseFileMode:D,validateArray:te,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:L,validateBoolean:Z,validateBuffer:z,validateDictionary:be,validateEncoding:Y,validateFunction:se,validateInt32:oe,validateInteger:U,validateNumber:re,validateObject:Q,validateOneOf:F,validatePlainFunction:R,validatePort:J,validateSignalName:ne,validateString:W,validateUint32:K,validateUndefined:q,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Dt=pe((o,e)=>{le(),ue(),ce();var t=e.exports={},r,i;function n(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?i=clearTimeout:i=s}catch{i=s}})();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(i===clearTimeout)return clearTimeout(w);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(w);try{return i(w)}catch{try{return i.call(null,w)}catch{return i.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 _=1;_<arguments.length;_++)m[_-1]=arguments[_];c.push(new b(w,m)),c.length===1&&!u&&a(f)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(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}}),bt=pe((o,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:i}=De(),n=i("nodejs.stream.destroyed"),s=i("nodejs.stream.errored"),a=i("nodejs.stream.readable"),l=i("nodejs.stream.writable"),c=i("nodejs.stream.disturbed"),u=i("nodejs.webstream.isClosedPromise"),d=i("nodejs.webstream.controllerErrorFunction");function p(M,Q=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!Q||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function 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 b(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!b(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!b(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!b(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(M){return y(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(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;return!!(M.destroyed||M[n]||te!=null&&te.destroyed)}function S(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 be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||Q===!1&&be.ended===!0&&be.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 be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||Q===!1&&be.ended===!0&&be.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&&!S(M)}function T(M,Q){return b(M)?v(M)?!0:!(Q?.readable!==!1&&C(M)||Q?.writable!==!1&&j(M)):null}function $(M){var Q,be;return b(M)?M.writableErrored?M.writableErrored:(Q=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function D(M){var Q,be;return b(M)?M.readableErrored?M.readableErrored:(Q=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&Q!==void 0?Q:null:null}function U(M){if(!b(M))return null;if(typeof M.closed=="boolean")return M.closed;let Q=M._writableState,be=M._readableState;return typeof Q?.closed=="boolean"||typeof be?.closed=="boolean"?Q?.closed||be?.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(!b(M))return null;let Q=M._writableState,be=M._readableState,te=Q||be;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,be,te,we,G,L,ne,z,Y,J;return!!(M&&((Q=(be=(te=(we=(G=(L=M[s])!==null&&L!==void 0?L: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&&be!==void 0?be:(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:s,isReadable:C,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:O,isReadableErrored:D,isNodeStream:b,isWebStream:_,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:S,isWritableFinished:E,isWritableErrored:$,isServerRequest:W,isServerResponse:K,willEmitClose:re,isTransformStream:m}}),Tt=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{AbortError:r,codes:i}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=i,{kEmptyObject:a,once:l}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=dr(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:b}=De(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:S,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:O,isWritableErrored:C,isNodeStream:j,willEmitClose:T,kIsClosedPromise:$}=bt(),D;function U(F){return F.setHeader&&typeof F.abort=="function"}var oe=()=>{};function K(F,Z,M){var Q,be;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),_(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=(be=Z.writable)!==null&&be!==void 0?be:E(F),G=F._writableState,L=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=x(F,!1),se=()=>{ge=!0,F.destroyed&&(z=!1),!(z&&(!F.writable||we))&&(!we||Y)&&M.call(F)},R=H=>{M.call(F,H)},q=y(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)&&!x(F,!1))return M.call(F,new s);if(we&&!Y&&!O(F,!1))return M.call(F,new s);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",R),F.on("close",ee),q?t.nextTick(ee):G!=null&&G.errorEmitted||L!=null&&L.errorEmitted?z||t.nextTick(he):(!te&&(!z||w(F))&&(Y||S(F)===!1)||!we&&(!z||S(F))&&(ge||w(F)===!1)||L&&F.req&&F.aborted)&&t.nextTick(he);let ye=()=>{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",R),F.removeListener("close",ee)};if(Z.signal&&!q){let H=()=>{let me=M;ye(),me.call(F,new r(void 0,{cause:Z.signal.reason}))};if(Z.signal.aborted)t.nextTick(H);else{D=D||Ye().addAbortListener;let me=D(Z.signal,H),ve=M;M=l((...ae)=>{me[b](),ve.apply(F,ae)})}}return ye}function W(F,Z,M){let Q=!1,be=oe;if(Z.signal)if(be=()=>{Q=!0,M.call(F,new r(void 0,{cause:Z.signal.reason}))},Z.signal.aborted)t.nextTick(be);else{D=D||Ye().addAbortListener;let we=D(Z.signal,be),G=M;M=l((...L)=>{we[b](),G.apply(F,L)})}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((be,te)=>{let we=K(F,Z,G=>{Q&&we(),G?te(G):be()})})}e.exports=K,e.exports.finished=re}),Yt=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:i},AbortError:n}=Ke(),{Symbol:s}=De(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=bt(),d=s("kDestroy"),p=s("kConstruct");function g(T,$,D){T&&(T.stack,$&&!$.errored&&($.errored=T),D&&!D.errored&&(D.errored=T))}function f(T,$){let D=this._readableState,U=this._writableState,oe=U||D;return U!=null&&U.destroyed||D!=null&&D.destroyed?(typeof $=="function"&&$(),this):(g(T,U,D),U&&(U.destroyed=!0),D&&(D.destroyed=!0),oe.constructed?b(this,T,$):this.once(d,function(K){b(this,r(K,T),$)}),this)}function b(T,$,D){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 D=="function"&&D(K),K?t.nextTick(y,T,K):t.nextTick(w,T)}try{T._destroy($||null,oe)}catch(K){oe(K)}}function y(T,$){m(T,$),w(T)}function w(T){let $=T._readableState,D=T._writableState;D&&(D.closeEmitted=!0),$&&($.closeEmitted=!0),(D!=null&&D.emitClose||$!=null&&$.emitClose)&&T.emit("close")}function m(T,$){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",$))}function _(){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 x(T,$,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($):$&&($.stack,oe&&!oe.errored&&(oe.errored=$),U&&!U.errored&&(U.errored=$),D?t.nextTick(m,T,$):m(T,$))}function v(T,$){if(typeof T._construct!="function")return;let D=T._readableState,U=T._writableState;D&&(D.constructed=!1),U&&(U.constructed=!1),T.once(p,$),!(T.listenerCount(p)>1)&&t.nextTick(S,T)}function S(T){let $=!1;function D(U){if($){x(T,U??new i);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?x(T,U,!0):t.nextTick(E,T)}try{T._construct(U=>{t.nextTick(D,U)})}catch(U){t.nextTick(D,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:_,errorOrDestroy:x}}),vo=pe((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=De(),{EventEmitter:i}=(Ut(),Ne(It));function n(a){i.call(this,a)}r(n.prototype,i.prototype),r(n,i),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 b(w){y(),i.listenerCount(this,"error")===0&&this.emit("error",w)}s(c,"error",b),s(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function s(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:s}}),Gr=pe((o,e)=>{le(),ue(),ce();var{SymbolDispose:t}=De(),{AbortError:r,codes:i}=Ke(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=bt(),l=Tt(),{ERR_INVALID_ARG_TYPE:c}=i,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)&&!s(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||Ye().addAbortListener;let b=u(p,f);l(g,b[t])}return g}}),Zc=pe((o,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:i,Uint8Array:n}=De(),{Buffer:s}=($e(),Ne(Fe)),{inspect:a}=Ye();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 s.alloc(0);let c=s.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)i(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=s.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)i(c,g,u-l),l-=g.length;else{l===g.length?(i(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(i(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})}}}),Yr=pe((o,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=De(),{validateInteger:i}=dr(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,s=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:s}function u(p,g){i(g,"value",0),p?a=g:s=g}function d(p,g,f,b){let y=l(g,b,f);if(y!=null){if(!r(y)||y<0){let w=b?`options.${f}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),eu=pe((o,e)=>{le(),ue(),ce();var t=($e(),Ne(Fe)),r=t.Buffer;function i(s,a){for(var l in s)a[l]=s[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(i(t,o),o.Buffer=n);function n(s,a,l){return r(s,a,l)}n.prototype=Object.create(r.prototype),i(r,n),n.from=function(s,a,l){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,l)},n.alloc=function(s,a,l){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},n.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}}),tu=pe(o=>{le(),ue(),ce();var e=eu().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 _;;)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(_)return;m=(""+m).toLowerCase(),_=!0}}function i(m){var _=r(m);if(typeof _!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return _||m}o.StringDecoder=n;function n(m){this.encoding=i(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=g,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=b,_=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(m){if(m.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(m),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?_?_+this.text(m,x):this.text(m,x):_||""},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 s(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,_,x){var v=_.length-1;if(v<x)return 0;var S=s(_[v]);return S>=0?(S>0&&(m.lastNeed=S-1),S):--v<x||S===-2?0:(S=s(_[v]),S>=0?(S>0&&(m.lastNeed=S-2),S):--v<x||S===-2?0:(S=s(_[v]),S>=0?(S>0&&(S===2?S=0:m.lastNeed=S-3),S):0))}function l(m,_,x){if((_[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var _=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,_,0,m.length),this.lastNeed-=m.length}function u(m,_){var x=a(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)}function d(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+"�":_}function p(m,_){if((m.length-_)%2===0){var x=m.toString("utf16le",_);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",_,m.length-1)}function g(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function f(m,_){var x=(m.length-_)%3;return x===0?m.toString("base64",_):(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",_,m.length-x))}function b(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),Pa=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{PromisePrototypeThen:r,SymbolAsyncIterator:i,SymbolIterator:n}=De(),{Buffer:s}=($e(),Ne(Fe)),{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 s)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[i])f=!0,g=d[i]();else if(d&&d[n])f=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof g.throw=="function";if(x&&v){let{value:S,done:E}=await g.throw(_);if(await S,E)return}if(typeof g.return=="function"){let{value:S}=await g.return();await S}}async function m(){for(;;){try{let{value:_,done:x}=f?await g.next():g.next();if(x)b.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(_){b.destroy(_)}break}}return b}e.exports=c}),Jr=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:i,NumberIsNaN:n,NumberParseInt:s,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:b}=(Ut(),Ne(It)),{Stream:y,prependListener:w}=vo(),{Buffer:m}=($e(),Ne(Fe)),{addAbortSignal:_}=Gr(),x=Tt(),v=Ye().debuglog("stream",P=>{v=P}),S=Zc(),E=Yt(),{getHighWaterMark:I,getDefaultHighWaterMark:O}=Yr(),{aggregateTwoErrors:C,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:$,ERR_STREAM_PUSH_AFTER_EOF:D,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:oe}=Ke(),{validateObject:K}=dr(),W=f("kPaused"),{StringDecoder:re}=tu(),F=Pa();c(ae.prototype,y.prototype),c(ae,y);var Z=()=>{},{errorOrDestroy:M}=E,Q=1,be=2,te=4,we=8,G=16,L=32,ne=64,z=128,Y=256,J=512,ge=1024,se=2048,R=4096,q=8192,ee=16384,he=32768,fe=65536,ye=1<<17,H=1<<18;function me(P){return{enumerable:!1,get(){return(this.state&P)!==0},set(N){N?this.state|=P:this.state&=~P}}}a(ve.prototype,{objectMode:me(Q),ended:me(be),endEmitted:me(te),reading:me(we),constructed:me(G),sync:me(L),needReadable:me(ne),emittedReadable:me(z),readableListening:me(Y),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(ye),dataEmitted:me(H)});function ve(P,N,_e){typeof _e!="boolean"&&(_e=N instanceof pt()),this.state=se|R|G|L,P&&P.objectMode&&(this.state|=Q),_e&&P&&P.readableObjectMode&&(this.state|=Q),this.highWaterMark=P?I(this,P,"readableHighWaterMark",_e):O(!1),this.buffer=new S,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 N=this instanceof pt();this._readableState=new ve(P,this,N),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&&!N&&_(P.signal,this)),y.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,N){N(P)},ae.prototype[b.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((N,_e)=>x(this,Se=>Se&&Se!==P?_e(Se):N(null)))},ae.prototype.push=function(P,N){return Oe(this,P,N,!1)},ae.prototype.unshift=function(P,N){return Oe(this,P,N,!0)};function Oe(P,N,_e,Se){v("readableAddChunk",N);let Ae=P._readableState,Be;if((Ae.state&Q)===0&&(typeof N=="string"?(_e=_e||Ae.defaultEncoding,Ae.encoding!==_e&&(Se&&Ae.encoding?N=m.from(N,_e).toString(Ae.encoding):(N=m.from(N,_e),_e=""))):N instanceof m?_e="":y._isUint8Array(N)?(N=y._uint8ArrayToBuffer(N),_e=""):N!=null&&(Be=new j("chunk",["string","Buffer","Uint8Array"],N))),Be)M(P,Be);else if(N===null)Ae.state&=~we,X(P,Ae);else if((Ae.state&Q)!==0||N&&N.length>0)if(Se)if((Ae.state&te)!==0)M(P,new U);else{if(Ae.destroyed||Ae.errored)return!1;h(P,Ae,N,!0)}else if(Ae.ended)M(P,new D);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~we,Ae.decoder&&!_e?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?h(P,Ae,N,!1):V(P,Ae)):h(P,Ae,N,!1)}else Se||(Ae.state&=~we,V(P,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function h(P,N,_e,Se){N.flowing&&N.length===0&&!N.sync&&P.listenerCount("data")>0?((N.state&fe)!==0?N.awaitDrainWriters.clear():N.awaitDrainWriters=null,N.dataEmitted=!0,P.emit("data",_e)):(N.length+=N.objectMode?1:_e.length,Se?N.buffer.unshift(_e):N.buffer.push(_e),(N.state&ne)!==0&&de(P)),V(P,N)}ae.prototype.isPaused=function(){let P=this._readableState;return P[W]===!0||P.flowing===!1},ae.prototype.setEncoding=function(P){let N=new re(P);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,Se="";for(let Ae of _e)Se+=N.write(Ae);return _e.clear(),Se!==""&&_e.push(Se),this._readableState.length=Se.length,this};var k=1073741824;function A(P){if(P>k)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 B(P,N){return P<=0||N.length===0&&N.ended?0:(N.state&Q)!==0?1:n(P)?N.flowing&&N.length?N.buffer.first().length:N.length:P<=N.length?P:N.ended?N.length:0}ae.prototype.read=function(P){v("read",P),P===void 0?P=NaN:i(P)||(P=s(P,10));let N=this._readableState,_e=P;if(P>N.highWaterMark&&(N.highWaterMark=A(P)),P!==0&&(N.state&=~z),P===0&&N.needReadable&&((N.highWaterMark!==0?N.length>=N.highWaterMark:N.length>0)||N.ended))return v("read: emitReadable",N.length,N.ended),N.length===0&&N.ended?nt(this):de(this),null;if(P=B(P,N),P===0&&N.ended)return N.length===0&&nt(this),null;let Se=(N.state&ne)!==0;if(v("need readable",Se),(N.length===0||N.length-P<N.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),N.state|=we|L,N.length===0&&(N.state|=ne);try{this._read(N.highWaterMark)}catch(Be){M(this,Be)}N.state&=~L,N.reading||(P=B(_e,N))}let Ae;return P>0?Ae=Ft(P,N):Ae=null,Ae===null?(N.needReadable=N.length<=N.highWaterMark,P=0):(N.length-=P,N.multiAwaitDrain?N.awaitDrainWriters.clear():N.awaitDrainWriters=null),N.length===0&&(N.ended||(N.needReadable=!0),_e!==P&&N.ended&&nt(this)),Ae!==null&&!N.errorEmitted&&!N.closeEmitted&&(N.dataEmitted=!0,this.emit("data",Ae)),Ae};function X(P,N){if(v("onEofChunk"),!N.ended){if(N.decoder){let _e=N.decoder.end();_e&&_e.length&&(N.buffer.push(_e),N.length+=N.objectMode?1:_e.length)}N.ended=!0,N.sync?de(P):(N.needReadable=!1,N.emittedReadable=!0,ke(P))}}function de(P){let N=P._readableState;v("emitReadable",N.needReadable,N.emittedReadable),N.needReadable=!1,N.emittedReadable||(v("emitReadable",N.flowing),N.emittedReadable=!0,t.nextTick(ke,P))}function ke(P){let N=P._readableState;v("emitReadable_",N.destroyed,N.length,N.ended),!N.destroyed&&!N.errored&&(N.length||N.ended)&&(P.emit("readable"),N.emittedReadable=!1),N.needReadable=!N.flowing&&!N.ended&&N.length<=N.highWaterMark,tt(P)}function V(P,N){!N.readingMore&&N.constructed&&(N.readingMore=!0,t.nextTick(ie,P,N))}function ie(P,N){for(;!N.reading&&!N.ended&&(N.length<N.highWaterMark||N.flowing&&N.length===0);){let _e=N.length;if(v("maybeReadMore read 0"),P.read(0),_e===N.length)break}N.readingMore=!1}ae.prototype._read=function(P){throw new T("_read()")},ae.prototype.pipe=function(P,N){let _e=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(P),v("pipe count=%d opts=%j",Se.pipes.length,N);let Ae=(!N||N.end!==!1)&&P!==t.stdout&&P!==t.stderr?Ve:Ot;Se.endEmitted?t.nextTick(Ae):_e.once("end",Ae),P.on("unpipe",Be);function Be(ot,ct){v("onunpipe"),ot===_e&&ct&&ct.hasUnpiped===!1&&(ct.hasUnpiped=!0,er())}function Ve(){v("onend"),P.end()}let Ze,Zt=!1;function er(){v("cleanup"),P.removeListener("close",it),P.removeListener("finish",wt),Ze&&P.removeListener("drain",Ze),P.removeListener("error",Pt),P.removeListener("unpipe",Be),_e.removeListener("end",Ve),_e.removeListener("end",Ot),_e.removeListener("data",pr),Zt=!0,Ze&&Se.awaitDrainWriters&&(!P._writableState||P._writableState.needDrain)&&Ze()}function tr(){Zt||(Se.pipes.length===1&&Se.pipes[0]===P?(v("false write response, pause",0),Se.awaitDrainWriters=P,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(P)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(P)),_e.pause()),Ze||(Ze=Ie(_e,P),P.on("drain",Ze))}_e.on("data",pr);function pr(ot){v("ondata");let ct=P.write(ot);v("dest.write",ct),ct===!1&&tr()}function Pt(ot){if(v("onerror",ot),Ot(),P.removeListener("error",Pt),P.listenerCount("error")===0){let ct=P._writableState||P._readableState;ct&&!ct.errorEmitted?M(P,ot):P.emit("error",ot)}}w(P,"error",Pt);function it(){P.removeListener("finish",wt),Ot()}P.once("close",it);function wt(){v("onfinish"),P.removeListener("close",it),Ot()}P.once("finish",wt);function Ot(){v("unpipe"),_e.unpipe(P)}return P.emit("pipe",_e),P.writableNeedDrain===!0?tr():Se.flowing||(v("pipe resume"),_e.resume()),P};function Ie(P,N){return function(){let _e=P._readableState;_e.awaitDrainWriters===N?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(N)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&P.listenerCount("data")&&P.resume()}}ae.prototype.unpipe=function(P){let N=this._readableState,_e={hasUnpiped:!1};if(N.pipes.length===0)return this;if(!P){let Ae=N.pipes;N.pipes=[],this.pause();for(let Be=0;Be<Ae.length;Be++)Ae[Be].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(N.pipes,P);return Se===-1?this:(N.pipes.splice(Se,1),N.pipes.length===0&&this.pause(),P.emit("unpipe",this,_e),this)},ae.prototype.on=function(P,N){let _e=y.prototype.on.call(this,P,N),Se=this._readableState;return P==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):P==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?de(this):Se.reading||t.nextTick(Pe,this)),_e},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(P,N){let _e=y.prototype.removeListener.call(this,P,N);return P==="readable"&&t.nextTick(Te,this),_e},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(P){let N=y.prototype.removeAllListeners.apply(this,arguments);return(P==="readable"||P===void 0)&&t.nextTick(Te,this),N};function Te(P){let N=P._readableState;N.readableListening=P.listenerCount("readable")>0,N.resumeScheduled&&N[W]===!1?N.flowing=!0:P.listenerCount("data")>0?P.resume():N.readableListening||(N.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,Me(this,P)),P[W]=!1,this};function Me(P,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(et,P,N))}function et(P,N){v("resume",N.reading),N.reading||P.read(0),N.resumeScheduled=!1,P.emit("resume"),tt(P),N.flowing&&!N.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 tt(P){let N=P._readableState;for(v("flow",N.flowing);N.flowing&&P.read()!==null;);}ae.prototype.wrap=function(P){let N=!1;P.on("data",Se=>{!this.push(Se)&&P.pause&&(N=!0,P.pause())}),P.on("end",()=>{this.push(null)}),P.on("error",Se=>{M(this,Se)}),P.on("close",()=>{this.destroy()}),P.on("destroy",()=>{this.destroy()}),this._read=()=>{N&&P.resume&&(N=!1,P.resume())};let _e=l(P);for(let Se=1;Se<_e.length;Se++){let Ae=_e[Se];this[Ae]===void 0&&typeof P[Ae]=="function"&&(this[Ae]=P[Ae].bind(P))}return this},ae.prototype[g]=function(){return qe(this)},ae.prototype.iterator=function(P){return P!==void 0&&K(P,"options"),qe(this,P)};function qe(P,N){typeof P.read!="function"&&(P=ae.wrap(P,{objectMode:!0}));let _e=rt(P,N);return _e.stream=P,_e}async function*rt(P,N){let _e=Z;function Se(Ve){this===P?(_e(),_e=Z):_e=Ve}P.on("readable",Se);let Ae,Be=x(P,{writable:!1},Ve=>{Ae=Ve?C(Ae,Ve):null,_e(),_e=Z});try{for(;;){let Ve=P.destroyed?null:P.read();if(Ve!==null)yield Ve;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Ve){throw Ae=C(Ae,Ve),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||P._readableState.autoDestroy)?E.destroyer(P,null):(P.off("readable",Se),Be())}}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=Ft;function Ft(P,N){if(N.length===0)return null;let _e;return N.objectMode?_e=N.buffer.shift():!P||P>=N.length?(N.decoder?_e=N.buffer.join(""):N.buffer.length===1?_e=N.buffer.first():_e=N.buffer.concat(N.length),N.buffer.clear()):_e=N.buffer.consume(P,N.decoder),_e}function nt(P){let N=P._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(Qe,N,P))}function Qe(P,N){if(v("endReadableNT",P.endEmitted,P.length),!P.errored&&!P.closeEmitted&&!P.endEmitted&&P.length===0){if(P.endEmitted=!0,N.emit("end"),N.writable&&N.allowHalfOpen===!1)t.nextTick(fr,N);else if(P.autoDestroy){let _e=N._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&N.destroy()}}}function fr(P){P.writable&&!P.writableEnded&&!P.destroyed&&P.end()}ae.from=function(P,N){return F(ae,P,N)};var $t;function Xt(){return $t===void 0&&($t={}),$t}ae.fromWeb=function(P,N){return Xt().newStreamReadableFromReadableStream(P,N)},ae.toWeb=function(P,N){return Xt().newReadableStreamFromStreamReadable(P,N)},ae.wrap=function(P,N){var _e,Se;return new ae({objectMode:(_e=(Se=P.readableObjectMode)!==null&&Se!==void 0?Se:P.objectMode)!==null&&_e!==void 0?_e:!0,...N,destroy(Ae,Be){E.destroyer(P,Ae),Be(Ae)}}).wrap(P)}}),wo=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{ArrayPrototypeSlice:r,Error:i,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=De();e.exports=K,K.WritableState=U;var{EventEmitter:p}=(Ut(),Ne(It)),g=vo().Stream,{Buffer:f}=($e(),Ne(Fe)),b=Yt(),{addAbortSignal:y}=Gr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Yr(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:S,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}=b;l(K.prototype,g.prototype),l(K,g);function $(){}var D=u("kOnFinished");function U(R,q,ee){typeof ee!="boolean"&&(ee=q instanceof pt()),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)},s(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function K(R){let q=this instanceof pt();if(!q&&!n(K,this))return new K(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&&y(R.signal,this)),g.call(this,R),b.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),z(this,ee)})}s(K,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==K?!1:R&&R._writableState instanceof U}}),K.prototype.pipe=function(){T(this,new S)};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=$)}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 _("chunk",["string","Buffer","Uint8Array"],q);let ye;return fe.ending?ye=new C:fe.destroyed&&(ye=new E("write")),ye?(t.nextTick(he,ye),T(R,ye,!0),ye):(fe.pendingcb++,re(R,fe,q,ee,he))}K.prototype.write=function(R,q,ee){return W(this,R,q,ee)===!0},K.prototype.cork=function(){this._writableState.corked++},K.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},K.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 ye=q.objectMode?1:ee.length;q.length+=ye;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=ye,q.writecb=fe,q.writing=!0,q.sync=!0,R._write(ee,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function F(R,q,ee,he,fe,ye,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new E("write")):ee?R._writev(fe,q.onwrite):R._write(fe,ye,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)):be(R,ee,1,fe))}function Q({stream:R,state:q,count:ee,cb:he}){return q.afterWriteTickInfo=null,be(R,q,ee,he)}function be(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:ye,callback:H}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,H((q=R.errored)!==null&&q!==void 0?q:new E("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 E("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,ye=ee.length-he;if(!ye)return;let H=he;if(q.bufferProcessing=!0,ye>1&&R._writev){q.pendingcb-=ye-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(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;F(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}K.prototype._write=function(R,q,ee){if(this._writev)this._writev([{chunk:R,encoding:q}],ee);else throw new x("_write()")},K.prototype._writev=null,K.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 ye=W(this,R,q);ye instanceof i&&(fe=ye)}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[D].push(ee)),this};function G(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function L(R,q){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,q.pendingcb--,fe){let ye=q[D].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(R,fe,q.sync)}else G(q)&&(q.prefinished=!0,R.emit("prefinish"),q.pendingcb++,t.nextTick(Y,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,L(R,q)):(q.prefinished=!0,R.emit("prefinish")))}function z(R,q,ee){G(q)&&(ne(R,q),q.pendingcb===0&&(ee?(q.pendingcb++,t.nextTick((he,fe)=>{G(fe)?Y(he,fe):fe.pendingcb--},R,q)):G(q)&&(q.pendingcb++,Y(R,q))))}function Y(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(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(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=b.destroy;K.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},K.prototype._undestroy=b.undestroy,K.prototype._destroy=function(R,q){q(R)},K.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function se(){return ge===void 0&&(ge={}),ge}K.fromWeb=function(R,q){return se().newStreamWritableFromWritableStream(R,q)},K.toWeb=function(R){return se().newWritableStreamFromStreamWritable(R)}}),ru=pe((o,e)=>{le(),ue(),ce();var t=Dt(),r=($e(),Ne(Fe)),{isReadable:i,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=bt(),g=Tt(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Yt(),m=pt(),_=Jr(),x=wo(),{createDeferredPromise:v}=Ye(),S=Pa(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(D){return D instanceof E}:function(D){return!1},O=globalThis.AbortController||cr().AbortController,{FunctionPrototypeCall:C}=De(),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 $({readable:U});if(c(U))return $({writable:U});if(a(U))return $({writable:!1,readable:!1});if(d(U))return $({readable:_.fromWeb(U)});if(p(U))return $({writable:x.fromWeb(U)});if(typeof U=="function"){let{value:W,write:re,final:F,destroy:Z}=T(U);if(s(W))return S(j,W,{objectMode:!0,write:re,final:F,destroy:Z});let M=W?.then;if(typeof M=="function"){let Q,be=C(M,W,te=>{if(te!=null)throw new y("nully","body",te)},te=>{w(Q,te)});return Q=new j({objectMode:!0,readable:!1,write:re,final(te){F(async()=>{try{await be,t.nextTick(te,null)}catch(we){t.nextTick(te,we)}})},destroy:Z})}throw new y("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(U))return D(U.arrayBuffer());if(s(U))return S(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 $({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 b(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(D){let{promise:U,resolve:oe}=v(),K=new O,W=K.signal;return{value:D((async function*(){for(;;){let re=U;U=null;let{chunk:F,done:Z,cb:M}=await re;if(t.nextTick(M),Z)return;if(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 $(D){let U=D.readable&&typeof D.readable.read!="function"?_.wrap(D.readable):D.readable,oe=D.writable,K=!!i(U),W=!!n(oe),re,F,Z,M,Q;function be(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),be(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),be(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((o,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:i,ObjectSetPrototypeOf:n}=De();e.exports=l;var s=Jr(),a=wo();n(l.prototype,s.prototype),n(l,s);{let p=i(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);s.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=ru()),d(p,"body")}}),Oa=pe((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=De();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:i}=Ke().codes,n=pt(),{getHighWaterMark:s}=Yr();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?s(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 i("_transform()")},l.prototype._write=function(d,p,g){let f=this._readableState,b=this._writableState,y=f.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===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()}}}),Ma=pe((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=De();e.exports=i;var r=Oa();t(i.prototype,r.prototype),t(i,r);function i(n){if(!(this instanceof i))return new i(n);r.call(this,n)}i.prototype._transform=function(n,s,a){a(null,n)}}),_o=pe((o,e)=>{le(),ue(),ce();var t=Dt(),{ArrayIsArray:r,Promise:i,SymbolAsyncIterator:n,SymbolDispose:s}=De(),a=Tt(),{once:l}=Ye(),c=Yt(),u=pt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:_}=dr(),{isIterable:x,isReadable:v,isReadableNodeStream:S,isNodeStream:E,isTransformStream:I,isWebStream:O,isReadableStream:C,isReadableFinished:j}=bt(),T=globalThis.AbortController||cr().AbortController,$,D,U;function oe(te,we,G){let L=!1;te.on("close",()=>{L=!0});let ne=a(te,{readable:we,writable:G},z=>{L=!z});return{destroy:z=>{L||(L=!0,c.destroyer(te,z||new b("pipe")))},cleanup:ne}}function K(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function W(te){if(x(te))return te;if(S(te))return re(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*re(te){D||(D=Jr()),yield*D.prototype[n].call(te)}async function F(te,we,G,{end:L}){let ne,z=null,Y=se=>{if(se&&(ne=se),z){let R=z;z=null,R()}},J=()=>new i((se,R)=>{ne?R(ne):z=()=>{ne?R(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();L&&(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:L}){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,L&&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 L=new T,ne=L.signal,z=G?.signal,Y=[];_(z,"options.signal");function J(){fe(new w)}U=U||Ye().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[s](),L.abort(),ae&&(se||Y.forEach(h=>h()),t.nextTick(we,se,R))}}let ye;for(let ve=0;ve<te.length;ve++){let ae=te[ve],Oe=ve<te.length-1,h=ve>0,k=Oe||G?.end!==!1,A=ve===te.length-1;if(E(ae)){let B=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(X)};if(k){let{destroy:X,cleanup:de}=oe(ae,Oe,h);q.push(X),v(ae)&&A&&Y.push(de)}ae.on("error",B),v(ae)&&A&&Y.push(()=>{ae.removeListener("error",B)})}if(ve===0)if(typeof ae=="function"){if(ye=ae({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(ae)||S(ae)||I(ae)?ye=ae:ye=u.from(ae);else if(typeof ae=="function"){if(I(ye)){var H;ye=W((H=ye)===null||H===void 0?void 0:H.readable)}else ye=W(ye);if(ye=ae(ye,{signal:ne}),Oe){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;$||($=Ma());let B=new $({objectMode:!0}),X=(me=ye)===null||me===void 0?void 0:me.then;if(typeof X=="function")ee++,X.call(ye,V=>{R=V,V!=null&&B.write(V),k&&B.end(),t.nextTick(he)},V=>{B.destroy(V),t.nextTick(he,V)});else if(x(ye,!0))ee++,F(ye,B,he,{end:k});else if(C(ye)||I(ye)){let V=ye.readable||ye;ee++,F(V,B,he,{end:k})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:ke}=oe(ye,!1,!0);q.push(de),A&&Y.push(ke)}}else if(E(ae)){if(S(ye)){ee+=2;let B=be(ye,ae,he,{end:k});v(ae)&&A&&Y.push(B)}else if(I(ye)||C(ye)){let B=ye.readable||ye;ee++,F(B,ae,he,{end:k})}else if(x(ye))ee++,F(ye,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(O(ae)){if(S(ye))ee++,Z(W(ye),ae,he,{end:k});else if(C(ye)||x(ye))ee++,Z(ye,ae,he,{end:k});else if(I(ye))ee++,Z(ye.readable,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ne!=null&&ne.aborted||z!=null&&z.aborted)&&t.nextTick(J),ye}function be(te,we,G,{end:L}){let ne=!1;if(we.on("close",()=>{ne||G(new y)}),te.pipe(we,{end:!1}),L){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}}),Ra=pe((o,e)=>{le(),ue(),ce();var{pipeline:t}=_o(),r=pt(),{destroyer:i}=Yt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=bt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ke(),b=Tt();e.exports=function(...y){if(y.length===0)throw new f("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(s(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,_,x,v,S;function E(T){let $=v;v=null,$?$(T):T?S.destroy(T):!j&&!C&&S.destroy()}let I=y[0],O=t(y,E),C=!!(a(I)||u(I)||c(I)),j=!!(s(O)||d(O)||c(O));if(S=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(O!=null&&O.readableObjectMode),writable:C,readable:j}),C){if(n(I))S._write=function($,D,U){I.write($,D)?U():m=U},S._final=function($){I.end(),_=$},I.on("drain",function(){if(m){let $=m;m=null,$()}});else if(l(I)){let $=(c(I)?I.writable:I).getWriter();S._write=async function(D,U,oe){try{await $.ready,$.write(D).catch(()=>{}),oe()}catch(K){oe(K)}},S._final=async function(D){try{await $.ready,$.close().catch(()=>{}),_=D}catch(U){D(U)}}}let T=c(O)?O.readable:O;b(T,()=>{if(_){let $=_;_=null,$()}})}if(j){if(n(O))O.on("readable",function(){if(x){let T=x;x=null,T()}}),O.on("end",function(){S.push(null)}),S._read=function(){for(;;){let T=O.read();if(T===null){x=S._read;return}if(!S.push(T))return}};else if(l(O)){let T=(c(O)?O.readable:O).getReader();S._read=async function(){for(;;)try{let{value:$,done:D}=await T.read();if(!S.push($))return;if(D){S.push(null);return}}catch{return}}}}return S._destroy=function(T,$){!T&&v!==null&&(T=new p),x=null,m=null,_=null,v===null?$(T):(v=$,n(O)&&i(O,T))},S}}),nu=pe((o,e)=>{le(),ue(),ce();var t=globalThis.AbortController||cr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:i,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=dr(),d=De().Symbol("kWeak"),p=De().Symbol("kResistStopPropagation"),{finished:g}=Tt(),f=Ra(),{addAbortSignalNoValidate:b}=Gr(),{isWritable:y,isNodeStream:w}=bt(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:S,NumberIsNaN:E,Promise:I,PromiseReject:O,PromiseResolve:C,PromisePrototypeThen:j,Symbol:T}=De(),$=T("kEmpty"),D=T("kEof");function U(z,Y){if(Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),w(z)&&!y(z))throw new r("stream",z,"must be writable");let J=f(this,z);return Y!=null&&Y.signal&&b(Y.signal,J),J}function oe(z,Y){if(typeof z!="function")throw new i("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=Ye().AbortSignalAny([Y?.signal].filter(x)),R=this,q=[],ee={signal:se},he,fe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,ae()}function ae(){fe&&!ye&&H<J&&q.length<ge&&(fe(),fe=null)}async function Oe(){try{for await(let h of R){if(ye)return;if(se.aborted)throw new a;try{if(h=z(h,ee),h===$)continue;h=C(h)}catch(k){h=O(k)}H+=1,j(h,ve,me),q.push(h),he&&(he(),he=null),!ye&&(q.length>=ge||H>=J)&&await new I(k=>{fe=k})}q.push(D)}catch(h){let k=O(h);j(k,ve,me),q.push(k)}finally{ye=!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!==$&&(yield h),q.shift(),ae()}await new I(h=>{he=h})}}finally{ye=!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 i("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 i("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 i("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 be(z,Y,J){var ge;if(typeof z!="function")throw new i("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 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?Y=await z(Y,fe,{signal:q}):(Y=fe,se=!0)}if(!ee&&!se)throw new Q}finally{R.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});_(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=S(z),E(z))return 0;if(z<0)throw new s("number",">= 0",z);return z}function L(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:L,filter:M,flatMap:we,map:oe,take:ne,compose:U},e.exports.promiseReturningOperators={every:re,forEach:Z,reduce:be,toArray:te,some:W,find:F}}),Na=pe((o,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=De(),{isIterable:i,isNodeStream:n,isWebStream:s}=bt(),{pipelineImpl:a}=_o(),{finished:l}=Tt();La();function c(...u){return new r((d,p)=>{let g,f,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!i(b)&&!s(b)){let y=t(u);g=y.signal,f=y.end}a(u,(y,w)=>{y?p(y):d(w)},{signal:g,end:f})})}e.exports={finished:l,pipeline:c}}),La=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Ne(Fe)),{ObjectDefineProperty:r,ObjectKeys:i,ReflectApply:n}=De(),{promisify:{custom:s}}=Ye(),{streamReturningOperators:a,promiseReturningOperators:l}=nu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=Ra(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Yr(),{pipeline:g}=_o(),{destroyer:f}=Yt(),b=Tt(),y=Na(),w=bt(),m=e.exports=vo().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Jr();for(let x of i(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(S,this,E))},S=a[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of i(l)){let v=function(...E){if(new.target)throw c();return n(S,this,E)},S=l[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=wo(),m.Duplex=pt(),m.Transform=Oa(),m.PassThrough=Ma(),m.pipeline=g;var{addAbortSignal:_}=Gr();m.addAbortSignal=_,m.finished=b,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,s,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,s,{__proto__:null,enumerable:!0,get(){return y.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)}}),Bt=pe((o,e)=>{le(),ue(),ce();var t=La(),r=Na(),i=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=i,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}),iu=pe((o,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 i=function(){};i.prototype=r.prototype,t.prototype=new i,t.prototype.constructor=t}}}),ou=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Ne(Fe)),r=Symbol.for("BufferList");function i(n){if(!(this instanceof i))return new i(n);i._init.call(this,n)}i._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},i.prototype._new=function(n){return new i(n)},i.prototype._offset=function(n){if(n===0)return[0,0];let s=0;for(let a=0;a<this._bufs.length;a++){let l=s+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-s];s=l}},i.prototype._reverseOffset=function(n){let s=n[0],a=n[1];for(let l=0;l<s;l++)a+=this._bufs[l].length;return a},i.prototype.getBuffers=function(){return this._bufs},i.prototype.get=function(n){if(n>this.length||n<0)return;let s=this._offset(n);return this._bufs[s[0]][s[1]]},i.prototype.slice=function(n,s){return typeof n=="number"&&n<0&&(n+=this.length),typeof s=="number"&&s<0&&(s+=this.length),this.copy(null,0,n,s)},i.prototype.copy=function(n,s,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&&s||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 b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,s,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-f;if(p>y)this._bufs[b].copy(n,g,f),g+=y;else{this._bufs[b].copy(n,g,f,f+p),g+=y;break}p-=y,f&&(f=0)}return n.length>g?n.slice(0,g):n},i.prototype.shallowSlice=function(n,s){if(n=n||0,s=typeof s!="number"?this.length:s,n<0&&(n+=this.length),s<0&&(s+=this.length),n===s)return this._new();let a=this._offset(n),l=this._offset(s),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)},i.prototype.toString=function(n,s,a){return this.slice(s,a).toString(n)},i.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},i.prototype.duplicate=function(){let n=this._new();for(let s=0;s<this._bufs.length;s++)n.append(this._bufs[s]);return n},i.prototype.append=function(n){return this._attach(n,i.prototype._appendBuffer)},i.prototype.prepend=function(n){return this._attach(n,i.prototype._prependBuffer,!0)},i.prototype._attach=function(n,s,a){if(n==null)return this;if(n.buffer)s.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],s,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],s,a)}else typeof n=="number"&&(n=n.toString()),s.call(this,t.from(n));return this},i.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},i.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},i.prototype.indexOf=function(n,s,a){if(a===void 0&&typeof s=="string"&&(a=s,s=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)),s=Number(s||0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),n.length===0)return s>this.length?this.length:s;let l=this._offset(s),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},i.prototype._match=function(n,s){if(this.length-n<s.length)return!1;for(let a=0;a<s.length;a++)if(this.get(n+a)!==s[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 s in n)(function(a){n[a]===null?i.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:i.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(s)})(),i.prototype._isBufferList=function(n){return n instanceof i||i.isBufferList(n)},i.isBufferList=function(n){return n!=null&&n[r]},e.exports=i}),su=pe((o,e)=>{le(),ue(),ce();var t=Bt().Duplex,r=iu(),i=ou();function n(s){if(!(this instanceof n))return new n(s);if(typeof s=="function"){this._callback=s;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)}),s=null}i._init.call(this,s),t.call(this)}r(n,t),Object.assign(n.prototype,i.prototype),n.prototype._new=function(s){return new n(s)},n.prototype._write=function(s,a,l){this._appendBuffer(s),typeof l=="function"&&l()},n.prototype._read=function(s){if(!this.length)return this.push(null);s=Math.min(s,this.length),this.push(this.slice(0,s)),this.consume(s)},n.prototype.end=function(s){t.prototype.end.call(this,s),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(s,a){this._bufs.length=0,this.length=0,a(s)},n.prototype._isBufferList=function(s){return s instanceof n||s instanceof i||n.isBufferList(s)},n.isBufferList=i.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=i}),au=pe((o,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}),ja=pe((o,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=($e(),Ne(Fe));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 s=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+s.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let s=t.types[n];t.codes[s]=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 s=t.properties[n];t.propertiesCodes[s]=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 i(n){return[0,1,2].map(s=>[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)|s<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=i("publish"),t.SUBSCRIBE_HEADER=i("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=i("unsubscribe"),t.ACKS={unsuback:i("unsuback"),puback:i("puback"),pubcomp:i("pubcomp"),pubrel:i("pubrel"),pubrec:i("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"}}),lu=pe((o,e)=>{le(),ue(),ce();var t=1e3,r=t*60,i=r*60,n=i*24,s=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]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return f*a;case"weeks":case"week":case"w":return f*s;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*i;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>=i?Math.round(p/i)+"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>=i?d(p,g,i,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,f,b){var y=g>=f*1.5;return Math.round(p/f)+" "+b+(y?"s":"")}}),cu=pe((o,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=lu(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function i(g){let f=0;for(let b=0;b<g.length;b++)f=(f<<5)-f+g.charCodeAt(b),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=i;function n(g){let f,b=null,y,w;function m(..._){if(!m.enabled)return;let x=m,v=Number(new Date),S=v-(f||v);x.diff=S,x.prev=f,x.curr=v,f=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let E=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(I,O)=>{if(I==="%%")return"%";E++;let C=n.formatters[O];if(typeof C=="function"){let j=_[E];I=C.call(x,j),_.splice(E,1),E--}return I}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=s,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:_=>{b=_}}),typeof n.init=="function"&&n.init(m),m}function s(g,f){let b=n(this.namespace+(typeof f>"u"?":":f)+g);return b.log=this.log,b}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 b of f)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,f){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<f.length&&(f[y]===g[b]||f[y]==="*"))f[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===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((o,e)=>{le(),ue(),ce(),o.formatArgs=r,o.save=i,o.load=n,o.useColors=t,o.storage=s(),o.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`."))}})(),o.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)}o.log=console.debug||console.log||(()=>{});function i(l){try{l?o.storage.setItem("debug",l):o.storage.removeItem("debug")}catch{}}function n(){let l;try{l=o.storage.getItem("debug")||o.storage.getItem("DEBUG")}catch{}return!l&&typeof Le<"u"&&"env"in Le&&(l=Le.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=cu()(o);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),uu=pe((o,e)=>{le(),ue(),ce();var t=su(),{EventEmitter:r}=(Ut(),Ne(It)),i=au(),n=ja(),s=mt()("mqtt-packet:parser"),a=class xi extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof xi?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new xi().parser(c)}_resetState(){s("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),s("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++,s("parse: state complete. _stateCounter is now: %d",this._stateCounter),s("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return s("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,s("_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)),s("_parseLength %d",c.value),!!c}_parsePayload(){s("_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 s("_parsePayload complete result: %s",c),c}_parseConnect(){s("_parseConnect");let c,u,d,p,g={},f=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=b,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 y=!!(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=y,f.will.qos=w;else{if(y)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 _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.properties=_)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,s("_parseConnect: packet.clientId: %s",f.clientId),g.will){if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.will.properties=_)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,s("_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,s("_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,s("_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,s("_parseConnect: complete"),f}_parseConnack(){s("_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)}s("_parseConnack: complete")}_parsePublish(){s("_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),s("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){s("_parseSubscribe");let c=this.packet,u,d,p,g,f,b,y;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(b=(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"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=b,y.rap=f,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),s("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){s("_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(){s("_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"));s("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){s("_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(){s("_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}s("_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(s("_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 s("_parseDisconnect result: true"),!0}_parseAuth(){s("_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),s("_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):(s("_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,s("_parseString: result: %s",p),p}_parseStringPair(){return s("_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,s("_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,s("_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,s("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){s("_parseVarByteNum");let u=4,d=0,p=1,g=0,f=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=p*(b&n.VARBYTEINT_MASK),p*=128,(b&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),f?c?f={bytes:d,value:g}:f=g:f=!1,s("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),s("_parseByte: result: %o",c),c}_parseByType(c){switch(s("_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(){s("_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 b=d[g][f.name];d[g][f.name]=[b],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 s("_newPacket"),this.packet&&(this._list.consume(this.packet.length),s("_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)),s("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(c){s("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),du=pe((o,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Ne(Fe)),r=65536,i={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function s(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++)i[u]=s(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:i,generateCache:a,generateNumber:s,genBufVariableByteInt:l,generate4ByteBuffer:c}}),hu=pe((o,e)=>{le(),ue(),ce(),typeof Le>"u"||!Le.version||Le.version.indexOf("v0.")===0||Le.version.indexOf("v1.")===0&&Le.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Le;function t(r,i,n,s){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 Le.nextTick(r);case 2:return Le.nextTick(function(){r.call(null,i)});case 3:return Le.nextTick(function(){r.call(null,i,n)});case 4:return Le.nextTick(function(){r.call(null,i,n,s)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return Le.nextTick(function(){r.apply(null,l)})}}}),Ua=pe((o,e)=>{le(),ue(),ce();var t=ja(),{Buffer:r}=($e(),Ne(Fe)),i=r.allocUnsafe(0),n=r.from([0]),s=du(),a=hu().nextTick,l=mt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,p=s.genBufVariableByteInt,g=s.generate4ByteBuffer,f=K,b=!0;function y(G,L,ne){switch(l("generate called"),L.cork&&(L.cork(),a(w,L)),b&&(b=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,L);case"connack":return _(G,L,ne);case"publish":return x(G,L,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,L,ne);case"subscribe":return S(G,L,ne);case"suback":return E(G,L,ne);case"unsubscribe":return I(G,L,ne);case"unsuback":return O(G,L,ne);case"pingreq":case"pingresp":return C(G,L);case"disconnect":return j(G,L,ne);case"auth":return T(G,L,ne);default:return L.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return f===K},set(G){G?((!c||Object.keys(c).length===0)&&(b=!0),f=K):(b=!1,f=W)}});function w(G){G.uncork()}function m(G,L,ne){let z=G||{},Y=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 ye=0;if(typeof Y!="string"&&!r.isBuffer(Y))return L.destroy(new Error("Invalid protocolId")),!1;if(ye+=Y.length+2,J!==3&&J!==4&&J!==5)return L.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof q=="string"||r.isBuffer(q))&&(q||J>=4)&&(q||se))ye+=r.byteLength(q)+2;else{if(J<4)return L.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return L.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return L.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(J===5){if(H=Z(L,fe),!H)return!1;ye+=H.length}if(ge){if(typeof ge!="object")return L.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return L.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return L.destroy(new Error("Invalid will payload")),!1;if(me={},J===5){if(me=Z(L,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return L.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return L.destroy(new Error("Username is required to use password")),!1;if(we(he))ye+=te(he)+2;else return L.destroy(new Error("Invalid password")),!1}L.write(t.CONNECT_HEADER),D(L,ye),F(L,Y),z.bridgeMode&&(J+=128),L.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,L.write(r.from([ae])),f(L,R),J===5&&H.write(),F(L,q),ge&&(J===5&&me.write(),U(L,ge.topic),F(L,ge.payload)),ee!=null&&F(L,ee),he!=null&&F(L,he),!0}function _(G,L,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 L.destroy(new Error("Invalid return code")),!1;let R=null;if(z===5){if(R=Z(L,ge),!R)return!1;se+=R.length}return L.write(t.CONNACK_HEADER),D(L,se),L.write(Y.sessionPresent?t.SESSIONPRESENT_HEADER:n),L.write(r.from([J])),R?.write(),!0}function x(G,L,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,R=Y.payload||i,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 L.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),J&&typeof q!="number")return L.destroy(new Error("Invalid messageId")),!1;J&&(he+=2);let fe=null;if(z===5){if(fe=Z(L,ee),!fe)return!1;he+=fe.length}return L.write(t.PUBLISH_HEADER[J][Y.dup?1:0][ge?1:0]),D(L,he),f(L,te(se)),L.write(se),J>0&&f(L,q),fe?.write(),l("publish: payload: %o",R),L.write(R)}function v(G,L,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,R=0,q=Y.reasonCode,ee=Y.properties,he=z===5?3:2;if(J==="pubrel"&&(R=1),typeof ge!="number")return L.destroy(new Error("Invalid messageId")),!1;let fe=null;if(z===5&&typeof ee=="object"){if(fe=M(L,ee,ne,he),!fe)return!1;he+=fe.length}return L.write(t.ACKS[J][R][se][0]),he===3&&(he+=q!==0?1:-1),D(L,he),f(L,ge),z===5&&he!==2&&L.write(r.from([q])),fe!==null?fe.write():he===4&&L.write(r.from([0])),!0}function S(G,L,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,R=Y.properties,q=0;if(typeof ge!="number")return L.destroy(new Error("Invalid messageId")),!1;q+=2;let ee=null;if(z===5){if(ee=Z(L,R),!ee)return!1;q+=ee.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,H=se[fe].qos;if(typeof ye!="string")return L.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return L.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(z===5){if(typeof(se[fe].nl||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return L.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[fe].rh||0;if(typeof me!="number"||me>2)return L.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=r.byteLength(ye)+2+1}else return L.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),L.write(t.SUBSCRIBE_HEADER[1][J?1:0][0]),D(L,q),f(L,ge),ee!==null&&ee.write();let he=!0;for(let fe of se){let ye=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;U(L,ye),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=L.write(r.from([Oe]))}return he}function E(G,L,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.granted,se=Y.properties,R=0;if(typeof J!="number")return L.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 L.destroy(new Error("Invalid qos vector")),!1;R+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let q=null;if(z===5){if(q=M(L,se,ne,R),!q)return!1;R+=q.length}return L.write(t.SUBACK_HEADER),D(L,R),f(L,J),q!==null&&q.write(),L.write(r.from(ge))}function I(G,L,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.unsubscriptions,R=Y.properties,q=0;if(typeof J!="number")return L.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 L.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return L.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(z===5){if(ee=Z(L,R),!ee)return!1;q+=ee.length}L.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),D(L,q),f(L,J),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(L,se[fe]);return he}function O(G,L,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.granted,R=Y.properties,q=Y.cmd,ee=0,he=2;if(typeof J!="number")return L.destroy(new Error("Invalid messageId")),!1;if(z===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[ye]!="number")return L.destroy(new Error("Invalid qos vector")),!1;he+=1}else return L.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(z===5){if(fe=M(L,R,ne,he),!fe)return!1;he+=fe.length}return L.write(t.ACKS[q][ee][ge][0]),D(L,he),f(L,J),fe!==null&&fe.write(),z===5&&L.write(r.from(se)),!0}function C(G,L,ne){return L.write(t.EMPTY[G.cmd])}function j(G,L,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.reasonCode,ge=Y.properties,se=z===5?1:0,R=null;if(z===5){if(R=M(L,ge,ne,se),!R)return!1;se+=R.length}return L.write(r.from([t.codes.disconnect<<4])),D(L,se),z===5&&L.write(r.from([J])),R!==null&&R.write(),!0}function T(G,L,ne){let z=ne?ne.protocolVersion:4,Y=G||{},J=Y.reasonCode,ge=Y.properties,se=z===5?1:0;z!==5&&L.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(L,ge,ne,se);return R?(se+=R.length,L.write(r.from([t.codes.auth<<4])),D(L,se),L.write(r.from([J])),R!==null&&R.write(),!0):!1}var $={};function D(G,L){if(L>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${L}`)),!1;let ne=$[L];return ne||(ne=p(L),L<16384&&($[L]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,L){let ne=r.byteLength(L);return f(G,ne),l("writeString: %s",L),G.write(L,"utf8")}function oe(G,L,ne){U(G,L),U(G,ne)}function K(G,L){return l("writeNumberCached: number: %d",L),l("writeNumberCached: %o",c[L]),G.write(c[L])}function W(G,L){let ne=u(L);return l("writeNumberGenerated: %o",ne),G.write(ne)}function re(G,L){let ne=g(L);return l("write4ByteNumber: %o",ne),G.write(ne)}function F(G,L){typeof L=="string"?U(G,L):L?(f(G,L.length),G.write(L)):f(G,0)}function Z(G,L){if(typeof L!="object"||L.length!=null)return{length:1,write(){be(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((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 G.destroy(new Error(`Invalid property ${Y}: ${J}`)),!1}return se}if(L)for(let Y in L){let J=0,ge=0,se=L[Y];if(se!==void 0){if(Array.isArray(se))for(let R=0;R<se.length;R++){if(ge=z(Y,se[R]),!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(){be(G,L,ne)}}}function M(G,L,ne,z){let Y=["reasonString","userProperties"],J=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=Z(G,L);if(J)for(;z+ge.length>J;){let se=Y.shift();if(se&&L[se])delete L[se],ge=Z(G,L);else return!1}return ge}function Q(G,L,ne){switch(t.propertiesTypes[L]){case"byte":{G.write(r.from([t.properties[L]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[L]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[L]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[L]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[L]])),re(G,ne);break}case"var":{G.write(r.from([t.properties[L]])),D(G,ne);break}case"string":{G.write(r.from([t.properties[L]])),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[L]])),oe(G,z.toString(),J.toString())}):(G.write(r.from([t.properties[L]])),oe(G,z.toString(),Y.toString()))});break}default:return G.destroy(new Error(`Invalid property ${L} value: ${ne}`)),!1}}function be(G,L,ne){D(G,ne);for(let z in L)if(Object.prototype.hasOwnProperty.call(L,z)&&L[z]!=null){let Y=L[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=y}),fu=pe((o,e)=>{le(),ue(),ce();var t=Ua(),{EventEmitter:r}=(Ut(),Ne(It)),{Buffer:i}=($e(),Ne(Fe));function n(a,l){let c=new s;return t(a,c,l),c.concat()}var s=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]=i.byteLength(c[d]),a+=l[d];let p=i.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}),pu=pe(o=>{le(),ue(),ce(),o.parser=uu().parser,o.generate=fu(),o.writeToStream=Ua()}),mu=pe((o,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof zr?zr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return i(n);let s=new Map;if(s.set(Date,d=>new Date(d)),s.set(Map,(d,p)=>new Map(l(Array.from(d),p))),s.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)s.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 b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?f[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?f[y]=a(w,p):ArrayBuffer.isView(w)?f[y]=t(w):f[y]=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=s.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=s.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=s.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=s.get(f.constructor))?p[g]=a(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function i(n){let s=[],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 b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],_=g[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=l.get(_.constructor)))y[m]=c(_,f);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=s.indexOf(_);x!==-1?y[m]=a[x]:y[m]=f(_)}}return y}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={};s.push(g),a.push(f);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[b]=c(y,d);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=s.indexOf(y);w!==-1?f[b]=a[w]:f[b]=d(y)}}return s.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={};s.push(g),a.push(f);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[b]=c(y,p);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=s.indexOf(y);w!==-1?f[b]=a[w]:f[b]=p(y)}}return s.pop(),a.pop(),f}}}),gu=pe((o,e)=>{le(),ue(),ce(),e.exports=mu()()}),Da=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.validateTopic=e,o.validateTopics=t;function e(r){let i=r.split("/");for(let n=0;n<i.length;n++)if(i[n]!=="+"){if(i[n]==="#")return n===i.length-1;if(i[n].indexOf("+")!==-1||i[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let i=0;i<r.length;i++)if(!e(r[i]))return r[i];return null}}),Ba=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Bt(),t={objectMode:!0},r={clean:!0},i=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,s){return this._inflights.set(n.messageId,n),s&&s(),this}createStream(){let n=new e.Readable(t),s=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{s.push(c)}),n._read=()=>{!a&&l<s.length?n.push(s[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,s){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),s(null,a)):s&&s(new Error("missing packet")),this}get(n,s){let a=this._inflights.get(n.messageId);return a?s(null,a):s&&s(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};o.default=i}),bu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,i,n)=>{r.log("handlePublish: packet %o",i),n=typeof n<"u"?n:r.noop;let s=i.topic.toString(),a=i.payload,{qos:l}=i,{messageId:c}=i,{options:u}=r;if(r.options.protocolVersion===5){let d;if(i.properties&&(d=i.properties.topicAlias),typeof d<"u")if(s.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)s=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",s,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(s,d))r.log("handlePublish :: registered topic: %s - alias: %d",s,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(s,a,i,(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(i,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,i,(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",s,a,i),r.handleMessage(i,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",s,a,i),r.handleMessage(i,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};o.default=t}),yu=pe((o,e)=>{e.exports={version:"5.15.0"}}),Jt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.MQTTJS_VERSION=o.nextTick=o.ErrorWithSubackPacket=o.ErrorWithReasonCode=void 0,o.applyMixin=r;var e=class Fa extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Fa.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};o.ErrorWithReasonCode=e;var t=class $a extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,$a.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};o.ErrorWithSubackPacket=t;function r(i,n,s=!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))(s||c!=="constructor")&&Object.defineProperty(i.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}o.nextTick=typeof Le?.nextTick=="function"?Le.nextTick:i=>{setTimeout(i,0)},o.MQTTJS_VERSION=yu().version}),Qr=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=void 0;var e=Jt();o.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,i)=>{let{messageId:n}=i,s=i.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",s),s){case"pubcomp":case"puback":{let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=i.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${o.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,i);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,i);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};o.default=t}),vu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Jt(),t=Qr(),r=(i,n)=>{let{options:s}=i,a=s.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);i.emit("error",c);return}i.handleAuth(n,(c,u)=>{if(c){i.emit("error",c);return}if(l===24)i.reconnecting=!1,i._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);i.emit("error",d)}})};o.default=r}),wu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof Le=="object"&&Le?Le:{},i=(g,f,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,b,y):console.error(`[${b}] ${f}: ${g}`)},n=globalThis.AbortController,s=globalThis.AbortSignal;if(typeof n>"u"){s=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new s;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!1,i("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 sr{heap;length;static#l=!1;static create(f){let b=c(f);if(!b)return[];sr.#l=!0;let y=new sr(f,b);return sr.#l=!1,y}constructor(f,b){if(!sr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class qa{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:b=>f.#t(b),backgroundFetch:(b,y,w,m)=>f.#N(b,y,w,m),moveToTail:b=>f.#C(b),indexes:b=>f.#k(b),rindexes:b=>f.#x(b),isStale:b=>f.#p(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}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:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:S,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:O,maxSize:C=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:$,memoMethod:D,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:K,allowStaleOnFetchAbort:W,ignoreFetchAbort:re}=f;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let F=b?c(b):Array;if(!F)throw new Error("invalid max value: "+b);if(this.#l=b,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(D!==void 0&&typeof D!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=D,$!==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(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new F(b),this.#h=new F(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof S=="function"&&(this.#m=S),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!O,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!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=!!_,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#L()}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),i("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",Z,qa))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#L(){let f=new u(this.#l),b=new u(this.#l);this.#f=f,this.#w=b,this.#j=(m,_,x=e.now())=>{if(b[m]=_!==0?x:0,f[m]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},_+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=b[_];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let S=m.now-v;m.remainingTTL=x-S}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let _=setTimeout(()=>y=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=f[_],v=b[_];if(!x||!v)return 1/0;let S=(y||w())-v;return x-S},this.#p=m=>{let _=b[m],x=f[m];return!!x&&!!_&&(y||w())-_>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=b=>{this.#b-=f[b],f[b]=0},this.#U=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!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=(b,y,w)=>{if(f[b]=y,this.#d){let m=this.#d-f[b];for(;this.#b>m;)this.#R(!0)}this.#b+=f[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,b,y)=>{};#U=(f,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#D(b)||((f||!this.#p(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#D(b)||((f||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#D(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#x())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*rkeys(){for(let f of this.#x()){let b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#x())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,b={}){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(f,b=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}rforEach(f,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}purgeStale(){let f=!1;for(let b of this.#x({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),f=!0);return f}info(f){let b=this.#n.get(f);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[b],x=this.#w[b];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let f=[];for(let b of this.#k({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[b];let x=e.now()-this.#w[b];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[b]),f.unshift([y,_])}return f}load(f){this.clear();for(let[b,y]of f){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(f,b,y={}){if(b===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:S=this.noUpdateTTL}=y,E=this.#U(f,b,y.size||0,x);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#R(!1):this.#i,this.#r[I]=f,this.#e[I]=b,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"),S=!1;else{this.#C(I);let O=this.#e[I];if(b!==O){if(this.#A&&this.#t(O)){O.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:C}=O;C!==void 0&&!_&&(this.#_&&this.#m?.(C,f,"set"),this.#u&&this.#s?.push([C,f,"set"]))}else _||(this.#_&&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]=b,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.#L(),this.#f&&(S||this.#j(I,w,m),v&&this.#E(v,I)),!_&&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.#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,b;for(;b=f?.shift();)this.#g?.(...b)}}}#R(f){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),f&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(f,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(f);if(m!==void 0){let _=this.#e[m];if(this.#t(_)&&_.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(f);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#N(f,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let _=new n,{signal:x}=y;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:y,context:w},S=(T,$=!1)=>{let{aborted:D}=_.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(D&&!$?(y.status.fetchAborted=!0,y.status.fetchError=_.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),D&&!U&&!$)return I(_.signal.reason);let oe=C;return this.#e[b]===C&&(T===void 0?oe.__staleWhileFetching?this.#e[b]=oe.__staleWhileFetching:this.#S(f,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},E=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:$}=_.signal,D=$&&y.allowStaleOnFetchAbort,U=D||y.allowStaleOnFetchRejection,oe=U||y.noDeleteOnFetchRejection,K=C;if(this.#e[b]===C&&(!oe||K.__staleWhileFetching===void 0?this.#S(f,"fetch"):D||(this.#e[b]=K.__staleWhileFetching)),U)return y.status&&K.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),K.__staleWhileFetching;if(K.__returned===K)throw T},O=(T,$)=>{let D=this.#P?.(f,m,v);D&&D instanceof Promise&&D.then(U=>T(U===void 0?void 0:U),$),_.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>S(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let C=new Promise(O).then(S,E),j=Object.assign(C,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(f,j,{...v.options,status:void 0}),b=this.#n.get(f)):this.#e[b]=j,j}#t(f){if(!this.#A)return!1;let b=f;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(f,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:S=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:D,signal:U}=b;if(!this.#A)return D&&(D.fetch="get"),this.get(f,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:D});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:S,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:O,allowStaleOnFetchAbort:j,ignoreFetchAbort:C,status:D,signal:U},K=this.#n.get(f);if(K===void 0){D&&(D.fetch="miss");let W=this.#N(f,K,oe,T);return W.__returned=W}else{let W=this.#e[K];if(this.#t(W)){let M=y&&W.__staleWhileFetching!==void 0;return D&&(D.fetch="inflight",M&&(D.returnedStale=!0)),M?W.__staleWhileFetching:W.__returned=W}let re=this.#p(K);if(!$&&!re)return D&&(D.fetch="hit"),this.#C(K),w&&this.#I(K),D&&this.#E(D,K),W;let F=this.#N(f,K,oe,T),Z=F.__staleWhileFetching!==void 0&&y;return D&&(D.fetch=re?"stale":"refresh",Z&&re&&(D.returnedStale=!0)),Z?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,b={}){let y=await this.fetch(f,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=b,x=this.get(f,_);if(!m&&x!==void 0)return x;let v=y(f,x,{options:_,context:w});return this.set(f,v,_),v}get(f,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=b,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],S=this.#t(v);return _&&this.#E(_,x),this.#p(x)?(_&&(_.get="stale"),S?(_&&y&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),_&&y&&(_.returnedStale=!0),y?v:void 0)):(_&&(_.get="hit"),S?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#B(f,b){this.#h[b]=f,this.#c[f]=b}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#B(this.#h[f],this.#c[f]),this.#B(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(f,b){let y=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(y=!0,this.#i===1)this.#F(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(m,f,b),this.#u&&this.#s?.push([m,f,b])),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 _=this.#h[w];this.#c[_]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#F("delete")}#F(f){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#_&&this.#m?.(y,w,f),this.#u&&this.#s?.push([y,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.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};o.LRUCache=p}),yt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.ContainerIterator=o.Container=o.Base=void 0;var e=class{constructor(i=0){this.iteratorType=i}equals(i){return this.o===i.o}};o.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};o.Base=t;var r=class extends t{};o.Container=r}),_u=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=yt(),t=class extends e.Base{constructor(i=[]){super(),this.S=[];let n=this;i.forEach(function(s){n.push(s)})}clear(){this.i=0,this.S=[]}push(i){return this.S.push(i),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;o.default=r}),ku=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=yt(),t=class extends e.Base{constructor(i=[]){super(),this.j=0,this.q=[];let n=this;i.forEach(function(s){n.push(s)})}clear(){this.q=[],this.i=this.j=0}push(i){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let s=this.i;for(let a=0;a<s;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=i}else this.q[this.j+this.i]=i;return++this.i}pop(){if(this.i===0)return;let i=this.q[this.j++];return this.i-=1,i}front(){if(this.i!==0)return this.q[this.j]}},r=t;o.default=r}),xu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=yt(),t=class extends e.Base{constructor(i=[],n=function(a,l){return a>l?-1:a<l?1:0},s=!0){if(super(),this.v=n,Array.isArray(i))this.C=s?[...i]:i;else{this.C=[];let l=this;i.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(i){let n=this.C[i];for(;i>0;){let s=i-1>>1,a=this.C[s];if(this.v(a,n)<=0)break;this.C[i]=a,i=s}this.C[i]=n}k(i,n){let s=this.C[i];for(;i<n;){let a=i<<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,s)>=0)break;this.C[i]=c,i=a}this.C[i]=s}clear(){this.i=0,this.C.length=0}push(i){this.C.push(i),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let i=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),i}top(){return this.C[0]}find(i){return this.C.indexOf(i)>=0}remove(i){let n=this.C.indexOf(i);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(i){let n=this.C.indexOf(i);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;o.default=r}),ko=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=yt(),t=class extends e.Container{},r=t;o.default=r}),vt=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ha=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.RandomIterator=void 0;var e=yt(),t=vt(),r=class extends e.ContainerIterator{constructor(i,n){super(n),this.o=i,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(i){this.container.setElementByPos(this.o,i)}};o.RandomIterator=r}),Su=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(ko()),t=Ha();function r(a){return a&&a.t?a:{default:a}}var i=class Wa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Wa(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 i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-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 i(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)()}},s=n;o.default=s}),Eu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(ko()),t=yt(),r=vt();function i(l){return l&&l.t?l:{default:l}}var n=class za 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 za(this.o,this.h,this.container,this.iteratorType)}},s=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=s;o.default=a}),Au=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(ko()),t=Ha();function r(a){return a&&a.t?a:{default:a}}var i=class Va extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Va(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 i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-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 i(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)()}},s=n;o.default=s}),Iu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.TreeNodeEnableIndex=o.TreeNode=void 0;var e=class{constructor(r,i){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=i}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 i=r.tt;for(;i.U===r;)r=i,i=r.tt;r=i}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let i=r.tt;for(;i.W===r;)r=i,i=r.tt;return r.W!==i?i:r}}te(){let r=this.tt,i=this.W,n=i.U;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.U=this,this.tt=i,this.W=n,n&&(n.tt=this),i}se(){let r=this.tt,i=this.U,n=i.W;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.W=this,this.tt=i,this.U=n,n&&(n.tt=this),i}};o.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)}};o.TreeNodeEnableIndex=t}),Ka=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Iu(),t=yt(),r=vt(),i=class extends t.Container{constructor(s=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=s,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:b,curNode:y}=g;f.ie(),b.ie(),y.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(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)s=s.W;else if(c>0)l=s,s=s.U;else return s}return l}Z(s,a){let l=this.h;for(;s;)this.v(s.u,a)<=0?s=s.W:(l=s,s=s.U);return l}$(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)l=s,s=s.W;else if(c>0)s=s.U;else return s}return l}rr(s,a){let l=this.h;for(;s;)this.v(s.u,a)<0?(l=s,s=s.W):s=s.U;return l}ue(s){for(;;){let a=s.tt;if(a===this.h)return;if(s.ee===1){s.ee=0;return}if(s===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,s=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,s=a)}}}fe(s){if(this.i===1)return this.clear(),this.h;let a=s;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[s.u,a.u]=[a.u,s.u],[s.l,a.l]=[a.l,s.l],s=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(s,a){return s===void 0?!1:this.oe(s.U,a)||a(s)?!0:this.oe(s.W,a)}he(s){for(;;){let a=s.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,s=l;continue}else if(s===a.W){if(s.ee=0,s.U&&(s.U.tt=a),s.W&&(s.W.tt=l),a.W=s.U,l.U=s.W,s.U=a,s.W=l,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}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,s=l;continue}else if(s===a.U){if(s.ee=0,s.U&&(s.U.tt=l),s.W&&(s.W.tt=a),l.W=s.U,a.U=s.W,s.U=l,s.W=a,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(s,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(s,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,s);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(s,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,s);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(s,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 b=this.v(f.u,s);if(b===0){f.l=a;return}else if(b>0){let y=f.L(),w=this.v(y.u,s);if(w===0){y.l=a;return}else w<0&&(c=new this.re(s,a),y.W===void 0?(y.W=c,c.tt=y):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,s);if(f>0){if(c.U===void 0){c.U=new this.re(s,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(s,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(s,a){for(;s;){let l=this.v(s.u,a);if(l<0)s=s.W;else if(l>0)s=s.U;else return s}return s||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(s,a){let l=s.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(s){if(s<0||s>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return s===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(s){if(this.i===0)return!1;let a=this.I(this.Y,s);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(s){let a=s.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return s.iteratorType===0?l&&s.next():(!l||a.U===void 0)&&s.next(),this.V(a),s}forEach(s){let a=0;for(let l of this)s(l,a++,this)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===s){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let s=function(a){return a?Math.max(s(a.U),s(a.W))+1:0};return s(this.Y)}},n=i;o.default=n}),Ga=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=yt(),t=vt(),r=class extends e.ContainerIterator{constructor(n,s,a){super(a),this.o=n,this.h=s,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,s=this.h.tt;if(n===this.h)return s?s.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==s;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},i=r;o.default=i}),Tu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(Ka()),t=i(Ga()),r=vt();function i(l){return l&&l.t?l:{default:l}}var n=class Ya 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 Ya(this.o,this.h,this.container,this.iteratorType)}},s=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=s;o.default=a}),Cu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(Ka()),t=i(Ga()),r=vt();function i(l){return l&&l.t?l:{default:l}}var n=class Ja 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 Ja(this.o,this.h,this.container,this.iteratorType)}},s=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=s;o.default=a}),Qa=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Xa=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.HashContainerIterator=o.HashContainer=void 0;var e=yt(),t=i(Qa()),r=vt();function i(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})}};o.HashContainerIterator=n;var s=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}};o.HashContainer=s}),Pu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Xa(),t=vt(),r=class Za 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 Za(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(s=[]){super();let a=this;s.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(s,a){return this.M(s,void 0,a)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=this.p;for(;s--;)a=a.B;return a.u}find(s,a){let l=this.I(s,a);return new r(l,this.h,this)}forEach(s){let a=0,l=this.p;for(;l!==this.h;)s(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let s=this.p;for(;s!==this.h;)yield s.u,s=s.B}).bind(this)()}},n=i;o.default=n}),Ou=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Xa(),t=i(Qa()),r=vt();function i(l){return l&&l.t?l:{default:l}}var n=class el 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 el(this.o,this.h,this.container,this.iteratorType)}},s=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=s;o.default=a}),Mu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),Object.defineProperty(o,"Deque",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(o,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(o,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(o,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(o,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(o,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(o,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(o,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(o,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(o,"Vector",{enumerable:!0,get:function(){return i.default}});var e=d(_u()),t=d(ku()),r=d(xu()),i=d(Su()),n=d(Eu()),s=d(Au()),a=d(Tu()),l=d(Cu()),c=d(Pu()),u=d(Ou());function d(p){return p&&p.t?p:{default:p}}}),Ru=pe((o,e)=>{le(),ue(),ce();var t=Mu().OrderedSet,r=mt()("number-allocator:trace"),i=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 s(a,l){if(!(this instanceof s))return new s(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}s.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},s.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},s.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},s.prototype.free=function(a){if(a<this.min||a>this.max){i("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)},s.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},s.prototype.intervalCount=function(){return this.ss.size()},s.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=s}),tl=pe((o,e)=>{le(),ue(),ce();var t=Ru();e.exports.NumberAllocator=t}),Nu=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=wu(),t=tl(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(i){i>0&&(this.aliasToTopic=new e.LRUCache({max:i}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,i),this.max=i,this.length=0)}put(i,n){if(n===0||n>this.max)return!1;let s=this.aliasToTopic.get(n);return s&&delete this.topicToAlias[s],this.aliasToTopic.set(n,i),this.topicToAlias[i]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(i){return this.aliasToTopic.get(i)}getAliasByTopic(i){let n=this.topicToAlias[i];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]}};o.default=r}),Lu=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(o,"__esModule",{value:!0});var t=Qr(),r=e(Nu()),i=Jt(),n=(s,a)=>{s.log("_handleConnack");let{options:l}=s,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(s.connackTimer),delete s.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){s.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(s.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)s.reconnecting=!1,s._onConnect(a);else if(c>0){let u=new i.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);s.emit("error",u),s.options.reconnectOnConnackError&&s._cleanUp(!0)}};o.default=n}),ju=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(t,r,i)=>{t.log("handling pubrel packet");let n=typeof i<"u"?i:t.noop,{messageId:s}=r,a={cmd:"pubcomp",messageId:s};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)}))})};o.default=e}),Uu=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(bu()),r=e(vu()),i=e(Lu()),n=e(Qr()),s=e(ju()),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,s.default)(l,c,u);break;case"connack":(0,i.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}};o.default=a}),rl=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__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(){}};o.default=e}),Du=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__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={}}};o.default=e}),Bu=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(o,"__esModule",{value:!0}),o.TypedEventEmitter=void 0;var t=e((Ut(),Ne(It))),r=Jt(),i=class{};o.TypedEventEmitter=i,(0,r.applyMixin)(i,t.default)}),Xr=pe((o,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((o,e)=>{le(),ue(),ce();var t=Xr().default;function r(i,n){if(t(i)!="object"||!i)return i;var s=i[Symbol.toPrimitive];if(s!==void 0){var a=s.call(i,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((o,e)=>{le(),ue(),ce();var t=Xr().default,r=Fu();function i(n){var s=r(n,"string");return t(s)=="symbol"?s:s+""}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((o,e)=>{le(),ue(),ce();var t=$u();function r(i,n,s){return(n=t(n))in i?Object.defineProperty(i,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):i[n]=s,i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((o,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}),Wu=pe((o,e)=>{le(),ue(),ce();function t(r,i){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var s,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,i===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(s=l.call(n)).done)&&(u.push(s.value),u.length!==i);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}),zu=pe((o,e)=>{le(),ue(),ce();function t(r,i){(i==null||i>r.length)&&(i=r.length);for(var n=0,s=Array(i);n<i;n++)s[n]=r[n];return s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Vu=pe((o,e)=>{le(),ue(),ce();var t=zu();function r(i,n){if(i){if(typeof i=="string")return t(i,n);var s={}.toString.call(i).slice(8,-1);return s==="Object"&&i.constructor&&(s=i.constructor.name),s==="Map"||s==="Set"?Array.from(i):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(i,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Ku=pe((o,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}),Gu=pe((o,e)=>{le(),ue(),ce();var t=Hu(),r=Wu(),i=Vu(),n=Ku();function s(a,l){return t(a)||r(a,l)||i(a,l)||n()}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),nl=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(o,function(t){var r=function(g){return function(f){var b=g(f);return f.add(b),b}},i=function(g){return function(f,b){return g.set(f,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,f){return function(b){var y=f.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<s){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=i(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Yu=pe((o,e)=>{le(),ue(),ce();function t(i,n,s,a,l,c,u){try{var d=i[c](u),p=d.value}catch(g){return void s(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(i){return function(){var n=this,s=arguments;return new Promise(function(a,l){var c=i.apply(n,s);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}),il=pe((o,e)=>{le(),ue(),ce();function t(r,i){this.v=r,this.k=i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ol=pe((o,e)=>{le(),ue(),ce();function t(r,i,n,s){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(b){return this._invoke(g,f,b)})}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,i,n,s)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),sl=pe((o,e)=>{le(),ue(),ce();var t=ol();function r(){var i,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,_,x){var v=m&&m.prototype instanceof d?m:d,S=Object.create(v.prototype);return t(S,"_invoke",(function(E,I,O){var C,j,T,$=0,D=O||[],U=!1,oe={p:0,n:0,v:i,a:K,f:K.bind(i,4),d:function(W,re){return C=W,j=0,T=i,oe.n=re,u}};function K(W,re){for(j=W,T=re,n=0;!U&&$&&!F&&n<D.length;n++){var F,Z=D[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]=i):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?i: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=i}else if((n=(U=oe.n<0)?T:E.call(I,oe))!==u)break}catch(Z){C=i,j=1,T=Z}finally{$=1}}return{value:n,done:U}}})(w,_,x),!0),S}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(f);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return p.prototype=g,t(b,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),al=pe((o,e)=>{le(),ue(),ce();var t=il(),r=ol();function i(n,s){function a(c,u,d,p){try{var g=n[c](u),f=g.value;return f instanceof t?s.resolve(f.v).then(function(b){a("next",b,d,p)},function(b){a("throw",b,d,p)}):s.resolve(f).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,p)})}catch(b){p(b)}}var l;this.next||(r(i.prototype),r(i.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new s(function(g,f){a(c,d,g,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),ll=pe((o,e)=>{le(),ue(),ce();var t=sl(),r=al();function i(n,s,a,l,c){return new r(t().w(n,s,a,l),c||Promise)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),Ju=pe((o,e)=>{le(),ue(),ce();var t=ll();function r(i,n,s,a,l){var c=t(i,n,s,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}),Qu=pe((o,e)=>{le(),ue(),ce();function t(r){var i=Object(r),n=[];for(var s in i)n.unshift(s);return function a(){for(;n.length;)if((s=n.pop())in i)return a.value=s,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Xu=pe((o,e)=>{le(),ue(),ce();var t=Xr().default;function r(i){if(i!=null){var n=i[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(n)return n.call(i);if(typeof i.next=="function")return i;if(!isNaN(i.length))return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}}}throw new TypeError(t(i)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Zu=pe((o,e)=>{le(),ue(),ce();var t=il(),r=sl(),i=Ju(),n=ll(),s=al(),a=Qu(),l=Xu();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(_){w||(w={stop:function(){return m(_.a,2)},catch:function(){return _.v},abrupt:function(x,v){return m(_.a,f[x],v)},delegateYield:function(x,v,S){return w.resultName=v,m(_.d,l(x),S)},finish:function(x){return m(_.f,x)}},m=function(x,v,S){_.p=w.prev,_.n=w.next;try{return x(v,S)}finally{w.next=_.n}}),w.resultName&&(w[w.resultName]=_.v,w.resultName=void 0),w.sent=_.v,w.next=_.n;try{return y.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,_){return u.w(b(y),w,m,_&&_.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:s,async:function(y,w,m,_,x){return(g(w)?n:i)(b(y),w,m,_,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}),ed=pe((o,e)=>{le(),ue(),ce();var t=Zu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),td=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,qu(),Gu(),nl(),Yu(),ed()):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))})(o,function(t,r,i,n,s,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%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(_){var x=_.call;return s(a.mark(function v(){var S,E,I,O;return a.wrap(function(C){for(;;)switch(C.prev=C.next){case 0:return S=new MessageChannel,E=S.port1,I=S.port2,C.next=1,x("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(_){var x=_.call;return(function(){var v=s(a.mark(function S(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,x("disconnect",{portId:I});case 2:case"end":return O.stop()}},S)}));return function(S){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function g(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var _=new Map;return b.set(m,_),_},w=function(m){var _=p(m);return function(x){var v=y(x);x.addEventListener("message",function(D){var U=D.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(x)&&x.start();for(var S=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(K,W){var re=n.generateUniqueNumber(v);v.set(re,{reject:W,resolve:K}),U===null?x.postMessage({id:re,method:D},oe):x.postMessage({id:re,method:D,params:U},oe)})},E=function(D,U){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:D,params:U},oe)},I={},O=0,C=Object.entries(_);O<C.length;O++){var j=i(C[O],2),T=j[0],$=j[1];I=f(f({},I),{},r({},T,$({call:S,notify:E})))}return f({},I)}};t.createBroker=w})}),rd=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,Xr(),td(),nl()):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))})(o,function(t,r,i,n){var s=new Map([[0,null]]),a=new Map([[0,null]]),l=i.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){s.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,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);s.set(m,w);var _=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=s.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,b),s.get(m)===w&&_())})};return _(),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,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];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 _=a.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(a.delete(m),p.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),nd=pe((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,rd()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(o,function(t,r){var i=function(d,p){var g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(f);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),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)})()})();`,s=i(r.load,n),a=function(d){return s().clearInterval(d)},l=function(d){return s().clearTimeout(d)},c=function(){var d;return(d=s()).setInterval.apply(d,arguments)},u=function(){var d;return(d=s()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Zr=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.isReactNativeBrowser=o.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&Le?.versions?!Object.prototype.hasOwnProperty.call(Le.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",i=e()||t()||r();o.isWebWorker=t(),o.isReactNativeBrowser=r(),o.default=i}),id=pe(o=>{le(),ue(),ce();var e=o&&o.__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=o&&o.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=o&&o.__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(o,"__esModule",{value:!0});var i=nd(),n=r(Zr()),s={set:i.setInterval,clear:i.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return s;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?s:a}};o.default=l}),cl=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(id()),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(i,n){this.client=i,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(i.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(i){if(i*=1e3,isNaN(i)||i<=0||i>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${i}`);this._keepalive=i,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${i}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let i=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+i,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)}};o.default=r}),Si=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(v,S,E,I){I===void 0&&(I=E);var O=Object.getOwnPropertyDescriptor(S,E);(!O||("get"in O?!S.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return S[E]}}),Object.defineProperty(v,I,O)}:function(v,S,E,I){I===void 0&&(I=E),v[I]=S[E]}),t=o&&o.__setModuleDefault||(Object.create?function(v,S){Object.defineProperty(v,"default",{enumerable:!0,value:S})}:function(v,S){v.default=S}),r=o&&o.__importStar||(function(){var v=function(S){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(S)};return function(S){if(S&&S.__esModule)return S;var E={};if(S!=null)for(var I=v(S),O=0;O<I.length;O++)I[O]!=="default"&&e(E,S,I[O]);return t(E,S),E}})(),i=o&&o.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(o,"__esModule",{value:!0});var n=i(pu()),s=Bt(),a=i(gu()),l=i(mt()),c=r(Da()),u=i(Ba()),d=i(Uu()),p=i(rl()),g=i(Du()),f=Jt(),b=Bu(),y=i(cl()),w=r(Zr()),m=globalThis.setImmediate||((...v)=>{let S=v.shift();(0,f.nextTick)(()=>{S(...v)})}),_={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 Ei extends b.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(S,E){super(),this.options=E||{};for(let I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Ei.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:Ei.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=S,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(S,E){E()}handleMessage(S,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let S=new s.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",D=>{this.log("parser :: on packet push to packets array."),O.push(D)});let C=()=>{this.log("work :: getting next packet in queue");let D=O.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=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(O.length)(0,f.nextTick)(C);else{let D=I;I=null,D()}};S._write=(D,U,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(D),C()};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(S),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 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(S,E,I,O){this.log("publish :: message `%s` to topic `%s`",E,S);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:D,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:S,payload:E,qos:j,retain:T,messageId:K,dup:$};switch(C.protocolVersion===5&&(W.properties=D),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(S,E,I){return new Promise((O,C)=>{this.publish(S,E,I,(j,T)=>{j?C(j):O(T)})})}subscribe(S,E,I){let O=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let C=!1,j=[];typeof S=="string"?(S=[S],j=S):Array.isArray(S)?j=S:typeof S=="object"&&(C=S.resubscribe,delete S.resubscribe,j=Object.keys(S));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:D}=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=D),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",Z.topic,Z.qos),U.push(Z)}};if(Array.isArray(S)?S.forEach(re=>{this.log("subscribe: array topic %s",re),oe(re)}):Object.keys(S).forEach(re=>{this.log("subscribe: object topic %s, %o",re,S[re]),oe(re,S[re])}),!U.length)return I(null,[]),this;let K=(re,F)=>{let Z={cmd:"subscribe",subscriptions:re,messageId:F};if(D&&(Z.properties=D),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Q=[];re.forEach(be=>{if(this.options.reconnectPeriod>0){let te={qos:be.qos};O===5&&(te.nl=be.nl||!1,te.rap=be.rap||!1,te.rh=be.rh||0,te.properties=be.properties),this._resubscribeTopics[be.topic]=te,Q.push(be.topic)}}),this.messageIdToTopic[Z.messageId]=Q}let M=new Promise((Q,be)=>{this.outgoing[Z.messageId]={volatile:!0,cb(te,we){if(!te){let{granted:G}=we;for(let L=0;L<G.length;L+=1)re[L].qos=G[L]}te?be(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(S,E){return new Promise((I,O)=>{this.subscribe(S,E,(C,j)=>{C?O(C):I(j)})})}unsubscribe(S,E,I){typeof S=="string"&&(S=[S]),typeof E=="function"&&(I=E),I=I||this.noop;let O=c.validateTopics(S);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 S=="string"?T.unsubscriptions=[S]:Array.isArray(S)&&(T.unsubscriptions=S),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(S,E){return new Promise((I,O)=>{this.unsubscribe(S,E,(C,j)=>{C?O(C):I(j)})})}end(S,E,I){this.log("end :: (%s)",this.options.clientId),(S==null||typeof S!="boolean")&&(I=I||E,E=S,S=!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,S),this._cleanUp(S,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(O)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!S&&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(S,E){return new Promise((I,O)=>{this.end(S,E,C=>{C?O(C):I()})})}removeOutgoingMessage(S){if(this.outgoing[S]){let{cb:E}=this.outgoing[S];this._removeOutgoingAndStoreMessage(S,()=>{E(new Error("Message removed"))})}return this}reconnect(S){this.log("client reconnect");let E=()=>{S?(this.options.incomingStore=S.incomingStore,this.options.outgoingStore=S.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(S=>{this.outgoing[S].volatile&&typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(S=>{typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_removeTopicAliasAndRecoverTopicName(S){let E;S.properties&&(E=S.properties.topicAlias);let I=S.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");S.topic=I}E&&delete S.properties.topicAlias}_checkDisconnecting(S){return this.disconnecting&&(S&&S!==this.noop?S(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(S,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",S),S)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(S,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",S.cmd);let O=S,C;if(O.cmd==="publish"&&(O=(0,a.default)(S),C=this._removeTopicAliasAndRecoverTopicName(O),C))return E&&E(C);this.outgoingStore.put(O,j=>{if(j)return E&&E(j);I(),this._writePacket(S,E)})}_applyTopicAlias(S){if(this.options.protocolVersion===5&&S.cmd==="publish"){let E;S.properties&&(E=S.properties.topicAlias);let I=S.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?(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(S.topic="",S.properties={...S.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(S){this.log("noop ::",S)}_writePacket(S,E){this.log("_writePacket :: packet: %O",S),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",S),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(S,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(S,E,I,O){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let C=this._applyTopicAlias(S);if(C){E(C);return}if(!this.connected){if(S.cmd==="auth"){this._writePacket(S,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(S,E,I);return}if(O){this._writePacket(S,E);return}switch(S.cmd){case"publish":break;case"pubrel":this._storeAndSend(S,E,I);return;default:this._writePacket(S,E);return}switch(S.qos){case 2:case 1:this._storeAndSend(S,E,I);break;default:this._writePacket(S,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(S,E,I){this.log("_storePacket :: packet: %o",S),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let O=S;if(O.cmd==="publish"){O=(0,a.default)(S);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 y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(S=!1){this.keepaliveManager&&this.options.keepalive&&(S||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 S=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&S.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<S.length;E++){let I={};I[S[E]]=this._resubscribeTopics[S[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[S[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(S){if(this.disconnected){this.emit("connect",S);return}this.connackPacket=S,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(D,U){$&&$(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)):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",S)):E()}),j()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let S=this._storeProcessingQueue[0];if(S&&S.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let S of this._storeProcessingQueue)S.cbStorePut&&S.cbStorePut(new Error("Connection closed")),S.callback&&S.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(S,E){delete this.outgoing[S],this.outgoingStore.del({messageId:S},(I,O)=>{E(I,O),this.messageIdProvider.deallocate(S),this._invokeStoreProcessingQueue()})}};o.default=x}),od=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=tl(),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()}};o.default=t});function sd(){if(Ai)return _r;Ai=!0;let o=2147483647,e=36,t=1,r=26,i=38,n=700,s=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,b=String.fromCharCode;function y(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 D=C.split("."),U=w(D,j).join(".");return $+U}function _(C){let j=[],T=0,$=C.length;for(;T<$;){let D=C.charCodeAt(T++);if(D>=55296&&D<=56319&&T<$){let U=C.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=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},S=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+i))},I=function(C){let j=[],T=C.length,$=0,D=a,U=s,oe=C.lastIndexOf(l);oe<0&&(oe=0);for(let K=0;K<oe;++K)C.charCodeAt(K)>=128&&y("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&&y("invalid-input");let M=v(C.charCodeAt(K++));M>=e&&y("invalid-input"),M>f((o-$)/F)&&y("overflow"),$+=M*F;let Q=Z<=U?t:Z>=U+r?r:Z-U;if(M<Q)break;let be=e-Q;F>f(o/be)&&y("overflow"),F*=be}let re=j.length+1;U=E($-W,re,W==0),f($/re)>o-D&&y("overflow"),D+=f($/re),$%=re,j.splice($++,0,D)}return String.fromCodePoint(...j)},O=function(C){let j=[];C=_(C);let T=C.length,$=a,D=0,U=s;for(let W of C)W<128&&j.push(b(W));let oe=j.length,K=oe;for(oe&&j.push(l);K<T;){let W=o;for(let F of C)F>=$&&F<W&&(W=F);let re=K+1;W-$>f((o-D)/re)&&y("overflow"),D+=(W-$)*re,$=W;for(let F of C)if(F<$&&++D>o&&y("overflow"),F===$){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 be=Z-Q,te=e-Q;j.push(b(S(Q+be%te,0))),Z=f(be/te)}j.push(b(S(Z,0))),U=E(D,re,K===oe),D=0,++K}++D,++$}return j.join("")};return _r={version:"2.3.1",ucs2:{decode:_,encode:x},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})}},_r}var _r,Ai,Et,ad=Je(()=>{le(),ue(),ce(),_r={},Ai=!1,Et=sd(),Et.decode,Et.encode,Et.toASCII,Et.toUnicode,Et.ucs2,Et.version});function ld(){return Ti||(Ti=!0,Ii=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var o={},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;o[e]=r;for(e in o)return!1;if(typeof Object.keys=="function"&&Object.keys(o).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(o).length!==0)return!1;var i=Object.getOwnPropertySymbols(o);if(i.length!==1||i[0]!==e||!Object.prototype.propertyIsEnumerable.call(o,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(o,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ii}function cd(){return Pi||(Pi=!0,Ci=Error),Ci}function ud(){return Mi||(Mi=!0,Oi=EvalError),Oi}function dd(){return Ni||(Ni=!0,Ri=RangeError),Ri}function hd(){return ji||(ji=!0,Li=ReferenceError),Li}function ul(){return Di||(Di=!0,Ui=SyntaxError),Ui}function hr(){return Fi||(Fi=!0,Bi=TypeError),Bi}function fd(){return qi||(qi=!0,$i=URIError),$i}function pd(){if(Hi)return kr;Hi=!0;var o=typeof Symbol<"u"&&Symbol,e=ld();return kr=function(){return typeof o!="function"||typeof Symbol!="function"||typeof o("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},kr}function md(){if(Wi)return xr;Wi=!0;var o={__proto__:null,foo:{}},e=Object;return xr=function(){return{__proto__:o}.foo===o.foo&&!(o instanceof e)},xr}function gd(){if(zi)return Sr;zi=!0;var o="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",i=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},s=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 Sr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(o+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,i(c,arguments));return Object(y)===y?y:this}return l.apply(a,i(c,arguments))},p=t(0,l.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+s(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},Sr}function xo(){if(Vi)return Er;Vi=!0;var o=gd();return Er=Function.prototype.bind||o,Er}function bd(){if(Ki)return Ar;Ki=!0;var o=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=xo();return Ar=t.call(o,e),Ar}function Qt(){if(Gi)return Ir;Gi=!0;var o,e=cd(),t=ud(),r=dd(),i=hd(),n=ul(),s=hr(),a=fd(),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 s},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=pd()(),f=md()(),b=Object.getPrototypeOf||(f?function(K){return K.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?o:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?o:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?o:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):o,"%AsyncFromSyncIteratorPrototype%":o,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?o:Atomics,"%BigInt%":typeof BigInt>"u"?o:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?o:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?o:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?o:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?o:Float32Array,"%Float64Array%":typeof Float64Array>"u"?o:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?o:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?o:Int8Array,"%Int16Array%":typeof Int16Array>"u"?o:Int16Array,"%Int32Array%":typeof Int32Array>"u"?o:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):o,"%JSON%":typeof JSON=="object"?JSON:o,"%Map%":typeof Map>"u"?o:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?o:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?o:Promise,"%Proxy%":typeof Proxy>"u"?o:Proxy,"%RangeError%":r,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?o:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?o:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?o:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?o:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):o,"%Symbol%":g?Symbol:o,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?o:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?o:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?o:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?o:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?o:WeakMap,"%WeakRef%":typeof WeakRef>"u"?o:WeakRef,"%WeakSet%":typeof WeakSet>"u"?o:WeakSet};if(b)try{null.error}catch(K){var _=b(b(K));m["%Error.prototype%"]=_}var x=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&&b&&(re=b(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"]},S=xo(),E=bd(),I=S.call(Function.call,Array.prototype.concat),O=S.call(Function.apply,Array.prototype.splice),C=S.call(Function.call,String.prototype.replace),j=S.call(Function.call,String.prototype.slice),T=S.call(Function.call,RegExp.prototype.exec),$=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,D=/\\(\\)?/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,be){F[F.length]=Q?C(be,D,"$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===y&&(Z=x(re)),typeof Z>"u"&&!W)throw new s("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 Ir=function(K,W){if(typeof K!="string"||K.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new s('"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,be=!1,te=Z.alias;te&&(F=te[0],O(re,I([0,1],te)));for(var we=1,G=!0;we<re.length;we+=1){var L=re[we],ne=j(L,0,1),z=j(L,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)throw new n("property names with quotes must have matching quotes");if((L==="constructor"||!G)&&(be=!0),F+="."+L,M="%"+F+"%",E(m,M))Q=m[M];else if(Q!=null){if(!(L in Q)){if(!W)throw new s("base intrinsic for "+K+" exists, but the property is not available.");return}if(u&&we+1>=re.length){var Y=u(Q,L);G=!!Y,G&&"get"in Y&&!("originalValue"in Y.get)?Q=Y.get:Q=Q[L]}else G=E(Q,L),Q=Q[L];G&&!be&&(m[M]=Q)}}return Q},Ir}function So(){if(Yi)return Tr;Yi=!0;var o=Qt(),e=o("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Tr=e,Tr}function dl(){if(Ji)return Cr;Ji=!0;var o=Qt(),e=o("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Cr=e,Cr}function yd(){if(Qi)return Pr;Qi=!0;var o=So(),e=ul(),t=hr(),r=dl();return Pr=function(i,n,s){if(!i||typeof i!="object"&&typeof i!="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(i,n);if(o)o(i,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:s,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)i[n]=s;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Pr}function vd(){if(Xi)return Or;Xi=!0;var o=So(),e=function(){return!!o};return e.hasArrayLengthDefineBug=function(){if(!o)return null;try{return o([],"length",{value:1}).length!==1}catch{return!0}},Or=e,Or}function wd(){if(Zi)return Mr;Zi=!0;var o=Qt(),e=yd(),t=vd()(),r=dl(),i=hr(),n=o("%Math.floor%");return Mr=function(s,a){if(typeof s!="function")throw new i("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new i("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in s&&r){var d=r(s,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(s,"length",a,!0,!0):e(s,"length",a)),s},Mr}function _d(){if(eo)return Wt;eo=!0;var o=xo(),e=Qt(),t=wd(),r=hr(),i=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||o.call(n,i),a=So(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var d=s(o,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return s(o,i,arguments)};return a?a(Wt,"apply",{value:c}):Wt.apply=c,Wt}function kd(){if(to)return Rr;to=!0;var o=Qt(),e=_d(),t=e(o("String.prototype.indexOf"));return Rr=function(r,i){var n=o(r,!!i);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Rr}var Ii,Ti,Ci,Pi,Oi,Mi,Ri,Ni,Li,ji,Ui,Di,Bi,Fi,$i,qi,kr,Hi,xr,Wi,Sr,zi,Er,Vi,Ar,Ki,Ir,Gi,Tr,Yi,Cr,Ji,Pr,Qi,Or,Xi,Mr,Zi,Wt,eo,Rr,to,xd=Je(()=>{le(),ue(),ce(),Ii={},Ti=!1,Ci={},Pi=!1,Oi={},Mi=!1,Ri={},Ni=!1,Li={},ji=!1,Ui={},Di=!1,Bi={},Fi=!1,$i={},qi=!1,kr={},Hi=!1,xr={},Wi=!1,Sr={},zi=!1,Er={},Vi=!1,Ar={},Ki=!1,Ir={},Gi=!1,Tr={},Yi=!1,Cr={},Ji=!1,Pr={},Qi=!1,Or={},Xi=!1,Mr={},Zi=!1,Wt={},eo=!1,Rr={},to=!1});function Eo(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function Sd(){!jt||!Nt||(jt=!1,Nt.length?at=Nt.concat(at):lr=-1,at.length&&hl())}function hl(){if(!jt){var o=setTimeout(Sd,0);jt=!0;for(var e=at.length;e;){for(Nt=at,at=[];++lr<e;)Nt&&Nt[lr].run();lr=-1,e=at.length}Nt=null,jt=!1,clearTimeout(o)}}function Ed(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];at.push(new fl(o,e)),at.length===1&&!jt&&setTimeout(hl,0)}function fl(o,e){this.fun=o,this.array=e}function We(){}function Ad(o){Eo("_linkedBinding")}function Id(o){Eo("dlopen")}function Td(){return[]}function Cd(){return[]}function Pd(o,e){if(!o)throw new Error(e||"assertion error")}function Od(){return!1}function Md(){return ft.now()/1e3}function nn(o){var e=Math.floor((Date.now()-ft.now())*.001),t=ft.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return o&&(r=r-o[0],i=i-o[1],i<0&&(r--,i+=Nr)),[r,i]}function _t(){return Ao}function Rd(o){return[]}var at,jt,Nt,lr,Bo,Fo,$o,qo,Ho,Wo,zo,Vo,Ko,Go,Yo,Jo,Qo,Xo,Zo,es,ts,rs,ns,is,os,mr,ss,as,ls,cs,us,ds,hs,fs,ps,ms,gs,bs,ys,vs,ws,_s,ks,xs,Ss,Es,As,Is,Ts,Cs,Ps,ft,on,Nr,Os,Ms,Rs,Ns,Ls,js,Us,Ds,Bs,Fs,$s,Ao,pl=Je(()=>{le(),ue(),ce(),at=[],jt=!1,lr=-1,fl.prototype.run=function(){this.fun.apply(null,this.array)},Bo="browser",Fo="x64",$o="browser",qo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ho=["/usr/bin/node"],Wo=[],zo="v16.8.0",Vo={},Ko=function(o,e){console.warn((e?e+": ":"")+o)},Go=function(o){Eo("binding")},Yo=function(o){return 0},Jo=function(){return"/"},Qo=function(o){},Xo={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Zo=We,es=[],ts={},rs=!1,ns={},is=We,os=We,mr=function(){return{}},ss=mr,as=mr,ls=We,cs=We,us=We,ds={},hs={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},fs=We,ps=We,ms=We,gs=We,bs=We,ys=We,vs=We,ws=void 0,_s=void 0,ks=void 0,xs=We,Ss=2,Es=1,As="/bin/usr/node",Is=9229,Ts="node",Cs=[],Ps=We,ft={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ft.now===void 0&&(on=Date.now(),ft.timing&&ft.timing.navigationStart&&(on=ft.timing.navigationStart),ft.now=()=>Date.now()-on),Nr=1e9,nn.bigint=function(o){var e=nn(o);return typeof BigInt>"u"?e[0]*Nr+e[1]:BigInt(e[0]*Nr)+BigInt(e[1])},Os=10,Ms={},Rs=0,Ns=_t,Ls=_t,js=_t,Us=_t,Ds=_t,Bs=We,Fs=_t,$s=_t,Ao={version:zo,versions:Vo,arch:Fo,platform:$o,release:Xo,_rawDebug:Zo,moduleLoadList:es,binding:Go,_linkedBinding:Ad,_events:Ms,_eventsCount:Rs,_maxListeners:Os,on:_t,addListener:Ns,once:Ls,off:js,removeListener:Us,removeAllListeners:Ds,emit:Bs,prependListener:Fs,prependOnceListener:$s,listeners:Rd,domain:ts,_exiting:rs,config:ns,dlopen:Id,uptime:Md,_getActiveRequests:Td,_getActiveHandles:Cd,reallyExit:is,_kill:os,cpuUsage:mr,resourceUsage:ss,memoryUsage:as,kill:ls,exit:cs,openStdin:us,allowedNodeEnvironmentFlags:ds,assert:Pd,features:hs,_fatalExceptions:fs,setUncaughtExceptionCaptureCallback:ps,hasUncaughtExceptionCaptureCallback:Od,emitWarning:Ko,nextTick:Ed,_tickCallback:ms,_debugProcess:gs,_debugEnd:bs,_startProfilerIdleNotifier:ys,_stopProfilerIdleNotifier:vs,stdout:ws,stdin:ks,stderr:_s,abort:xs,umask:Yo,chdir:Qo,cwd:Jo,env:qo,title:Bo,argv:Ho,execArgv:Wo,pid:Ss,ppid:Es,execPath:As,debugPort:Is,hrtime:nn,argv0:Ts,_preload_modules:Cs,setSourceMapsEnabled:Ps}});function Nd(){if(ro)return Lr;ro=!0;var o=Ao;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,s){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}}s&&(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,s){var a=s.dir||s.root,l=s.base||(s.name||"")+(s.ext||"");return a?a===s.root?a+l:a+n+l:l}var i={resolve:function(){for(var n="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=o.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,s=c.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var s=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&a&&(n+="/"),s?"/"+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,s=0;s<arguments.length;++s){var a=arguments[s];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":i.normalize(n)},relative:function(n,s){if(e(n),e(s),n===s||(n=i.resolve(n),s=i.resolve(s),n===s))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<s.length&&s.charCodeAt(u)===47;++u);for(var d=s.length,p=d-u,g=c<p?c:p,f=-1,b=0;b<=g;++b){if(b===g){if(p>g){if(s.charCodeAt(u+b)===47)return s.slice(u+b+1);if(b===0)return s.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?f=b:b===0&&(f=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(f=b)}var m="";for(b=a+f+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+f):(u+=f,s.charCodeAt(u)===47&&++u,s.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var s=n.charCodeAt(0),a=s===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(s=n.charCodeAt(u),s===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var d=s.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===s.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 s=-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?s===-1?s=d:u!==1&&(u=1):s!==-1&&(u=-1)}return s===-1||l===-1||u===0||u===1&&s===l-1&&s===a+1?"":n.slice(s,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 s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var a=n.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,f=n.length-1,b=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:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||p===-1||b===0||b===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?s.base=s.name=n.slice(1,p):s.base=s.name=n.slice(d,p)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,p)):(s.name=n.slice(d,u),s.base=n.slice(d,p)),s.ext=n.slice(u,p)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Lr=i,Lr}var Lr,ro,no,Ld=Je(()=>{le(),ue(),ce(),pl(),Lr={},ro=!1,no=Nd()}),ml={};Gt(ml,{URL:()=>El,Url:()=>wl,default:()=>ze,fileURLToPath:()=>bl,format:()=>_l,parse:()=>Sl,pathToFileURL:()=>yl,resolve:()=>kl,resolveObject:()=>xl});function jd(){if(io)return jr;io=!0;var o=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=o&&e&&typeof e.get=="function"?e.get:null,r=o&&Map.prototype.forEach,i=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=i&&n&&typeof n.get=="function"?n.get:null,a=i&&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,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,_=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,S=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,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,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||S.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),Me=m.call(ie,Pe.length+1);return _.call(Pe,Ie,"$&_")+"."+_.call(_.call(Me,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ie,"$&_")}var re=vl,F=re.custom,Z=Y(F)?F:null;jr=function V(ie,Ie,Te,Pe){var Me=Ie||{};if(se(Me,"quoteStyle")&&Me.quoteStyle!=="single"&&Me.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Me,"maxStringLength")&&(typeof Me.maxStringLength=="number"?Me.maxStringLength<0&&Me.maxStringLength!==1/0:Me.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var et=se(Me,"customInspect")?Me.customInspect:!0;if(typeof et!="boolean"&&et!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Me,"indent")&&Me.indent!==null&&Me.indent!==" "&&!(parseInt(Me.indent,10)===Me.indent&&Me.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Me,"numericSeparator")&&typeof Me.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var tt=Me.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,Me);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var qe=String(ie);return tt?W(ie,qe):qe}if(typeof ie=="bigint"){var rt=String(ie)+"n";return tt?W(ie,rt):rt}var Ft=typeof Me.depth>"u"?5:Me.depth;if(typeof Te>"u"&&(Te=0),Te>=Ft&&Ft>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var nt=X(Me,Te);if(typeof Pe>"u")Pe=[];else if(ee(Pe,ie)>=0)return"[Circular]";function Qe(it,wt,Ot){if(wt&&(Pe=O.call(Pe),Pe.push(wt)),Ot){var ot={depth:Me.depth};return se(Me,"quoteStyle")&&(ot.quoteStyle=Me.quoteStyle),V(it,ot,Te+1,Pe)}return V(it,Me,Te+1,Pe)}if(typeof ie=="function"&&!we(ie)){var fr=q(ie),$t=ke(ie,Qe);return"[Function"+(fr?": "+fr:" (anonymous)")+"]"+($t.length>0?" { "+I.call($t,", ")+" }":"")}if(Y(ie)){var Xt=D?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):$.call(ie);return typeof ie=="object"&&!D?h(Xt):Xt}if(ve(ie)){for(var P="<"+v.call(String(ie.nodeName)),N=ie.attributes||[],_e=0;_e<N.length;_e++)P+=" "+N[_e].name+"="+M(Q(N[_e].value),"double",Me);return P+=">",ie.childNodes&&ie.childNodes.length&&(P+="..."),P+="</"+v.call(String(ie.nodeName))+">",P}if(be(ie)){if(ie.length===0)return"[]";var Se=ke(ie,Qe);return nt&&!B(Se)?"["+de(Se,nt)+"]":"[ "+I.call(Se,", ")+" ]"}if(G(ie)){var Ae=ke(ie,Qe);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+Qe(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&&et){if(Z&&typeof ie[Z]=="function"&&re)return re(ie,{depth:Ft-Te});if(et!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Be=[];return r&&r.call(ie,function(it,wt){Be.push(Qe(wt,ie,!0)+" => "+Qe(it,ie))}),A("Map",t.call(ie),Be,nt)}if(H(ie)){var Ve=[];return a&&a.call(ie,function(it){Ve.push(Qe(it,ie))}),A("Set",s.call(ie),Ve,nt)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return h(Qe(Number(ie)));if(J(ie))return h(Qe(j.call(ie)));if(z(ie))return h(f.call(ie));if(L(ie))return h(Qe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Ur<"u"&&ie===Ur)return"{ [object globalThis] }";if(!te(ie)&&!we(ie)){var Ze=ke(ie,Qe),Zt=K?K(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,er=ie instanceof Object?"":"null prototype",tr=!Zt&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):er?"Object":"",pr=Zt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Pt=pr+(tr||er?"["+I.call(E.call([],tr||[],er||[]),": ")+"] ":"");return Ze.length===0?Pt+"{}":nt?Pt+"{"+de(Ze,nt)+"}":Pt+"{ "+I.call(Ze,", ")+" }"}return String(ie)};function M(V,ie,Ie){var Te=(Ie.quoteStyle||ie)==="double"?'"':"'";return Te+V+Te}function Q(V){return _.call(String(V),/"/g,""")}function be(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 G(V){return R(V)==="[object Error]"&&(!U||!(typeof V=="object"&&U in V))}function L(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 Y(V){if(D)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||Ur)};function se(V,ie){return ge.call(V,ie)}function R(V){return b.call(V)}function q(V){if(V.name)return V.name;var ie=w.call(y.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{s.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 ye(V){if(!g||!V||typeof V!="object")return!1;try{return g.call(V),!0}catch{}return!1}function H(V){if(!s||!V||typeof V!="object")return!1;try{s.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=_.call(_.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":"")+x.call(ie.toString(16))}function h(V){return"Object("+V+")"}function k(V){return V+" { ? }"}function A(V,ie,Ie,Te){var Pe=Te?de(Ie,Te):I.call(Ie,", ");return V+" ("+ie+") {"+Pe+"}"}function B(V){for(var ie=0;ie<V.length;ie++)if(ee(V[ie],`
|
|
4
|
-
`)>=0)return!1;return!0}function
|
|
5
|
-
`+ie.prev+ie.base;return Ie+I.call(
|
|
6
|
-
`+ie.prev}function ke(V,ie){var Ie=be(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 Me=typeof T=="function"?T(V):[],et;if(D){et={};for(var tt=0;tt<Me.length;tt++)et["$"+Me[tt]]=Me[tt]}for(var qe in V)se(V,qe)&&(Ie&&String(Number(qe))===qe&&qe<V.length||D&&et["$"+qe]instanceof Symbol||(S.call(/[^\w$]/,qe)?Te.push(ie(qe,V)+": "+ie(V[qe],V)):Te.push(qe+": "+ie(V[qe],V))));if(typeof T=="function")for(var rt=0;rt<Me.length;rt++)oe.call(V,Me[rt])&&Te.push("["+ie(Me[rt])+"]: "+ie(V[Me[rt]],V));return Te}return jr}function Ud(){if(oo)return Dr;oo=!0;var o=Qt(),e=kd(),t=jd(),r=hr(),i=o("%WeakMap%",!0),n=o("%Map%",!0),s=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(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},g=function(y,w){var m=p(y,w);return m&&m.value},f=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return Dr=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(y)return s(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(i&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){i&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new i),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Dr}function Io(){if(so)return Br;so=!0;var o=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Br={default:t.RFC3986,formatters:{RFC1738:function(r){return o.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Br}function gl(){if(ao)return Fr;ao=!0;var o=Io(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),i=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},s=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.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,_)),t(w)&&t(m)?(m.forEach(function(v,S){if(e.call(w,S)){var E=w[S];E&&typeof E=="object"&&v&&typeof v=="object"?w[S]=y(E,v,_):w.push(v)}else w[S]=v}),w):Object.keys(m).reduce(function(v,S){var E=m[S];return e.call(v,S)?v[S]=y(v[S],E,_):v[S]=E,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var S="",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||x===o.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]}S+=O.join("")}return S},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],S=Object.keys(v),E=0;E<S.length;++E){var I=S[E],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return i(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Fr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:s},Fr}function Dd(){if(lo)return $r;lo=!0;var o=Ud(),e=gl(),t=Io(),r=Object.prototype.hasOwnProperty,i={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},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(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,_,x,v,S,E,I,O,C,j,T,$,D,U,oe,K){for(var W=y,re=K,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof O=="function"?W=O(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 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[D(Q)+"="+D(I(W,u.encoder,oe,"value",$))]}return[D(w)+"="+D(String(W))]}var be=[];if(typeof W>"u")return be;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,L=_&&n(W)&&W.length===1?G+"[]":G;if(x&&n(W)&&W.length===0)return L+"[]";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(!(S&&Y===null)){var J=j&&E?z.replace(/\./g,"%2E"):z,ge=n(W)?typeof m=="function"?m(L,J):L:L+(j?"."+J:"["+J+"]");K.set(y,F);var se=o();se.set(p,K),a(be,b(Y,ge,m,_,x,v,S,E,m==="comma"&&U&&n(W)?null:I,O,C,j,T,$,D,U,oe,se))}}return be},f=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.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 b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],_=u.filter;(typeof b.filter=="function"||n(b.filter))&&(_=b.filter);var x;if(b.arrayFormat in i?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return $r=function(b,y){var w=b,m=f(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var S=i[m.arrayFormat],E=S==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=o(),O=0;O<_.length;++O){var C=_[O];m.skipNulls&&w[C]===null||a(v,g(w[C],C,S,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:""},$r}function Bd(){if(co)return qr;co=!0;var o=gl(),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:o.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},i=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},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var f={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,_,x=g.charset;if(g.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===s&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],S=v.indexOf("]="),E=S===-1?v.indexOf("="):S+1,I,O;E===-1?(I=g.decoder(v,r.decoder,x,"key"),O=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,x,"key"),O=o.maybeMap(n(v.slice(E+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),O&&g.interpretNumericEntities&&x==="iso-8859-1"&&(O=i(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var C=e.call(f,I);C&&g.duplicates==="combine"?f[I]=o.combine(f[I],O):(!C||g.duplicates==="last")&&(f[I]=O)}return f},c=function(p,g,f,b){for(var y=b?g:n(g,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);else{m=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,S=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(S)&&_!==v&&String(S)===v&&S>=0&&f.parseArrays&&S<=f.arrayLimit?(m=[],m[S]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,f,b){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var S=0;f.depth>0&&(_=m.exec(y))!==null&&S<f.depth;){if(S+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,g,f,b)}},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 b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,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"||o.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 qr=function(p,g){var f=d(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var _=w[m],x=u(_,b[_],f,typeof p=="string");y=o.merge(y,x,f)}return f.allowSparse===!0?y:o.compact(y)},qr}function Fd(){if(uo)return Hr;uo=!0;var o=Dd(),e=Bd(),t=Io();return Hr={formats:t,parse:e,stringify:o},Hr}function $d(){if(ho)return At;ho=!0;var o=Et;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]*$/,i=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
-
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),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},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y
|
|
8
|
-
`)&&(e=e.replace(Rl,"%0A")),e.includes("\r")&&(e=e.replace(Nl,"%0D")),e.includes(" ")&&(e=e.replace(Ll,"%09")),r.pathname=e,r}var vl,jr,io,Ur,Dr,oo,Br,so,Fr,ao,$r,lo,qr,co,Hr,uo,At,ho,ze,qs,wl,_l,kl,xl,Sl,El,Al,Il,Tl,Cl,Vr,Pl,Ol,Ml,Rl,Nl,Ll,Wd=Je(()=>{le(),ue(),ce(),ad(),xd(),Ld(),pl(),vl=Object.freeze(Object.create(null)),jr={},io=!1,Ur=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Dr={},oo=!1,Br={},so=!1,Fr={},ao=!1,$r={},lo=!1,qr={},co=!1,Hr={},uo=!1,At={},ho=!1,ze=$d(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,qs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=yl,ze.fileURLToPath=bl,wl=ze.Url,_l=ze.format,kl=ze.resolve,xl=ze.resolveObject,Sl=ze.parse,El=ze.URL,Al=92,Il=47,Tl=97,Cl=122,Vr=qs==="win32",Pl=/\//g,Ol=/%/g,Ml=/\\/g,Rl=/\n/g,Nl=/\r/g,Ll=/\t/g}),zd=pe((o,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")}}),To=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.BufferedDuplex=void 0,o.writev=r;var e=Bt(),t=($e(),Ne(Fe));function r(n,s){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",s)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,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,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};o.BufferedDuplex=i}),gr=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(o,"__esModule",{value:!0}),o.streamBuilder=o.browserStreamBuilder=void 0;var t=($e(),Ne(Fe)),r=e(zd()),i=e(mt()),n=Bt(),s=e(Zr()),a=To(),l=(0,i.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}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={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),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 _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let _=d(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),S=r.default.createWebSocketStream(v,_.wsOptions);return S.url=x,v.on("close",()=>{S.destroy()}),S};o.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,S=!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?(_=I,_.socket=E):(_=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",D)):(E.onclose=T,E.onerror=$,E.onmessage=D);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"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(K){l("WebSocket onClose",K),_.end(),_.destroy()}function $(K){l("WebSocket onError",K);let W=new Error("WebSocket error");W.event=K,_.destroy(W)}async function D(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>x){setTimeout(U,v,K,W,re);return}S&&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 _};o.browserStreamBuilder=y}),Co={};Gt(Co,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>jl,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 jl,Ul=Je(()=>{le(),ue(),ce(),jl={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),Dl=pe((o,e)=>{le(),ue(),ce(),e.exports={}}),Hs=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0});var t=e((Ul(),Ne(Co))),r=e(mt()),i=e(Dl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,i.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})};o.default=s}),Bl={};Gt(Bl,{default:()=>Fl});var Fl,Vd=Je(()=>{le(),ue(),ce(),Fl={}}),Ws=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(o,"__esModule",{value:!0});var t=(Vd(),Ne(Bl)),r=e((Ul(),Ne(Co))),i=e(mt()),n=e(Dl()),s=(0,i.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,s("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};o.default=l}),zs=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=($e(),Ne(Fe)),t=Bt(),r=To(),i,n,s;function a(){let p=new t.Transform;return p._write=(g,f,b)=>{i.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{i.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",b=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){i.onOpen(()=>{s.socketReady()}),i.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),i.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),i.onError(p=>{let g=new Error(p.errMsg);s.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 b=c(g,p);i=wx.connectSocket({url:b,protocols:[f]}),n=a(),s=new r.BufferedDuplex(g,n,i),s._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{i.close({fail(){s._destroy(w,m)}})},0),s),u(),s};o.default=d}),Vs=pe(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=($e(),Ne(Fe)),t=Bt(),r=To(),i,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(f,b,y)=>{i.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},g._flush=f=>{i.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 b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,f)),y}function d(){a||(a=!0,i.onSocketOpen(()=>{s.socketReady()}),i.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)}}),i.onSocketClose(()=>{s.end(),s.destroy()}),i.onSocketError(g=>{s.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 b=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,g);return i=f.my,i.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(f,n,i),d(),s};o.default=p}),Kd=pe(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(o,"__esModule",{value:!0}),o.connectAsync=u;var t=e(mt()),r=e((Wd(),Ne(ml))),i=e(Si()),n=e(Zr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var s=(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(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,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 Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=gr().streamBuilder,a.wss=gr().streamBuilder,a.mqtt=Hs().default,a.tcp=Hs().default,a.ssl=Ws().default,a.tls=a.ssl,a.mqtts=Ws().default):(a.ws=gr().browserStreamBuilder,a.wss=gr().browserStreamBuilder,a.wx=zs().default,a.wxs=zs().default,a.ali=Vs().default,a.alis=Vs().default)),!a[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let f=new i.default(g,p);return f.on("error",()=>{}),f}function u(d,p,g=!0){return new Promise((f,b)=>{let y=c(d,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),b(_)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}o.default=c}),Ks=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(g,f,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(f,b);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[b]}}),Object.defineProperty(g,y,w)}:function(g,f,b,y){y===void 0&&(y=b),g[y]=f[b]}),t=o&&o.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=o&&o.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(f)};return function(f){if(f&&f.__esModule)return f;var b={};if(f!=null)for(var y=g(f),w=0;w<y.length;w++)y[w]!=="default"&&e(b,f,y[w]);return t(b,f),b}})(),i=o&&o.__exportStar||function(g,f){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(f,b)&&e(f,g,b)},n=o&&o.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=o.KeepaliveManager=o.UniqueMessageIdProvider=o.DefaultMessageIdProvider=o.Store=o.MqttClient=o.connectAsync=o.connect=o.Client=void 0;var s=n(Si());o.MqttClient=s.default;var a=n(rl());o.DefaultMessageIdProvider=a.default;var l=n(od());o.UniqueMessageIdProvider=l.default;var c=n(Ba());o.Store=c.default;var u=r(Kd());o.connect=u.default,Object.defineProperty(o,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(cl());o.KeepaliveManager=d.default,o.Client=s.default,i(Si(),o),i(Jt(),o),i(Da(),o);var p=Qr();Object.defineProperty(o,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Gd=pe(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(s,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(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=o&&o.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=o&&o.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),i=o&&o.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(o,"__esModule",{value:!0});var n=r(Ks());o.default=n,i(Ks(),o)});const Yd=Gd();const Jd={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}/#"},Qd=300,Xd={templateId:"7",type:"link",isDeepLink:!0},Zd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class $l{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={...Jd,...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,i={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&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,s)=>{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(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Yd.connect(this.config.mqttEndpoint,i),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[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=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 i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...Xd,...this.config.fileTemplate??{},...eh(t)},i={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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Qd){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,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 i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.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 i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:d,raw:i};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,l))}buildOutgoingEnvelope(e,t){const r={...Zd,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:i,senderFullname:i,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:s}}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,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function eh(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(e[t]=r);return e}function ql(o,e){return(o.sender??"").toString()===e}function Hl(o,e){const t=(o.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function Po(o){const e={raw:o},t=o.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 o.text=="string"&&o.text.trim().startsWith("{"))try{const i=o.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(i);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=o.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function Wl(o){const e=Po(o);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 i=r[0],n=i.action,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof i.description=="string"?i.description:void 0,l=o.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function Gs(o,e,t){const r=Hl(o,t),i=Po(o),n=Wl(o);let s="";i.innerMessage?s=i.innerMessage:typeof o.text=="string"&&(o.text.trim().startsWith("{")?i.contentType!=="300"&&(s=o.text):s=o.text);const a=typeof o.message_id=="string"?o.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof o.timestamp=="number"?new Date(o.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof o.status=="number"?th(o.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:o.sender,sender_fullname:o.sender_fullname??o.senderFullname,app_id:o.app_id,attributes:o.attributes}};return i.contentType&&(d.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:i}}function th(o){return o<0?"error":o>=250?"read":o>=150?"delivered":"sent"}class zl extends mo{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 sa(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new aa,this.conversationManager=new ca(e.conversationId),this.usesAikaara()&&(this.connection=new oa(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 $l({...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 i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),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),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(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 i=r.map(l=>Gs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=i.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of i){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 i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);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 i=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:i.fileName,fileUrl:i.url,cloudFileId:i.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 i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,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 i=t.conversationId??r;if(!i)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=Gs(e,i,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(ql(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);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:i,role:s.role==="tool"?"system":s.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||"",i=e.content||"";i?this.messageStore.updateStreaming(i):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,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ys={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 rh(o){const e=o.lastIndexOf(".");return e<0||e===o.length-1?"":o.slice(e+1).toLowerCase()}function nh(o,e,t){const r=rh(o.name||"");if(r&&e&&e[r])return e[r];const i=o.type;return i&&i.trim().length>0?i:r&&Ys[r]?Ys[r]:t}function sn(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ih(o,e){const t=e.split(".");let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function Vl(o){const e=o.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=nh(t,o.contentTypeMap,o.contentTypeFallback??"application/octet-stream"),s={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=o.authHeader?await o.authHeader():void 0,l={accept:"application/json",...o.extraHeaders??{},...a?{authorization:a}:{}};let c=o.signEndpoint.includes("{")?o.signEndpoint:`${o.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=sn(c,s),d=await fetch(u,{method:o.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=ih(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=o.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,o.s3HostRewrite):g,b=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(o.registerEndpoint){const w=JSON.parse(sn(JSON.stringify(o.registerBody??{}),s)),m=await fetch(o.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:o.viewerTemplate?sn(o.viewerTemplate,s):g.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Oo(o){return{async upload(e,t){const r=new FormData,i=o.fieldName??"file";r.append(i,e,e.name);const n=typeof o.extraFields=="function"?o.extraFields(t):o.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 s=typeof o.headers=="function"?await o.headers():o.headers??{},a=await fetch(o.endpoint,{method:o.method??"POST",body:r,headers:s,credentials:o.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(o.parseResponse)return o.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 oh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Kl(o){const e=o.apiBase.replace(/\/$/,""),t=o.pageSize??200,r=o.pathTemplate??oh;return{async fetchMessages(i,n){const s=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...o.extraHeaders??{}};if(o.getToken){const p=await o.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(o.parseResponse&&u)return o.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 sh="^[A-Z]{4}[0-9]{5}[A-Z]$",ah="^[A-Z]{4}0[A-Z0-9]{6}$",lh="^[0-9]{6}$",ch={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"},uh={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:sh,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"},dh={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:lh}]},{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"},hh={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"},fh={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"},ph={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"},mh={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:ah,maxLength:11}]}],submitLabel:"Save"},gh=[uh,ph,hh,fh,ch,dh,mh];function bh(o,e){const t=o||{},r={userId:lt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Ph()};r.us80cAmount=xe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=xe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=xe(t.us80dForParentsAmount),r.hasParentOverSixty=ur(t.hasParentOverSixty),r.preventiveHealthCheckUp=xe(t.preventiveHealthCheckUp),r.medicalExpenditure=xe(t.medicalExpenditure),r.savingBankInterest=xe(t.savingBankInterest),r.fdInterest=xe(t.fdInterest),r.dividend=xe(t.dividend),r.anyOtherIncome=xe(t.anyOtherIncome),r.cryptoSellValue=xe(t.cryptoSellPrice),r.cryptoPurchaseAmount=xe(t.cryptoPurchasePrice),r.vdaPurchaseCost=xe(t.cryptoPurchasePrice);const i=(xe(t.bizReceiptsBank)??0)+(xe(t.bizReceiptsCash)??0),n=(xe(t.profReceiptsBank)??0)+(xe(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||i>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?i||void 0:n||void 0,r.agricultureDetails={income:xe(t.agricultureIncome)},r.exemptIncomeAmount=xe(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),xe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(xe(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:xe(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=an(t.hpDetails,yh);l.length&&(r.hpDetails=l);const c=an(t.salaryDetails,vh);if(c.length){r.salaryIncome=c;const u=an(t.salaryDetails,p=>({grossSalary:xe(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=en(t.salaryDetails)[0]??{};r.hraAmount=xe(d.hraReceived),r.leaveTravelAllowanceAmount=xe(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=xe(d.leaveEncashment),r.anyOtherAllowanceAmount=xe(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return gt(r)}function yh(o){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(o.loanTakenFrom),bankOrInstituteName:Ee(o.lenderName),loanAccountNo:Ee(o.loanAccountNumber),loanSanctionDate:Kr(o.sanctionDate),totalLoanAmount:xe(o.totalLoanAmount),loanOutstandingAmount:xe(o.outstandingAmount),interest:xe(o.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Ee(o.typeOfHouseProperty),hasRentalIncome:o.typeOfHouseProperty==="LOP"?!0:ur(o.hasRentalIncome),homeLoanInterest:xe(o.homeLoanInterest),homeLoanPrinciple:xe(o.homeLoanPrinciple),housePropertyAddress:Ee(o.housePropertyAddress),housePropertyPincode:Ee(o.housePropertyPincode),rentalIncome:xe(o.rentalIncome),nameOfTenant:Ee(o.nameOfTenant),propertyTax:xe(o.propertyTax),hasCoOwnedProperty:ur(o.hasCoOwnedProperty),coOwnerName:Ee(o.coOwnerName),coOwnerPan:Ee(o.coOwnerPan),coOwnerShare:Ee(o.coOwnerShare),loanDetails:t?[e]:void 0}}function vh(o){return{grossSalaryIncome:xe(o.grossSalary),salary:xe(o.basicSalary),employer:{employerName:Ee(o.employerName),employerTan:Ee(o.employerTan)},allowance:{hraAmount:xe(o.hraReceived),leaveTravelAllowanceAmount:xe(o.leaveTravelAllowance),leaveEncashmentAllowanceAmount:xe(o.leaveEncashment),anyOtherAllowanceAmount:xe(o.anyOtherAllowance)}}}function wh(o,e){const t=[];for(const r of o){const i=Ee(r.employerName),n=Ee(r.employerTan),s=xe(r.grossSalary),a=xe(r.basicSalary),l=xe(r.totalTdsDeposited);i===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:i??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:lt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function _h(o,e){const t=Ee(o.aadhaarNumber),r=Ee(o.bankAccountNumber),i=Ee(o.bankIfscCode);return t===void 0&&r===void 0&&i===void 0?null:{userId:lt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:i}]}}function kh(o,e){return{userId:lt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:xe(o.savingBankInterest)??0,fdInterest:xe(o.fdInterest)??0,dividend:xe(o.dividend)??0,anyOtherIncome:xe(o.anyOtherIncome)??0,familyPension:xe(o.familyPension)??0}}function xh(o,e){const t=xe(o.cryptoSellPrice),r=xe(o.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:lt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Sh(o,e){const t=(i,n,s,a)=>{const l=Ee(o[i]),c=Ee(o[n]),u=xe(o[s]),d=xe(o[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(i=>i!==null);return r.length?{userId:lt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Eh(o){return Ee(o.lenderName)!==void 0||Ee(o.loanAccountNumber)!==void 0||xe(o.totalLoanAmount)!==void 0||xe(o.outstandingAmount)!==void 0||xe(o.homeLoanInterest)!==void 0}function Gl(o){const e=Ee(o.typeOfHouseProperty)?.toUpperCase();return xe(o.rentalIncome)!==void 0||Ee(o.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Ah(o,e){const t=en(o.hpDetails).filter(Eh).map(r=>{const i=gt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:Kr(r.sanctionDate),totalLoanAmount:xe(r.totalLoanAmount),loanOutstandingAmount:xe(r.outstandingAmount),interest:xe(r.homeLoanInterest)});return gt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:xe(r.homeLoanInterest),homeLoanPrinciple:xe(r.homeLoanPrinciple),propertyTax:xe(r.propertyTax),eligible80EEAAmount:xe(r.eligible80EEAAmount),eligible80EEAmount:xe(r.eligible80EEAmount),hasCoOwnedProperty:ur(r.hasCoOwnedProperty)??!1,hasRentalIncome:Gl(r),loanDetails:[i]})});return t.length?{userId:lt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Ih(o,e){const t=en(o.hpDetails).filter(Gl).map(r=>gt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:xe(r.rentalIncome),propertyTax:xe(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:xe(r.homeLoanInterest)}));return t.length?{userId:lt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Th(o,e){const t=o||{},r=g=>({userId:lt(e.userId),assessmentYear:e.assessmentYear,deductions:gt(g)}),i=[],n=xe(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?i.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 s=Ee(t.us80ccd1bPanNo),a=xe(t.us80ccd1bAmount);a!==void 0&&i.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=xe(t.us80ccd2Amount);l!==void 0&&i.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=xe(t.us80eInterest);c!==void 0&&i.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:Kr(t.us80eLoanSanctionDate),totalLoanAmount:xe(t.us80eLoanAmount),loanOutstandingAmount:xe(t.us80eOutstandingLoan)}));const u=xe(t.us80eeInterest);u!==void 0&&i.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:Kr(t.us80eeLoanSanctionDate),totalLoanAmount:xe(t.us80eeLoanAmount),loanOutstandingAmount:xe(t.us80eeOutstandingLoan),vehicleRegistrationNumber:Ee(t.us80eeVehicleRegistrationNumber)}));const d=xe(t.us80dForSelfAndFamilyAmount);d!==void 0&&i.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=xe(t.us80dForParentsAmount);return p!==void 0&&i.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:ur(t.hasParentOverSixty)??!1})),i}function Ch(o,e){const t=o||{},r=xe(t.us80gDonationAmount),i=Ee(t.us80gNameOfCharity);return r===void 0&&i===void 0?null:{userId:lt(e.userId),assessmentYear:e.assessmentYear,donations80g:[gt({name:i,panNumber:Ee(t.us80gCharityPan),amountOtherThanCash:r,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode)})]}}function lt(o){if(o===void 0||o==="")return;const e=Number(o);return Number.isFinite(e)&&String(e)===String(o)?e:o}function xe(o){if(o==null||o==="")return;const e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:void 0}function Ee(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function ur(o){return o===!0||o===!1?o:void 0}function Ph(){const o=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())}T${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}.${e(o.getMilliseconds(),3)}`}function Kr(o){const e=Ee(o);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function en(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function an(o,e){return en(o).map(t=>gt(e(t))).filter(t=>t!==void 0)}function gt(o){if(Array.isArray(o)){const e=o.map(gt).filter(t=>t!==void 0);return e.length?e:void 0}if(o&&typeof o=="object"){const e={};for(const[t,r]of Object.entries(o)){const i=gt(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return o}function Oh(o){const e=o&&typeof o=="object"?o:{},t={},r=je(e.employers),i=je(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(C=>{const j=ln(C.salary),T=ln(C.perquisites),$=ln(C.profitsInLieuOfSalaryType),D=j+T+$,U=Rh(C.allowance);return{employerName:Ce(C.employerName),employerTan:Ce(C.employerTAN),basicSalary:j||void 0,grossSalary:D||void 0,hraReceived:U.hra,leaveTravelAllowance:U.lta,leaveEncashment:U.leaveEncashment,anyOtherAllowance:U.other,totalTdsDeposited:Mh(C,i,r)??Re(C.totalTdsDeposited)}}));const n=je(e.houseProperties);n.length&&(t.hpDetails=n.map(C=>{const j=je(C.loanDetails),T=j.length?j[0]:void 0,$=Re(C.grossAnnualRentReceived),D=j.length?j.reduce((re,F)=>re+(Re(F.interest)??0),0):void 0,U=je(C.tenant),oe=je(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:Js(T?.loanSanctionDate),totalLoanAmount:Re(T?.totalLoanAmount),outstandingAmount:Re(T?.loanOutstandingAmount),homeLoanInterest:D,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 s=je(e.deductionUS80CDetails),a=kt(s.map(C=>Re(C.amount))),l=s.find(C=>Ce(C.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=je(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=je(e.deductionUS80DDetails),p=d.find(C=>Ce(C.policyFor)?.toUpperCase()==="DEPENDANT")??je(e.insurances).find(C=>Ce(C.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(C=>Ce(C.policyFor)?.toUpperCase()==="PARENTS")??je(e.insurances).find(C=>Ce(C.policyFor)?.toUpperCase()==="PARENTS"),f=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,b=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??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??b?.accountNo),t.hasParentOverSixty=Nh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=je(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 _=je(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(_?.loanTakenFrom),t.us80eeBankName=Ce(_?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(_?.loanAccountNo),t.us80eeLoanSanctionDate=Js(_?.loanSanctionDate),t.us80eeLoanAmount=Re(_?.totalLoanAmount),t.us80eeOutstandingLoan=Re(_?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(_?.vehicleRegistrationNo);const x=je(e.insurances);t.preventiveHealthCheckUp=kt(x.map(C=>Re(C.preventiveCheckUp))),t.medicalExpenditure=kt(x.map(C=>Re(C.medicalExpenditure)));const v=je(e.incomes),S=C=>kt(v.filter(j=>Ce(j.incomeType)===C).map(j=>Re(j.amount)));t.savingBankInterest=S("SAVING_INTEREST"),t.fdInterest=S("FD_RD_INTEREST"),t.anyOtherIncome=S("ANY_OTHER"),t.familyPension=S("FAMILY_PENSION"),t.dividend=kt(je(e.dividendIncomes).map(C=>Re(C.income)));const E=e.business;if(E){const C=je(E.presumptiveIncomes),j=D=>{const U=je(D.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(D.businessType)?.toUpperCase().includes("PROFESSION")},T=D=>C.find(U=>j(U)===D),$=(D,U)=>{if(!D)return;const oe=je(D.incomes),K=re=>Re(oe.find(F=>Ce(F.incomeType)===re)?.receipts),W=K("BANK")||K("ANY_OTHER");t[U.name]=Ce(D.businessType),t[U.nature]=Ce(D.natureOfBusiness),t[U.bank]=W||void 0,t[U.cash]=K("CASH")||void 0,t[U.net]=kt(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=je(e.capitalGain).filter(C=>Ce(C.assetType)?.toUpperCase()==="VDA").flatMap(C=>je(C.assetDetails));I.length&&(t.cryptoSellPrice=kt(I.map(C=>Re(C.sellValue))),t.cryptoPurchasePrice=kt(I.map(C=>Re(C.purchaseCost)))),t.agricultureIncome=Re(e.agriculturalDetails?.income),t.aadhaarNumber=Ce(e.aadharNumber);const O=je(e.bankDetails)[0];return O&&(t.bankAccountNumber=Ce(O.accountNumber),t.bankIfscCode=Ce(O.ifsCode)),Yl(t)}function Js(o){const e=Ce(o);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function ln(o){return je(o).reduce((e,t)=>e+(Re(t.taxableAmount)??0),0)}function Mh(o,e,t){if(!e.length)return;const r=Ce(o.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Re(n.totalTdsDeposited)}const i=Ce(o.employerName)?.trim().toLowerCase();if(i){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===i)return Re(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Re(e[0].totalTdsDeposited)}function Rh(o){const e=je(o);if(!e.length)return{};let t,r,i,n;for(const s of e){const a=Re(s.exemptAmount)??Re(s.allowanceAmount);switch(Ce(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":i=a;break;default:n=(n??0)+(Re(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:i,other:n}}function kt(o){let e=0,t=!1;for(const r of o)r!=null&&(e+=r,t=!0);return t?e:void 0}function je(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function Re(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""&&Number.isFinite(Number(o)))return Number(o)}function Ce(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function Nh(o){if(typeof o=="boolean")return o;if(typeof o=="string"){const e=o.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 o=="number")return o===1?!0:o===0?!1:void 0}function Yl(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(Array.isArray(r)?e[t]=r.map(i=>i&&typeof i=="object"?Yl(i):i):e[t]=r);return e}function cn(){if(typeof window>"u")return null;const o=window,e=o.__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=o.__aikaara_descriptor__??{},r=Wh(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 i=zh(e.slug),n=typeof i?.tenantJwt=="string"?i.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(i&&i.userId!=null&&i.userId!==""?String(i.userId):Kh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Vh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Gh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Lh(o){const e=await o.getToken(),t=o.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${o.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...o.headers}});if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${i.slice(0,200)}`)}return Oh(Mo(await r.json().catch(()=>({}))))}async function jh(o,e){const t=await o.getToken(),r=o.userId,i={...bh(e,{userId:r,assessmentYear:o.assessmentYear,isRevised:o.isRevised}),sendSummary:!0},n=o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...o.headers};o.txbdyApiKey&&(s["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(i)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Mo(await a.json().catch(()=>({})))}async function Uh(o,e){return Ct(o,`${o.baseUrl}/itr/v1/automation/salary`,e)}async function Dh(o,e){return Ct(o,`${o.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Qs(o,e){return Ct(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function Bh(o,e){return Ct(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function Fh(o,e){return Ct(o,`${o.baseUrl}/itr/v1/automation/deductions`,e)}async function $h(o,e){return Ct(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function qh(o,e){return Ct(o,`${o.baseUrl}/itr/v1/automation/hp-income`,e)}async function Hh(o,e){return Ct(o,`${o.baseUrl}/itr/v1/automation/vda`,e)}async function Ct(o,e,t){const i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await o.getToken()}`,...o.headers};o.txbdyApiKey&&(i["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:i,body:JSON.stringify(t)});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Mo(await n.json().catch(()=>({})))}function Wh(o){const e=[o.cloud?.listEndpoint,o.cloud?.downloadEndpoint,o.upload?.signEndpoint,o.login?.pan?.basicPanEndpoint,o.login?.pan?.panDetailEndpoint,o.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 zh(o){if(!o||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${o}`);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 Vh(o){const e={};if(!o)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(o))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function Kh(o){if(!o)return;const e=o.userId??o.id??o.ext_uid??o.extUid;return e==null||e===""?void 0:String(e)}function Mo(o){if(o&&typeof o=="object"){const e=o;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Gh(){const o=new Date,e=o.getMonth()>=3?o.getFullYear():o.getFullYear()-1;return`${e}-${e+1}`}class Yh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new zl(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??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};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(),i=r(e);return t.some(n=>typeof n=="string"&&r(n)===i)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:gh,data:{}});const t=cn();if(!(!t||!t.baseUrl))try{const r=await Lh(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=cn();if(!r)return;const i={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=wh(n,i);s&&await Uh(r,s)}else if(e==="bank-details"){const n=_h(t,i);n&&await Dh(r,n)}else if(e==="other-sources")await Qs(r,kh(t,i));else if(e==="business-profession"){const n=Sh(t,i);n&&await Bh(r,n)}else if(e==="crypto-income"){const n=xh(t,i);n&&await Hh(r,n)}else if(e==="deductions"){for(const s of Th(t,i))await Fh(r,s);const n=Ch(t,i);n&&await Qs(r,n)}else if(e==="house-property"){const n=Ah(t,i);n&&await $h(r,n);const s=Ih(t,i);s&&await qh(r,s)}}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=cn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await jh(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 Jl 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||Fc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||No,position:this.getAttribute("position")||this._config.position||Bc,width:Number(this.getAttribute("width"))||this._config.width||Lc,height:Number(this.getAttribute("height"))||this._config.height||jc,fontFamily:this._config.fontFamily||Dc,borderRadius:this._config.borderRadius??Uc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Lo,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||$c,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,i){if(typeof document>"u")return;const n=document.documentElement,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??i),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}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(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${n};`).join(`
|
|
1
|
+
"use strict";class ia{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 pn{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 ia(t,o=>{this.send({command:"message",identifier:t,data:JSON.stringify(o)})});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((o,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>o(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 mo{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(o){console.error(`Error in event handler for "${e}":`,o)}})}removeAllListeners(){this.handlers.clear()}}const Rc=1e3,Nc=10,jc=400,Uc=600,Ro="#6366f1",Dc=12,Bc="system-ui, -apple-system, sans-serif",No="Type a message...",Fc="bottom-right",$c="light",qc={x:20,y:20},tn="aikaara_conversation_id";class oa extends mo{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 pn(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,o){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...o&&{source:o}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Nc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Rc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const o=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new pn(o),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const o=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${o}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class sa{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,o){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=o}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 o=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(o,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(o,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 s=await n.json();if(s&&typeof s=="object"&&"success"in s){if(!s.success)throw new Error(`API error: ${s.message||"Request failed"}`);return s.data}return s}async fetchWithHeaders(e,t,r){const o={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(o["X-Api-Key"]=this.apiKey),this.authToken&&(o.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:o};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class aa{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const o={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(o),o}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(o=>o.status==="sending"&&o.role===e.role&&o.content===e.content&&o.conversationId===e.conversationId&&Date.now()-new Date(o.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 o=jo(this._messages,e);return o?(Object.assign(o,e,{id:o.id}),{message:o,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(o=>o.externalId===e||o.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 o=jo(t,r);if(o){const n=Wr(o),s=Wr(r);!n&&s&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function jo(i,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const s=Wr(e),a=Uo(e),l=Do(e);if(!s&&!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 b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=Wr(d);if(s&&y&&s===y)return d;const w=Uo(d);if(a&&w&&a===w)return d;const m=Do(d);if(l&&m&&l===m)return d}return null}function Uo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=la(i);if(t)return t}function Do(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 Wr(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=la(i);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function la(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 ca{_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(tn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(tn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(tn,e)}catch{}}}var go=Object.defineProperty,Hc=Object.getOwnPropertyDescriptor,Wc=Object.getOwnPropertyNames,zc=Object.prototype.hasOwnProperty,Je=(i,e)=>()=>(i&&(e=i(i=0)),e),pe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Gt=(i,e)=>{for(var t in e)go(i,t,{get:e[t],enumerable:!0})},Vc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wc(e))!zc.call(i,o)&&o!==t&&go(i,o,{get:()=>e[o],enumerable:!(r=Hc(e,o))||r.enumerable});return i},Re=i=>Vc(go({},"__esModule",{value:!0}),i),le=Je(()=>{}),Ne={};Gt(Ne,{_debugEnd:()=>Gn,_debugProcess:()=>Kn,_events:()=>ci,_eventsCount:()=>ui,_exiting:()=>Ln,_fatalExceptions:()=>Wn,_getActiveHandles:()=>ga,_getActiveRequests:()=>ma,_kill:()=>jn,_linkedBinding:()=>fa,_maxListeners:()=>li,_preload_modules:()=>si,_rawDebug:()=>Pn,_startProfilerIdleNotifier:()=>Yn,_stopProfilerIdleNotifier:()=>Jn,_tickCallback:()=>Vn,abort:()=>ei,addListener:()=>di,allowedNodeEnvironmentFlags:()=>qn,arch:()=>gn,argv:()=>vn,argv0:()=>oi,assert:()=>ba,binding:()=>Sn,browser:()=>Cn,chdir:()=>In,config:()=>Rn,cpuUsage:()=>nr,cwd:()=>An,debugPort:()=>ii,default:()=>yo,dlopen:()=>pa,domain:()=>Mn,emit:()=>gi,emitWarning:()=>xn,env:()=>yn,execArgv:()=>wn,execPath:()=>ni,exit:()=>Fn,features:()=>Hn,hasUncaughtExceptionCaptureCallback:()=>ya,hrtime:()=>vr,kill:()=>Bn,listeners:()=>wa,memoryUsage:()=>Dn,moduleLoadList:()=>On,nextTick:()=>da,off:()=>fi,on:()=>dt,once:()=>hi,openStdin:()=>$n,pid:()=>ti,platform:()=>bn,ppid:()=>ri,prependListener:()=>bi,prependOnceListener:()=>yi,reallyExit:()=>Nn,release:()=>Tn,removeAllListeners:()=>mi,removeListener:()=>pi,resourceUsage:()=>Un,setSourceMapsEnabled:()=>ai,setUncaughtExceptionCaptureCallback:()=>zn,stderr:()=>Xn,stdin:()=>Zn,stdout:()=>Qn,title:()=>mn,umask:()=>En,uptime:()=>va,version:()=>_n,versions:()=>kn});function bo(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Kc(){!Nt||!Lt||(Nt=!1,Lt.length?lt=Lt.concat(lt):ar=-1,lt.length&&ua())}function ua(){if(!Nt){var i=setTimeout(Kc,0);Nt=!0;for(var e=lt.length;e;){for(Lt=lt,lt=[];++ar<e;)Lt&&Lt[ar].run();ar=-1,e=lt.length}Lt=null,Nt=!1,clearTimeout(i)}}function da(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];lt.push(new ha(i,e)),lt.length===1&&!Nt&&setTimeout(ua,0)}function ha(i,e){this.fun=i,this.array=e}function He(){}function fa(i){bo("_linkedBinding")}function pa(i){bo("dlopen")}function ma(){return[]}function ga(){return[]}function ba(i,e){if(!i)throw new Error(e||"assertion error")}function ya(){return!1}function va(){return ft.now()/1e3}function vr(i){var e=Math.floor((Date.now()-ft.now())*.001),t=ft.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=wr)),[r,o]}function dt(){return yo}function wa(i){return[]}var lt,Nt,Lt,ar,mn,gn,bn,yn,vn,wn,_n,kn,xn,Sn,En,An,In,Tn,Cn,Pn,On,Mn,Ln,Rn,Nn,jn,nr,Un,Dn,Bn,Fn,$n,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,ft,rn,wr,li,ci,ui,di,hi,fi,pi,mi,gi,bi,yi,yo,Gc=Je(()=>{le(),ue(),ce(),lt=[],Nt=!1,ar=-1,ha.prototype.run=function(){this.fun.apply(null,this.array)},mn="browser",gn="x64",bn="browser",yn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},vn=["/usr/bin/node"],wn=[],_n="v16.8.0",kn={},xn=function(i,e){console.warn((e?e+": ":"")+i)},Sn=function(i){bo("binding")},En=function(i){return 0},An=function(){return"/"},In=function(i){},Tn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Cn=!0,Pn=He,On=[],Mn={},Ln=!1,Rn={},Nn=He,jn=He,nr=function(){return{}},Un=nr,Dn=nr,Bn=He,Fn=He,$n=He,qn={},Hn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Wn=He,zn=He,Vn=He,Kn=He,Gn=He,Yn=He,Jn=He,Qn=void 0,Xn=void 0,Zn=void 0,ei=He,ti=2,ri=1,ni="/bin/usr/node",ii=9229,oi="node",si=[],ai=He,ft={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ft.now===void 0&&(rn=Date.now(),ft.timing&&ft.timing.navigationStart&&(rn=ft.timing.navigationStart),ft.now=()=>Date.now()-rn),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])},li=10,ci={},ui=0,di=dt,hi=dt,fi=dt,pi=dt,mi=dt,gi=He,bi=dt,yi=dt,yo={version:_n,versions:kn,arch:gn,platform:bn,browser:Cn,release:Tn,_rawDebug:Pn,moduleLoadList:On,binding:Sn,_linkedBinding:fa,_events:ci,_eventsCount:ui,_maxListeners:li,on:dt,addListener:di,once:hi,off:fi,removeListener:pi,removeAllListeners:mi,emit:gi,prependListener:bi,prependOnceListener:yi,listeners:wa,domain:Mn,_exiting:Ln,config:Rn,dlopen:pa,uptime:va,_getActiveRequests:ma,_getActiveHandles:ga,reallyExit:Nn,_kill:jn,cpuUsage:nr,resourceUsage:Un,memoryUsage:Dn,kill:Bn,exit:Fn,openStdin:$n,allowedNodeEnvironmentFlags:qn,assert:ba,features:Hn,_fatalExceptions:Wn,setUncaughtExceptionCaptureCallback:zn,hasUncaughtExceptionCaptureCallback:ya,emitWarning:xn,nextTick:da,_tickCallback:Vn,_debugProcess:Kn,_debugEnd:Gn,_startProfilerIdleNotifier:Yn,_stopProfilerIdleNotifier:Jn,stdout:Qn,stdin:Zn,stderr:Xn,abort:ei,umask:En,chdir:In,cwd:An,env:yn,title:mn,argv:vn,execArgv:wn,pid:ti,ppid:ri,execPath:ni,debugPort:ii,hrtime:vr,argv0:oi,_preload_modules:si,setSourceMapsEnabled:ai}}),ce=Je(()=>{Gc()});function Yc(){if(vi)return qt;vi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,n=r.length;o<n;++o)i[o]=r[o],e[r.charCodeAt(o)]=o;e[45]=62,e[95]=63;function s(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=f);var y=b===f?0:4-b%4;return[b,y]}function a(g){var f=s(g),b=f[0],y=f[1];return(b+y)*3/4-y}function l(g,f,b){return(f+b)*3/4-b}function c(g){var f,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),_=0,x=w>0?y-4:y,v;for(v=0;v<x;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[_++]=f>>16&255,m[_++]=f>>8&255,m[_++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[_++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[_++]=f>>8&255,m[_++]=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,b){for(var y,w=[],m=f;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function p(g){for(var f,b=g.length,y=b%3,w=[],m=16383,_=0,x=b-y;_<x;_+=m)w.push(d(g,_,_+m>x?x:_+m));return y===1?(f=g[b-1],w.push(i[f>>2]+i[f<<4&63]+"==")):y===2&&(f=(g[b-2]<<8)+g[b-1],w.push(i[f>>10]+i[f>>4&63]+i[f<<2&63]+"=")),w.join("")}return qt}function Jc(){return wi?ir:(wi=!0,ir.read=function(i,e,t,r,o){var n,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?o-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(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+i[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,r),n=n-c}return(g?-1:1)*s*Math.pow(2,n-r)},ir.write=function(i,e,t,r,o,n){var s,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,p=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;i[t+g]=a&255,g+=f,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;i[t+g]=s&255,g+=f,s/=256,c-=8);i[t+g-f]|=b*128},ir)}function Qc(){if(_i)return Et;_i=!0;let i=Yc(),e=Jc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Et.Buffer=s,Et.SlowBuffer=w,Et.INSPECT_MAX_BYTES=50;let r=2147483647;Et.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=o(),!s.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 o(){try{let h=new Uint8Array(1),k={foo:function(){return 42}};return Object.setPrototypeOf(k,Uint8Array.prototype),Object.setPrototypeOf(h,k),h.foo()===42}catch{return!1}}Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let k=new Uint8Array(h);return Object.setPrototypeOf(k,s.prototype),k}function s(h,k,A){if(typeof h=="number"){if(typeof k=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,k,A)}s.poolSize=8192;function a(h,k,A){if(typeof h=="string")return d(h,k);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(W(h,ArrayBuffer)||h&&W(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(W(h,SharedArrayBuffer)||h&&W(h.buffer,SharedArrayBuffer)))return f(h,k,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let $=h.valueOf&&h.valueOf();if($!=null&&$!==h)return s.from($,k,A);let Z=b(h);if(Z)return Z;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return s.from(h[Symbol.toPrimitive]("string"),k,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}s.from=function(h,k,A){return a(h,k,A)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,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,k,A){return l(h),h<=0?n(h):k!==void 0?typeof A=="string"?n(h).fill(k,A):n(h).fill(k):n(h)}s.alloc=function(h,k,A){return c(h,k,A)};function u(h){return l(h),n(h<0?0:y(h)|0)}s.allocUnsafe=function(h){return u(h)},s.allocUnsafeSlow=function(h){return u(h)};function d(h,k){if((typeof k!="string"||k==="")&&(k="utf8"),!s.isEncoding(k))throw new TypeError("Unknown encoding: "+k);let A=m(h,k)|0,$=n(A),Z=$.write(h,k);return Z!==A&&($=$.slice(0,Z)),$}function p(h){let k=h.length<0?0:y(h.length)|0,A=n(k);for(let $=0;$<k;$+=1)A[$]=h[$]&255;return A}function g(h){if(W(h,Uint8Array)){let k=new Uint8Array(h);return f(k.buffer,k.byteOffset,k.byteLength)}return p(h)}function f(h,k,A){if(k<0||h.byteLength<k)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<k+(A||0))throw new RangeError('"length" is outside of buffer bounds');let $;return k===void 0&&A===void 0?$=new Uint8Array(h):A===void 0?$=new Uint8Array(h,k):$=new Uint8Array(h,k,A),Object.setPrototypeOf($,s.prototype),$}function b(h){if(s.isBuffer(h)){let k=y(h.length)|0,A=n(k);return A.length===0||h.copy(A,0,0,k),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 y(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),s.alloc(+h)}s.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==s.prototype},s.compare=function(h,k){if(W(h,Uint8Array)&&(h=s.from(h,h.offset,h.byteLength)),W(k,Uint8Array)&&(k=s.from(k,k.offset,k.byteLength)),!s.isBuffer(h)||!s.isBuffer(k))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===k)return 0;let A=h.length,$=k.length;for(let Z=0,de=Math.min(A,$);Z<de;++Z)if(h[Z]!==k[Z]){A=h[Z],$=k[Z];break}return A<$?-1:$<A?1:0},s.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}},s.concat=function(h,k){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return s.alloc(0);let A;if(k===void 0)for(k=0,A=0;A<h.length;++A)k+=h[A].length;let $=s.allocUnsafe(k),Z=0;for(A=0;A<h.length;++A){let de=h[A];if(W(de,Uint8Array))Z+de.length>$.length?(s.isBuffer(de)||(de=s.from(de)),de.copy($,Z)):Uint8Array.prototype.set.call($,de,Z);else if(s.isBuffer(de))de.copy($,Z);else throw new TypeError('"list" argument must be an Array of Buffers');Z+=de.length}return $};function m(h,k){if(s.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||W(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,$=arguments.length>2&&arguments[2]===!0;if(!$&&A===0)return 0;let Z=!1;for(;;)switch(k){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(Z)return $?-1:q(h).length;k=(""+k).toLowerCase(),Z=!0}}s.byteLength=m;function _(h,k,A){let $=!1;if((k===void 0||k<0)&&(k=0),k>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,k>>>=0,A<=k))return"";for(h||(h="utf8");;)switch(h){case"hex":return H(this,k,A);case"utf8":case"utf-8":return L(this,k,A);case"ascii":return oe(this,k,A);case"latin1":case"binary":return z(this,k,A);case"base64":return T(this,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return te(this,k,A);default:if($)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),$=!0}}s.prototype._isBuffer=!0;function x(h,k,A){let $=h[k];h[k]=h[A],h[A]=$}s.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 k=0;k<h;k+=2)x(this,k,k+1);return this},s.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 k=0;k<h;k+=4)x(this,k,k+3),x(this,k+1,k+2);return this},s.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 k=0;k<h;k+=8)x(this,k,k+7),x(this,k+1,k+6),x(this,k+2,k+5),x(this,k+3,k+4);return this},s.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?L(this,0,h):_.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(h){if(!s.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:s.compare(this,h)===0},s.prototype.inspect=function(){let h="",k=Et.INSPECT_MAX_BYTES;return h=this.toString("hex",0,k).replace(/(.{2})/g,"$1 ").trim(),this.length>k&&(h+=" ... "),"<Buffer "+h+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(h,k,A,$,Z){if(W(h,Uint8Array)&&(h=s.from(h,h.offset,h.byteLength)),!s.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(k===void 0&&(k=0),A===void 0&&(A=h?h.length:0),$===void 0&&($=0),Z===void 0&&(Z=this.length),k<0||A>h.length||$<0||Z>this.length)throw new RangeError("out of range index");if($>=Z&&k>=A)return 0;if($>=Z)return-1;if(k>=A)return 1;if(k>>>=0,A>>>=0,$>>>=0,Z>>>=0,this===h)return 0;let de=Z-$,ke=A-k,K=Math.min(de,ke),ie=this.slice($,Z),Ie=h.slice(k,A);for(let Te=0;Te<K;++Te)if(ie[Te]!==Ie[Te]){de=ie[Te],ke=Ie[Te];break}return de<ke?-1:ke<de?1:0};function v(h,k,A,$,Z){if(h.length===0)return-1;if(typeof A=="string"?($=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,me(A)&&(A=Z?0:h.length-1),A<0&&(A=h.length+A),A>=h.length){if(Z)return-1;A=h.length-1}else if(A<0)if(Z)A=0;else return-1;if(typeof k=="string"&&(k=s.from(k,$)),s.isBuffer(k))return k.length===0?-1:S(h,k,A,$,Z);if(typeof k=="number")return k=k&255,typeof Uint8Array.prototype.indexOf=="function"?Z?Uint8Array.prototype.indexOf.call(h,k,A):Uint8Array.prototype.lastIndexOf.call(h,k,A):S(h,[k],A,$,Z);throw new TypeError("val must be string, number or Buffer")}function S(h,k,A,$,Z){let de=1,ke=h.length,K=k.length;if($!==void 0&&($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le")){if(h.length<2||k.length<2)return-1;de=2,ke/=2,K/=2,A/=2}function ie(Te,Pe){return de===1?Te[Pe]:Te.readUInt16BE(Pe*de)}let Ie;if(Z){let Te=-1;for(Ie=A;Ie<ke;Ie++)if(ie(h,Ie)===ie(k,Te===-1?0:Ie-Te)){if(Te===-1&&(Te=Ie),Ie-Te+1===K)return Te*de}else Te!==-1&&(Ie-=Ie-Te),Te=-1}else for(A+K>ke&&(A=ke-K),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Pe=0;Pe<K;Pe++)if(ie(h,Ie+Pe)!==ie(k,Pe)){Te=!1;break}if(Te)return Ie}return-1}s.prototype.includes=function(h,k,A){return this.indexOf(h,k,A)!==-1},s.prototype.indexOf=function(h,k,A){return v(this,h,k,A,!0)},s.prototype.lastIndexOf=function(h,k,A){return v(this,h,k,A,!1)};function E(h,k,A,$){A=Number(A)||0;let Z=h.length-A;$?($=Number($),$>Z&&($=Z)):$=Z;let de=k.length;$>de/2&&($=de/2);let ke;for(ke=0;ke<$;++ke){let K=parseInt(k.substr(ke*2,2),16);if(me(K))return ke;h[A+ke]=K}return ke}function I(h,k,A,$){return ye(q(k,h.length-A),h,A,$)}function P(h,k,A,$){return ye(ee(k),h,A,$)}function O(h,k,A,$){return ye(fe(k),h,A,$)}function B(h,k,A,$){return ye(he(k,h.length-A),h,A,$)}s.prototype.write=function(h,k,A,$){if(k===void 0)$="utf8",A=this.length,k=0;else if(A===void 0&&typeof k=="string")$=k,A=this.length,k=0;else if(isFinite(k))k=k>>>0,isFinite(A)?(A=A>>>0,$===void 0&&($="utf8")):($=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Z=this.length-k;if((A===void 0||A>Z)&&(A=Z),h.length>0&&(A<0||k<0)||k>this.length)throw new RangeError("Attempt to write outside buffer bounds");$||($="utf8");let de=!1;for(;;)switch($){case"hex":return E(this,h,k,A);case"utf8":case"utf-8":return I(this,h,k,A);case"ascii":case"latin1":case"binary":return P(this,h,k,A);case"base64":return O(this,h,k,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,h,k,A);default:if(de)throw new TypeError("Unknown encoding: "+$);$=(""+$).toLowerCase(),de=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,k,A){return k===0&&A===h.length?i.fromByteArray(h):i.fromByteArray(h.slice(k,A))}function L(h,k,A){A=Math.min(h.length,A);let $=[],Z=k;for(;Z<A;){let de=h[Z],ke=null,K=de>239?4:de>223?3:de>191?2:1;if(Z+K<=A){let ie,Ie,Te,Pe;switch(K){case 1:de<128&&(ke=de);break;case 2:ie=h[Z+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(ke=Pe));break;case 3:ie=h[Z+1],Ie=h[Z+2],(ie&192)===128&&(Ie&192)===128&&(Pe=(de&15)<<12|(ie&63)<<6|Ie&63,Pe>2047&&(Pe<55296||Pe>57343)&&(ke=Pe));break;case 4:ie=h[Z+1],Ie=h[Z+2],Te=h[Z+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&&(ke=Pe))}}ke===null?(ke=65533,K=1):ke>65535&&(ke-=65536,$.push(ke>>>10&1023|55296),ke=56320|ke&1023),$.push(ke),Z+=K}return D($)}let U=4096;function D(h){let k=h.length;if(k<=U)return String.fromCharCode.apply(String,h);let A="",$=0;for(;$<k;)A+=String.fromCharCode.apply(String,h.slice($,$+=U));return A}function oe(h,k,A){let $="";A=Math.min(h.length,A);for(let Z=k;Z<A;++Z)$+=String.fromCharCode(h[Z]&127);return $}function z(h,k,A){let $="";A=Math.min(h.length,A);for(let Z=k;Z<A;++Z)$+=String.fromCharCode(h[Z]);return $}function H(h,k,A){let $=h.length;(!k||k<0)&&(k=0),(!A||A<0||A>$)&&(A=$);let Z="";for(let de=k;de<A;++de)Z+=ve[h[de]];return Z}function te(h,k,A){let $=h.slice(k,A),Z="";for(let de=0;de<$.length-1;de+=2)Z+=String.fromCharCode($[de]+$[de+1]*256);return Z}s.prototype.slice=function(h,k){let A=this.length;h=~~h,k=k===void 0?A:~~k,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),k<0?(k+=A,k<0&&(k=0)):k>A&&(k=A),k<h&&(k=h);let $=this.subarray(h,k);return Object.setPrototypeOf($,s.prototype),$};function F(h,k,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+k>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let $=this[h],Z=1,de=0;for(;++de<k&&(Z*=256);)$+=this[h+de]*Z;return $},s.prototype.readUintBE=s.prototype.readUIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let $=this[h+--k],Z=1;for(;k>0&&(Z*=256);)$+=this[h+--k]*Z;return $},s.prototype.readUint8=s.prototype.readUInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]|this[h+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(h,k){return h=h>>>0,k||F(h,2,this.length),this[h]<<8|this[h+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},s.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,Q(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let $=k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24,Z=this[++h]+this[++h]*2**8+this[++h]*2**16+A*2**24;return BigInt($)+(BigInt(Z)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,Q(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let $=k*2**24+this[++h]*2**16+this[++h]*2**8+this[++h],Z=this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A;return(BigInt($)<<BigInt(32))+BigInt(Z)}),s.prototype.readIntLE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let $=this[h],Z=1,de=0;for(;++de<k&&(Z*=256);)$+=this[h+de]*Z;return Z*=128,$>=Z&&($-=Math.pow(2,8*k)),$},s.prototype.readIntBE=function(h,k,A){h=h>>>0,k=k>>>0,A||F(h,k,this.length);let $=k,Z=1,de=this[h+--$];for(;$>0&&(Z*=256);)de+=this[h+--$]*Z;return Z*=128,de>=Z&&(de-=Math.pow(2,8*k)),de},s.prototype.readInt8=function(h,k){return h=h>>>0,k||F(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},s.prototype.readInt16LE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(h,k){h=h>>>0,k||F(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},s.prototype.readInt32BE=function(h,k){return h=h>>>0,k||F(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},s.prototype.readBigInt64LE=ae(function(h){h=h>>>0,Q(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let $=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt($)<<BigInt(32))+BigInt(k+this[++h]*2**8+this[++h]*2**16+this[++h]*2**24)}),s.prototype.readBigInt64BE=ae(function(h){h=h>>>0,Q(h,"offset");let k=this[h],A=this[h+7];(k===void 0||A===void 0)&&ge(h,this.length-8);let $=(k<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt($)<<BigInt(32))+BigInt(this[++h]*2**24+this[++h]*2**16+this[++h]*2**8+A)}),s.prototype.readFloatLE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!0,23,4)},s.prototype.readFloatBE=function(h,k){return h=h>>>0,k||F(h,4,this.length),e.read(this,h,!1,23,4)},s.prototype.readDoubleLE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!0,52,8)},s.prototype.readDoubleBE=function(h,k){return h=h>>>0,k||F(h,8,this.length),e.read(this,h,!1,52,8)};function X(h,k,A,$,Z,de){if(!s.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(k>Z||k<de)throw new RangeError('"value" argument is out of bounds');if(A+$>h.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(h,k,A,$){if(h=+h,k=k>>>0,A=A>>>0,!$){let ke=Math.pow(2,8*A)-1;X(this,h,k,A,ke,0)}let Z=1,de=0;for(this[k]=h&255;++de<A&&(Z*=256);)this[k+de]=h/Z&255;return k+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(h,k,A,$){if(h=+h,k=k>>>0,A=A>>>0,!$){let ke=Math.pow(2,8*A)-1;X(this,h,k,A,ke,0)}let Z=A-1,de=1;for(this[k+Z]=h&255;--Z>=0&&(de*=256);)this[k+Z]=h/de&255;return k+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,1,255,0),this[k]=h&255,k+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,2,65535,0),this[k]=h&255,this[k+1]=h>>>8,k+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,2,65535,0),this[k]=h>>>8,this[k+1]=h&255,k+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,4,4294967295,0),this[k+3]=h>>>24,this[k+2]=h>>>16,this[k+1]=h>>>8,this[k]=h&255,k+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,4,4294967295,0),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4};function M(h,k,A,$,Z){Y(k,$,Z,h,A,7);let de=Number(k&BigInt(4294967295));h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de;let ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,ke=ke>>8,h[A++]=ke,A}function J(h,k,A,$,Z){Y(k,$,Z,h,A,7);let de=Number(k&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 ke=Number(k>>BigInt(32)&BigInt(4294967295));return h[A+3]=ke,ke=ke>>8,h[A+2]=ke,ke=ke>>8,h[A+1]=ke,ke=ke>>8,h[A]=ke,A+8}s.prototype.writeBigUInt64LE=ae(function(h,k=0){return M(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(h,k=0){return J(this,h,k,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(h,k,A,$){if(h=+h,k=k>>>0,!$){let K=Math.pow(2,8*A-1);X(this,h,k,A,K-1,-K)}let Z=0,de=1,ke=0;for(this[k]=h&255;++Z<A&&(de*=256);)h<0&&ke===0&&this[k+Z-1]!==0&&(ke=1),this[k+Z]=(h/de>>0)-ke&255;return k+A},s.prototype.writeIntBE=function(h,k,A,$){if(h=+h,k=k>>>0,!$){let K=Math.pow(2,8*A-1);X(this,h,k,A,K-1,-K)}let Z=A-1,de=1,ke=0;for(this[k+Z]=h&255;--Z>=0&&(de*=256);)h<0&&ke===0&&this[k+Z+1]!==0&&(ke=1),this[k+Z]=(h/de>>0)-ke&255;return k+A},s.prototype.writeInt8=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,1,127,-128),h<0&&(h=255+h+1),this[k]=h&255,k+1},s.prototype.writeInt16LE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,2,32767,-32768),this[k]=h&255,this[k+1]=h>>>8,k+2},s.prototype.writeInt16BE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,2,32767,-32768),this[k]=h>>>8,this[k+1]=h&255,k+2},s.prototype.writeInt32LE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,4,2147483647,-2147483648),this[k]=h&255,this[k+1]=h>>>8,this[k+2]=h>>>16,this[k+3]=h>>>24,k+4},s.prototype.writeInt32BE=function(h,k,A){return h=+h,k=k>>>0,A||X(this,h,k,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[k]=h>>>24,this[k+1]=h>>>16,this[k+2]=h>>>8,this[k+3]=h&255,k+4},s.prototype.writeBigInt64LE=ae(function(h,k=0){return M(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(h,k=0){return J(this,h,k,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function be(h,k,A,$,Z,de){if(A+$>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function re(h,k,A,$,Z){return k=+k,A=A>>>0,Z||be(h,k,A,4),e.write(h,k,A,$,23,4),A+4}s.prototype.writeFloatLE=function(h,k,A){return re(this,h,k,!0,A)},s.prototype.writeFloatBE=function(h,k,A){return re(this,h,k,!1,A)};function we(h,k,A,$,Z){return k=+k,A=A>>>0,Z||be(h,k,A,8),e.write(h,k,A,$,52,8),A+8}s.prototype.writeDoubleLE=function(h,k,A){return we(this,h,k,!0,A)},s.prototype.writeDoubleBE=function(h,k,A){return we(this,h,k,!1,A)},s.prototype.copy=function(h,k,A,$){if(!s.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!$&&$!==0&&($=this.length),k>=h.length&&(k=h.length),k||(k=0),$>0&&$<A&&($=A),$===A||h.length===0||this.length===0)return 0;if(k<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if($<0)throw new RangeError("sourceEnd out of bounds");$>this.length&&($=this.length),h.length-k<$-A&&($=h.length-k+A);let Z=$-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(k,A,$):Uint8Array.prototype.set.call(h,this.subarray(A,$),k),Z},s.prototype.fill=function(h,k,A,$){if(typeof h=="string"){if(typeof k=="string"?($=k,k=0,A=this.length):typeof A=="string"&&($=A,A=this.length),$!==void 0&&typeof $!="string")throw new TypeError("encoding must be a string");if(typeof $=="string"&&!s.isEncoding($))throw new TypeError("Unknown encoding: "+$);if(h.length===1){let de=h.charCodeAt(0);($==="utf8"&&de<128||$==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(k<0||this.length<k||this.length<A)throw new RangeError("Out of range index");if(A<=k)return this;k=k>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let Z;if(typeof h=="number")for(Z=k;Z<A;++Z)this[Z]=h;else{let de=s.isBuffer(h)?h:s.from(h,$),ke=de.length;if(ke===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(Z=0;Z<A-k;++Z)this[Z+k]=de[Z%ke]}return this};let G={};function j(h,k,A){G[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:k.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code($){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:$,writable:!0})}toString(){return`${this.name} [${h}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(h){return h?`${h} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(h,k){return`The "${h}" argument must be of type number. Received type ${typeof k}`},TypeError),j("ERR_OUT_OF_RANGE",function(h,k,A){let $=`The value of "${h}" is out of range.`,Z=A;return Number.isInteger(A)&&Math.abs(A)>2**32?Z=ne(String(A)):typeof A=="bigint"&&(Z=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(Z=ne(Z)),Z+="n"),$+=` It must be ${k}. Received ${Z}`,$},RangeError);function ne(h){let k="",A=h.length,$=h[0]==="-"?1:0;for(;A>=$+4;A-=3)k=`_${h.slice(A-3,A)}${k}`;return`${h.slice(0,A)}${k}`}function V(h,k,A){Q(k,"offset"),(h[k]===void 0||h[k+A]===void 0)&&ge(k,h.length-(A+1))}function Y(h,k,A,$,Z,de){if(h>A||h<k){let ke=typeof k=="bigint"?"n":"",K;throw k===0||k===BigInt(0)?K=`>= 0${ke} and < 2${ke} ** ${(de+1)*8}${ke}`:K=`>= -(2${ke} ** ${(de+1)*8-1}${ke}) and < 2 ** ${(de+1)*8-1}${ke}`,new G.ERR_OUT_OF_RANGE("value",K,h)}V($,Z,de)}function Q(h,k){if(typeof h!="number")throw new G.ERR_INVALID_ARG_TYPE(k,"number",h)}function ge(h,k,A){throw Math.floor(h)!==h?(Q(h,A),new G.ERR_OUT_OF_RANGE("offset","an integer",h)):k<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${k}`,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,k){k=k||1/0;let A,$=h.length,Z=null,de=[];for(let ke=0;ke<$;++ke){if(A=h.charCodeAt(ke),A>55295&&A<57344){if(!Z){if(A>56319){(k-=3)>-1&&de.push(239,191,189);continue}else if(ke+1===$){(k-=3)>-1&&de.push(239,191,189);continue}Z=A;continue}if(A<56320){(k-=3)>-1&&de.push(239,191,189),Z=A;continue}A=(Z-55296<<10|A-56320)+65536}else Z&&(k-=3)>-1&&de.push(239,191,189);if(Z=null,A<128){if((k-=1)<0)break;de.push(A)}else if(A<2048){if((k-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((k-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((k-=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 k=[];for(let A=0;A<h.length;++A)k.push(h.charCodeAt(A)&255);return k}function he(h,k){let A,$,Z,de=[];for(let ke=0;ke<h.length&&!((k-=2)<0);++ke)A=h.charCodeAt(ke),$=A>>8,Z=A%256,de.push(Z),de.push($);return de}function fe(h){return i.toByteArray(R(h))}function ye(h,k,A,$){let Z;for(Z=0;Z<$&&!(Z+A>=k.length||Z>=h.length);++Z)k[Z+A]=h[Z];return Z}function W(h,k){return h instanceof k||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===k.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",k=new Array(256);for(let A=0;A<16;++A){let $=A*16;for(let Z=0;Z<16;++Z)k[$+Z]=h[A]+h[Z]}return k})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return Et}var qt,vi,ir,wi,Et,_i,Xc=Je(()=>{le(),ue(),ce(),qt={},vi=!1,ir={},wi=!1,Et={},_i=!1}),Fe={};Gt(Fe,{Buffer:()=>zr,INSPECT_MAX_BYTES:()=>_a,default:()=>ht,kMaxLength:()=>ka});var ht,zr,_a,ka,$e=Je(()=>{le(),ue(),ce(),Xc(),ht=Qc(),ht.Buffer,ht.SlowBuffer,ht.INSPECT_MAX_BYTES,ht.kMaxLength,zr=ht.Buffer,_a=ht.INSPECT_MAX_BYTES,ka=ht.kMaxLength}),ue=Je(()=>{$e()}),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 o="";for(let n=0;n<r.length;n++)o+=` ${r[n].stack}
|
|
2
|
+
`;super(o),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,o){return r.includes(o)},ArrayPrototypeIndexOf(r,o){return r.indexOf(o)},ArrayPrototypeJoin(r,o){return r.join(o)},ArrayPrototypeMap(r,o){return r.map(o)},ArrayPrototypePop(r,o){return r.pop(o)},ArrayPrototypePush(r,o){return r.push(o)},ArrayPrototypeSlice(r,o,n){return r.slice(o,n)},Error,FunctionPrototypeCall(r,o,...n){return r.call(o,...n)},FunctionPrototypeSymbolHasInstance(r,o){return Function.prototype[Symbol.hasInstance].call(r,o)},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,o){return Object.defineProperties(r,o)},ObjectDefineProperty(r,o,n){return Object.defineProperty(r,o,n)},ObjectGetOwnPropertyDescriptor(r,o){return Object.getOwnPropertyDescriptor(r,o)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,o){return Object.setPrototypeOf(r,o)},Promise,PromisePrototypeCatch(r,o){return r.catch(o)},PromisePrototypeThen(r,o,n){return r.then(o,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,o){return r.test(o)},SafeSet:Set,String,StringPrototypeSlice(r,o,n){return r.slice(o,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,o,n){return r.set(o,n)},Boolean,Uint8Array}}),xa=pe((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[o,n]){let s=r.shift();return n==="f"?s.toFixed(6):n==="j"?JSON.stringify(s):n==="s"&&typeof s=="object"?`${s.constructor!==Object?s.constructor.name:""} {}`.trim():s.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}=xa(),{AggregateError:o}=De(),n=globalThis.AggregateError||o,s=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,_){if(!m)throw new u.ERR_INTERNAL_ASSERTION(_)}function p(m){let _="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)_=`_${m.slice(x-3,x)}${_}`;return`${m.slice(0,x)}${_}`}function g(m,_,x){if(typeof _=="function")return d(_.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${_.length}).`),_(...x);let v=(_.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?_:t(_,...x)}function f(m,_,x){x||(x=Error);class v extends x{constructor(...E){super(g(m,_,E))}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[s]=!0,u[m]=v}function b(m){let _=c+m.name;return Object.defineProperty(m,"name",{value:_}),m}function y(m,_){if(m&&_&&m!==_){if(Array.isArray(_.errors))return _.errors.push(m),_;let x=new n([_,m],_.message);return x.code=_.code,x}return m||_}var w=class extends Error{constructor(m="The operation was aborted",_=void 0){if(_!==void 0&&typeof _!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",_);super(m,_),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,_,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(_)||(_=[_]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let S=[],E=[],I=[];for(let O of _)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?S.push(O.toLowerCase()):l.test(O)?E.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(E.length>0){let O=S.indexOf("object");O!==-1&&(S.splice(S,O,1),E.push("Object"))}if(S.length>0){switch(S.length){case 1:v+=`of type ${S[0]}`;break;case 2:v+=`one of type ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`one of type ${S.join(", ")}, or ${O}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`an instance of ${E.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(x==null)v+=`. Received ${x}`;else if(typeof x=="function"&&x.name)v+=`. Received function ${x.name}`;else if(typeof x=="object"){var P;if((P=x.constructor)!==null&&P!==void 0&&P.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,_,x="is invalid")=>{let v=r(_);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,_,x)=>{var v;let S=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 "${_}" function but got ${S}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let _,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:_+=`The ${m[0]} argument`;break;case 2:_+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();_+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${_} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,_,x)=>{d(_,'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 S=BigInt(2)**BigInt(32);(x>S||x<-S)&&(v=p(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${_}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),cr=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}),Tt={};Gt(Tt,{EventEmitter:()=>Sa,default:()=>Ht,defaultMaxListeners:()=>Ea,init:()=>Aa,listenerCount:()=>Ia,on:()=>Ta,once:()=>Ca});function Zc(){if(ki)return or;ki=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(x,v,S){return Function.prototype.apply.call(x,v,S)},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 o=Number.isNaN||function(x){return x!==x};function n(){n.init.call(this)}or=n,or.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var s=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 s},set:function(x){if(typeof x!="number"||x<0||o(x))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+x+".");s=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||o(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=[],S=1;S<arguments.length;S++)v.push(arguments[S]);var E=x==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var B=I[x];if(B===void 0)return!1;if(typeof B=="function")e(B,this,v);else for(var T=B.length,L=f(B,T),S=0;S<T;++S)e(L[S],this,v);return!0};function c(x,v,S,E){var I,P,O;if(a(S),P=x._events,P===void 0?(P=x._events=Object.create(null),x._eventsCount=0):(P.newListener!==void 0&&(x.emit("newListener",v,S.listener?S.listener:S),P=x._events),O=P[v]),O===void 0)O=P[v]=S,++x._eventsCount;else if(typeof O=="function"?O=P[v]=E?[S,O]:[O,S]:E?O.unshift(S):O.push(S),I=l(x),I>0&&O.length>I&&!O.warned){O.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=x,B.type=v,B.count=O.length,r(B)}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,S){var E={fired:!1,wrapFn:void 0,target:x,type:v,listener:S},I=u.bind(E);return I.listener=S,E.wrapFn=I,I}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 S,E,I,P,O;if(a(v),E=this._events,E===void 0)return this;if(S=E[x],S===void 0)return this;if(S===v||S.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[x],E.removeListener&&this.emit("removeListener",x,S.listener||v));else if(typeof S!="function"){for(I=-1,P=S.length-1;P>=0;P--)if(S[P]===v||S[P].listener===v){O=S[P].listener,I=P;break}if(I<0)return this;I===0?S.shift():b(S,I),S.length===1&&(E[x]=S[0]),E.removeListener!==void 0&&this.emit("removeListener",x,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(x){var v,S,E;if(S=this._events,S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[x]),this;if(arguments.length===0){var I=Object.keys(S),P;for(E=0;E<I.length;++E)P=I[E],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=S[x],typeof v=="function")this.removeListener(x,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(x,v[E]);return this};function p(x,v,S){var E=x._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?S?[I.listener||I]:[I]:S?y(I):f(I,I.length)}n.prototype.listeners=function(x){return p(this,x,!0)},n.prototype.rawListeners=function(x){return p(this,x,!1)},n.listenerCount=function(x,v){return typeof x.listenerCount=="function"?x.listenerCount(v):g.call(x,v)},n.prototype.listenerCount=g;function g(x){var v=this._events;if(v!==void 0){var S=v[x];if(typeof S=="function")return 1;if(S!==void 0)return S.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(x,v){for(var S=new Array(v),E=0;E<v;++E)S[E]=x[E];return S}function b(x,v){for(;v+1<x.length;v++)x[v]=x[v+1];x.pop()}function y(x){for(var v=new Array(x.length),S=0;S<v.length;++S)v[S]=x[S].listener||x[S];return v}function w(x,v){return new Promise(function(S,E){function I(O){x.removeListener(v,P),E(O)}function P(){typeof x.removeListener=="function"&&x.removeListener("error",I),S([].slice.call(arguments))}_(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,S){typeof x.on=="function"&&_(x,"error",v,S)}function _(x,v,S,E){if(typeof x.on=="function")E.once?x.once(v,S):x.on(v,S);else if(typeof x.addEventListener=="function")x.addEventListener(v,function I(P){E.once&&x.removeEventListener(v,I),S(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof x)}return or}var or,ki,Ht,Sa,Ea,Aa,Ia,Ta,Ca,Ut=Je(()=>{le(),ue(),ce(),or={},ki=!1,Ht=Zc(),Ht.once,Ht.once=function(i,e){return new Promise((t,r)=>{function o(...s){n!==void 0&&i.removeListener("error",n),t(s)}let n;e!=="error"&&(n=s=>{i.removeListener(name,o),r(s)},i.once("error",n)),i.once(e,o)})},Ht.on=function(i,e){let t=[],r=[],o=null,n=!1,s={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(o){let u=Promise.reject(o);return o=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){o=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),s;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):o=c,s.return()}},{EventEmitter:Sa,defaultMaxListeners:Ea,init:Aa,listenerCount:Ia,on:Ta,once:Ca}=Ht}),Ye=pe((i,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),{format:r,inspect:o}=xa(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=De(),c=globalThis.AbortSignal||cr().AbortSignal,u=globalThis.AbortController||cr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},f=(y,w)=>{if(y!==void 0&&(y===null||typeof y!="object"||!("aborted"in y)))throw new n(w,"AbortSignal",y)},b=(y,w)=>{if(typeof y!="function")throw new n(w,"Function",y)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(y){let w=!1;return function(...m){w||(w=!0,y.apply(this,m))}},createDeferredPromise:function(){let y,w;return{promise:new Promise((m,_)=>{y=m,w=_}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((_,...x)=>_?m(_):w(...x))})},debuglog(){return function(){}},format:r,inspect:o,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Ut(),Re(Tt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);f(y,"signal"),b(w,"listener");let m;return y.aborted?queueMicrotask(()=>w()):(y.addEventListener("abort",w,{__proto__:null,once:!0,[s]:!0}),m=()=>{y.removeEventListener("abort",w)}),{__proto__:null,[l](){var _;(_=m)===null||_===void 0||_()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(_=>{f(_,"signals"),_.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(_=>_.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),dr=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:o,ArrayPrototypeMap:n,NumberIsInteger:s,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:b}=De(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:S}=Ye(),{isAsyncFunction:E,isArrayBufferView:I}=Ye().types,P={};function O(W){return W===(W|0)}function B(W){return W===W>>>0}var T=/^[0-7]+$/,L="must be a 32-bit unsigned integer or an octal string";function U(W,me,ve){if(typeof W>"u"&&(W=ve),typeof W=="string"){if(p(T,W)===null)throw new _(me,W,L);W=u(W,8)}return z(W,me),W}var D=y((W,me,ve=c,ae=l)=>{if(typeof W!="number")throw new m(me,"number",W);if(!s(W))throw new x(me,"an integer",W);if(W<ve||W>ae)throw new x(me,`>= ${ve} && <= ${ae}`,W)}),oe=y((W,me,ve=-2147483648,ae=2147483647)=>{if(typeof W!="number")throw new m(me,"number",W);if(!s(W))throw new x(me,"an integer",W);if(W<ve||W>ae)throw new x(me,`>= ${ve} && <= ${ae}`,W)}),z=y((W,me,ve=!1)=>{if(typeof W!="number")throw new m(me,"number",W);if(!s(W))throw new x(me,"an integer",W);let ae=ve?1:0,Oe=4294967295;if(W<ae||W>Oe)throw new x(me,`>= ${ae} && <= ${Oe}`,W)});function H(W,me){if(typeof W!="string")throw new m(me,"string",W)}function te(W,me,ve=void 0,ae){if(typeof W!="number")throw new m(me,"number",W);if(ve!=null&&W<ve||ae!=null&&W>ae||(ve!=null||ae!=null)&&a(W))throw new x(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,W)}var F=y((W,me,ve)=>{if(!r(ve,W)){let ae="must be one of: "+o(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:g(Oe)),", ");throw new _(me,W,ae)}});function X(W,me){if(typeof W!="boolean")throw new m(me,"boolean",W)}function M(W,me,ve){return W==null||!d(W,me)?ve:W[me]}var J=y((W,me,ve=null)=>{let ae=M(ve,"allowArray",!1),Oe=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&W===null||!ae&&t(W)||typeof W!="object"&&(!Oe||typeof W!="function"))throw new m(me,"Object",W)}),be=y((W,me)=>{if(W!=null&&typeof W!="object"&&typeof W!="function")throw new m(me,"a dictionary",W)}),re=y((W,me,ve=0)=>{if(!t(W))throw new m(me,"Array",W);if(W.length<ve){let ae=`must be longer than ${ve}`;throw new _(me,W,ae)}});function we(W,me){re(W,me);for(let ve=0;ve<W.length;ve++)H(W[ve],`${me}[${ve}]`)}function G(W,me){re(W,me);for(let ve=0;ve<W.length;ve++)X(W[ve],`${me}[${ve}]`)}function j(W,me){re(W,me);for(let ve=0;ve<W.length;ve++){let ae=W[ve],Oe=`${me}[${ve}]`;if(ae==null)throw new m(Oe,"AbortSignal",ae);ge(ae,Oe)}}function ne(W,me="signal"){if(H(W,me),P[W]===void 0)throw P[f(W)]!==void 0?new v(W+" (signals must use all capital letters)"):new v(W)}var V=y((W,me="buffer")=>{if(!I(W))throw new m(me,["Buffer","TypedArray","DataView"],W)});function Y(W,me){let ve=S(me),ae=W.length;if(ve==="hex"&&ae%2!==0)throw new _("encoding",me,`is invalid for data of length ${ae}`)}function Q(W,me="Port",ve=!0){if(typeof W!="number"&&typeof W!="string"||typeof W=="string"&&b(W).length===0||+W!==+W>>>0||W>65535||W===0&&!ve)throw new w(me,W,ve);return W|0}var ge=y((W,me)=>{if(W!==void 0&&(W===null||typeof W!="object"||!("aborted"in W)))throw new m(me,"AbortSignal",W)}),se=y((W,me)=>{if(typeof W!="function")throw new m(me,"Function",W)}),R=y((W,me)=>{if(typeof W!="function"||E(W))throw new m(me,"Function",W)}),q=y((W,me)=>{if(W!==void 0)throw new m(me,"undefined",W)});function ee(W,me,ve){if(!r(ve,W))throw new m(me,`('${o(ve,"|")}')`,W)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(W,me){if(typeof W>"u"||!p(he,W))throw new _(me,W,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(W){if(typeof W=="string")return fe(W,"hints"),W;if(t(W)){let me=W.length,ve="";if(me===0)return ve;for(let ae=0;ae<me;ae++){let Oe=W[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new _("hints",W,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:B,parseFileMode:U,validateArray:re,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:j,validateBoolean:X,validateBuffer:V,validateDictionary:be,validateEncoding:Y,validateFunction:se,validateInt32:oe,validateInteger:D,validateNumber:te,validateObject:J,validateOneOf:F,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:H,validateUint32:z,validateUndefined:q,validateUnion:ee,validateAbortSignal:ge,validateLinkHeaderValue:ye}}),Dt=pe((i,e)=>{le(),ue(),ce();var t=e.exports={},r,o;function n(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?o=clearTimeout:o=s}catch{o=s}})();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(o===clearTimeout)return clearTimeout(w);if((o===s||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(w);try{return o(w)}catch{try{return o.call(null,w)}catch{return o.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 _=1;_<arguments.length;_++)m[_-1]=arguments[_];c.push(new b(w,m)),c.length===1&&!u&&a(f)};function b(w,m){this.fun=w,this.array=m}b.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function y(){}t.on=y,t.addListener=y,t.once=y,t.off=y,t.removeListener=y,t.removeAllListeners=y,t.emit=y,t.prependListener=y,t.prependOnceListener=y,t.listeners=function(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}}),bt=pe((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=De(),n=o("nodejs.stream.destroyed"),s=o("nodejs.stream.errored"),a=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),c=o("nodejs.stream.disturbed"),u=o("nodejs.webstream.isClosedPromise"),d=o("nodejs.webstream.controllerErrorFunction");function p(M,J=!1){var be;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!J||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((be=M._readableState)===null||be===void 0?void 0:be.readable)!==!1)&&(!M._writableState||M._readableState))}function g(M){var J;return!!(M&&typeof M.write=="function"&&typeof M.on=="function"&&(!M._readableState||((J=M._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(M){return!!(M&&typeof M.pipe=="function"&&M._readableState&&typeof M.on=="function"&&typeof M.write=="function")}function b(M){return M&&(M._readableState||M._writableState||typeof M.write=="function"&&typeof M.on=="function"||typeof M.pipe=="function"&&typeof M.on=="function")}function y(M){return!!(M&&!b(M)&&typeof M.pipeThrough=="function"&&typeof M.getReader=="function"&&typeof M.cancel=="function")}function w(M){return!!(M&&!b(M)&&typeof M.getWriter=="function"&&typeof M.abort=="function")}function m(M){return!!(M&&!b(M)&&typeof M.readable=="object"&&typeof M.writable=="object")}function _(M){return y(M)||w(M)||m(M)}function x(M,J){return M==null?!1:J===!0?typeof M[t]=="function":J===!1?typeof M[r]=="function":typeof M[t]=="function"||typeof M[r]=="function"}function v(M){if(!b(M))return null;let J=M._writableState,be=M._readableState,re=J||be;return!!(M.destroyed||M[n]||re!=null&&re.destroyed)}function S(M){if(!g(M))return null;if(M.writableEnded===!0)return!0;let J=M._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function E(M,J){if(!g(M))return null;if(M.writableFinished===!0)return!0;let be=M._writableState;return be!=null&&be.errored?!1:typeof be?.finished!="boolean"?null:!!(be.finished||J===!1&&be.ended===!0&&be.length===0)}function I(M){if(!p(M))return null;if(M.readableEnded===!0)return!0;let J=M._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function P(M,J){if(!p(M))return null;let be=M._readableState;return be!=null&&be.errored?!1:typeof be?.endEmitted!="boolean"?null:!!(be.endEmitted||J===!1&&be.ended===!0&&be.length===0)}function O(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:p(M)&&M.readable&&!P(M)}function B(M){return M&&M[l]!=null?M[l]:typeof M?.writable!="boolean"?null:v(M)?!1:g(M)&&M.writable&&!S(M)}function T(M,J){return b(M)?v(M)?!0:!(J?.readable!==!1&&O(M)||J?.writable!==!1&&B(M)):null}function L(M){var J,be;return b(M)?M.writableErrored?M.writableErrored:(J=(be=M._writableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function U(M){var J,be;return b(M)?M.readableErrored?M.readableErrored:(J=(be=M._readableState)===null||be===void 0?void 0:be.errored)!==null&&J!==void 0?J:null:null}function D(M){if(!b(M))return null;if(typeof M.closed=="boolean")return M.closed;let J=M._writableState,be=M._readableState;return typeof J?.closed=="boolean"||typeof be?.closed=="boolean"?J?.closed||be?.closed:typeof M._closed=="boolean"&&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 z(M){return typeof M._sent100=="boolean"&&oe(M)}function H(M){var J;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((J=M.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function te(M){if(!b(M))return null;let J=M._writableState,be=M._readableState,re=J||be;return!re&&z(M)||!!(re&&re.autoDestroy&&re.emitClose&&re.closed===!1)}function F(M){var J;return!!(M&&((J=M[c])!==null&&J!==void 0?J:M.readableDidRead||M.readableAborted))}function X(M){var J,be,re,we,G,j,ne,V,Y,Q;return!!(M&&((J=(be=(re=(we=(G=(j=M[s])!==null&&j!==void 0?j:M.readableErrored)!==null&&G!==void 0?G:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&re!==void 0?re:(V=M._writableState)===null||V===void 0?void 0:V.errorEmitted)!==null&&be!==void 0?be:(Y=M._readableState)===null||Y===void 0?void 0:Y.errored)!==null&&J!==void 0?J:!((Q=M._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:F,kIsDisturbed:c,isErrored:X,kIsErrored:s,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:D,isDuplexNodeStream:f,isFinished:T,isIterable:x,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:U,isNodeStream:b,isWebStream:_,isWritable:B,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:S,isWritableFinished:E,isWritableErrored:L,isServerRequest:H,isServerResponse:z,willEmitClose:te,isTransformStream:m}}),Ct=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{AbortError:r,codes:o}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=o,{kEmptyObject:a,once:l}=Ye(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=dr(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:b}=De(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:_,isReadableFinished:x,isReadableErrored:v,isWritable:S,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:B,willEmitClose:T,kIsClosedPromise:L}=bt(),U;function D(F){return F.setHeader&&typeof F.abort=="function"}var oe=()=>{};function z(F,X,M){var J,be;if(arguments.length===2?(M=X,X=a):X==null?X=a:d(X,"options"),u(M,"callback"),c(X.signal,"options.signal"),M=l(M),_(F)||I(F))return H(F,X,M);if(!B(F))throw new n("stream",["ReadableStream","WritableStream","Stream"],F);let re=(J=X.readable)!==null&&J!==void 0?J:m(F),we=(be=X.writable)!==null&&be!==void 0?be:E(F),G=F._writableState,j=F._readableState,ne=()=>{F.writable||Q()},V=T(F)&&m(F)===re&&E(F)===we,Y=P(F,!1),Q=()=>{Y=!0,F.destroyed&&(V=!1),!(V&&(!F.readable||re))&&(!re||ge)&&M.call(F)},ge=x(F,!1),se=()=>{ge=!0,F.destroyed&&(V=!1),!(V&&(!F.writable||we))&&(!we||Y)&&M.call(F)},R=W=>{M.call(F,W)},q=y(F),ee=()=>{q=!0;let W=O(F)||v(F);if(W&&typeof W!="boolean")return M.call(F,W);if(re&&!ge&&m(F,!0)&&!x(F,!1))return M.call(F,new s);if(we&&!Y&&!P(F,!1))return M.call(F,new s);M.call(F)},he=()=>{q=!0;let W=O(F)||v(F);if(W&&typeof W!="boolean")return M.call(F,W);M.call(F)},fe=()=>{F.req.on("finish",Q)};D(F)?(F.on("complete",Q),V||F.on("abort",ee),F.req?fe():F.on("request",fe)):we&&!G&&(F.on("end",ne),F.on("close",ne)),!V&&typeof F.aborted=="boolean"&&F.on("aborted",ee),F.on("end",se),F.on("finish",Q),X.error!==!1&&F.on("error",R),F.on("close",ee),q?t.nextTick(ee):G!=null&&G.errorEmitted||j!=null&&j.errorEmitted?V||t.nextTick(he):(!re&&(!V||w(F))&&(Y||S(F)===!1)||!we&&(!V||S(F))&&(ge||w(F)===!1)||j&&F.req&&F.aborted)&&t.nextTick(he);let ye=()=>{M=oe,F.removeListener("aborted",ee),F.removeListener("complete",Q),F.removeListener("abort",ee),F.removeListener("request",fe),F.req&&F.req.removeListener("finish",Q),F.removeListener("end",ne),F.removeListener("close",ne),F.removeListener("finish",Q),F.removeListener("end",se),F.removeListener("error",R),F.removeListener("close",ee)};if(X.signal&&!q){let W=()=>{let me=M;ye(),me.call(F,new r(void 0,{cause:X.signal.reason}))};if(X.signal.aborted)t.nextTick(W);else{U=U||Ye().addAbortListener;let me=U(X.signal,W),ve=M;M=l((...ae)=>{me[b](),ve.apply(F,ae)})}}return ye}function H(F,X,M){let J=!1,be=oe;if(X.signal)if(be=()=>{J=!0,M.call(F,new r(void 0,{cause:X.signal.reason}))},X.signal.aborted)t.nextTick(be);else{U=U||Ye().addAbortListener;let we=U(X.signal,be),G=M;M=l((...j)=>{we[b](),G.apply(F,j)})}let re=(...we)=>{J||t.nextTick(()=>M.apply(F,we))};return f(F[L].promise,re,re),oe}function te(F,X){var M;let J=!1;return X===null&&(X=a),(M=X)!==null&&M!==void 0&&M.cleanup&&(p(X.cleanup,"cleanup"),J=X.cleanup),new g((be,re)=>{let we=z(F,X,G=>{J&&we(),G?re(G):be()})})}e.exports=z,e.exports.finished=te}),Yt=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ke(),{Symbol:s}=De(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=bt(),d=s("kDestroy"),p=s("kConstruct");function g(T,L,U){T&&(T.stack,L&&!L.errored&&(L.errored=T),U&&!U.errored&&(U.errored=T))}function f(T,L){let U=this._readableState,D=this._writableState,oe=D||U;return D!=null&&D.destroyed||U!=null&&U.destroyed?(typeof L=="function"&&L(),this):(g(T,D,U),D&&(D.destroyed=!0),U&&(U.destroyed=!0),oe.constructed?b(this,T,L):this.once(d,function(z){b(this,r(z,T),L)}),this)}function b(T,L,U){let D=!1;function oe(z){if(D)return;D=!0;let H=T._readableState,te=T._writableState;g(z,te,H),te&&(te.closed=!0),H&&(H.closed=!0),typeof U=="function"&&U(z),z?t.nextTick(y,T,z):t.nextTick(w,T)}try{T._destroy(L||null,oe)}catch(z){oe(z)}}function y(T,L){m(T,L),w(T)}function w(T){let L=T._readableState,U=T._writableState;U&&(U.closeEmitted=!0),L&&(L.closeEmitted=!0),(U!=null&&U.emitClose||L!=null&&L.emitClose)&&T.emit("close")}function m(T,L){let U=T._readableState,D=T._writableState;D!=null&&D.errorEmitted||U!=null&&U.errorEmitted||(D&&(D.errorEmitted=!0),U&&(U.errorEmitted=!0),T.emit("error",L))}function _(){let T=this._readableState,L=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),L&&(L.constructed=!0,L.destroyed=!1,L.closed=!1,L.closeEmitted=!1,L.errored=null,L.errorEmitted=!1,L.finalCalled=!1,L.prefinished=!1,L.ended=L.writable===!1,L.ending=L.writable===!1,L.finished=L.writable===!1)}function x(T,L,U){let D=T._readableState,oe=T._writableState;if(oe!=null&&oe.destroyed||D!=null&&D.destroyed)return this;D!=null&&D.autoDestroy||oe!=null&&oe.autoDestroy?T.destroy(L):L&&(L.stack,oe&&!oe.errored&&(oe.errored=L),D&&!D.errored&&(D.errored=L),U?t.nextTick(m,T,L):m(T,L))}function v(T,L){if(typeof T._construct!="function")return;let U=T._readableState,D=T._writableState;U&&(U.constructed=!1),D&&(D.constructed=!1),T.once(p,L),!(T.listenerCount(p)>1)&&t.nextTick(S,T)}function S(T){let L=!1;function U(D){if(L){x(T,D??new o);return}L=!0;let oe=T._readableState,z=T._writableState,H=z||oe;oe&&(oe.constructed=!0),z&&(z.constructed=!0),H.destroyed?T.emit(d,D):D?x(T,D,!0):t.nextTick(E,T)}try{T._construct(D=>{t.nextTick(U,D)})}catch(D){t.nextTick(U,D)}}function E(T){T.emit(p)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,L){T.emit("error",L),t.nextTick(P,T)}function B(T,L){!T||l(T)||(!L&&!c(T)&&(L=new n),u(T)?(T.socket=null,T.destroy(L)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(L):typeof T.close=="function"?T.close():L?t.nextTick(O,T,L):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:B,destroy:f,undestroy:_,errorOrDestroy:x}}),vo=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=De(),{EventEmitter:o}=(Ut(),Re(Tt));function n(a){o.call(this,a)}r(n.prototype,o.prototype),r(n,o),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 b(w){y(),o.listenerCount(this,"error")===0&&this.emit("error",w)}s(c,"error",b),s(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",b),a.removeListener("error",b),c.removeListener("end",y),c.removeListener("close",y),a.removeListener("close",y)}return c.on("end",y),c.on("close",y),a.on("close",y),a.emit("pipe",c),a};function s(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:s}}),Gr=pe((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=De(),{AbortError:r,codes:o}=Ke(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=bt(),l=Ct(),{ERR_INVALID_ARG_TYPE:c}=o,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)&&!s(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||Ye().addAbortListener;let b=u(p,f);l(g,b[t])}return g}}),eu=pe((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=De(),{Buffer:s}=($e(),Re(Fe)),{inspect:a}=Ye();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 s.alloc(0);let c=s.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)o(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=s.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)o(c,g,u-l),l-=g.length;else{l===g.length?(o(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(o(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})}}}),Yr=pe((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=De(),{validateInteger:o}=dr(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,s=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:s}function u(p,g){o(g,"value",0),p?a=g:s=g}function d(p,g,f,b){let y=l(g,b,f);if(y!=null){if(!r(y)||y<0){let w=b?`options.${f}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),tu=pe((i,e)=>{le(),ue(),ce();var t=($e(),Re(Fe)),r=t.Buffer;function o(s,a){for(var l in s)a[l]=s[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(o(t,i),i.Buffer=n);function n(s,a,l){return r(s,a,l)}n.prototype=Object.create(r.prototype),o(r,n),n.from=function(s,a,l){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,l)},n.alloc=function(s,a,l){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},n.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}}),ru=pe(i=>{le(),ue(),ce();var e=tu().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 _;;)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(_)return;m=(""+m).toLowerCase(),_=!0}}function o(m){var _=r(m);if(typeof _!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return _||m}i.StringDecoder=n;function n(m){this.encoding=o(m);var _;switch(this.encoding){case"utf16le":this.text=p,this.end=g,_=4;break;case"utf8":this.fillLast=c,_=4;break;case"base64":this.text=f,this.end=b,_=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(_)}n.prototype.write=function(m){if(m.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(m),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?_?_+this.text(m,x):this.text(m,x):_||""},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 s(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,_,x){var v=_.length-1;if(v<x)return 0;var S=s(_[v]);return S>=0?(S>0&&(m.lastNeed=S-1),S):--v<x||S===-2?0:(S=s(_[v]),S>=0?(S>0&&(m.lastNeed=S-2),S):--v<x||S===-2?0:(S=s(_[v]),S>=0?(S>0&&(S===2?S=0:m.lastNeed=S-3),S):0))}function l(m,_,x){if((_[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&_.length>2&&(_[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var _=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,_,0,m.length),this.lastNeed-=m.length}function u(m,_){var x=a(this,m,_);if(!this.lastNeed)return m.toString("utf8",_);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",_,v)}function d(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+"�":_}function p(m,_){if((m.length-_)%2===0){var x=m.toString("utf16le",_);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",_,m.length-1)}function g(m){var _=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function f(m,_){var x=(m.length-_)%3;return x===0?m.toString("base64",_):(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",_,m.length-x))}function b(m){var _=m&&m.length?this.write(m):"";return this.lastNeed?_+this.lastChar.toString("base64",0,3-this.lastNeed):_}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),Pa=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=De(),{Buffer:s}=($e(),Re(Fe)),{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 s)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[o])f=!0,g=d[o]();else if(d&&d[n])f=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(_,x){r(w(_),()=>t.nextTick(x,_),v=>t.nextTick(x,v||_))};async function w(_){let x=_!=null,v=typeof g.throw=="function";if(x&&v){let{value:S,done:E}=await g.throw(_);if(await S,E)return}if(typeof g.return=="function"){let{value:S}=await g.return();await S}}async function m(){for(;;){try{let{value:_,done:x}=f?await g.next():g.next();if(x)b.push(null);else{let v=_&&typeof _.then=="function"?await _:_;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(_){b.destroy(_)}break}}return b}e.exports=c}),Jr=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:s,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:b}=(Ut(),Re(Tt)),{Stream:y,prependListener:w}=vo(),{Buffer:m}=($e(),Re(Fe)),{addAbortSignal:_}=Gr(),x=Ct(),v=Ye().debuglog("stream",C=>{v=C}),S=eu(),E=Yt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=Yr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:L,ERR_STREAM_PUSH_AFTER_EOF:U,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:oe}=Ke(),{validateObject:z}=dr(),H=f("kPaused"),{StringDecoder:te}=ru(),F=Pa();c(ae.prototype,y.prototype),c(ae,y);var X=()=>{},{errorOrDestroy:M}=E,J=1,be=2,re=4,we=8,G=16,j=32,ne=64,V=128,Y=256,Q=512,ge=1024,se=2048,R=4096,q=8192,ee=16384,he=32768,fe=65536,ye=1<<17,W=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(N){N?this.state|=C:this.state&=~C}}}a(ve.prototype,{objectMode:me(J),ended:me(be),endEmitted:me(re),reading:me(we),constructed:me(G),sync:me(j),needReadable:me(ne),emittedReadable:me(V),readableListening:me(Y),resumeScheduled:me(Q),errorEmitted:me(ge),emitClose:me(se),autoDestroy:me(R),destroyed:me(q),closed:me(ee),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(ye),dataEmitted:me(W)});function ve(C,N,_e){typeof _e!="boolean"&&(_e=N instanceof mt()),this.state=se|R|G|j,C&&C.objectMode&&(this.state|=J),_e&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",_e):P(!1),this.buffer=new S,this.length=0,this.pipes=[],this.flowing=null,this[H]=null,C&&C.emitClose===!1&&(this.state&=~se),C&&C.autoDestroy===!1&&(this.state&=~R),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new te(C.encoding),this.encoding=C.encoding)}function ae(C){if(!(this instanceof ae))return new ae(C);let N=this instanceof mt();this._readableState=new ve(C,this,N),C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy),typeof C.construct=="function"&&(this._construct=C.construct),C.signal&&!N&&_(C.signal,this)),y.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&K(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(C,N){N(C)},ae.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},ae.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new oe,this.destroy(C)),new u((N,_e)=>x(this,Se=>Se&&Se!==C?_e(Se):N(null)))},ae.prototype.push=function(C,N){return Oe(this,C,N,!1)},ae.prototype.unshift=function(C,N){return Oe(this,C,N,!0)};function Oe(C,N,_e,Se){v("readableAddChunk",N);let Ae=C._readableState,Be;if((Ae.state&J)===0&&(typeof N=="string"?(_e=_e||Ae.defaultEncoding,Ae.encoding!==_e&&(Se&&Ae.encoding?N=m.from(N,_e).toString(Ae.encoding):(N=m.from(N,_e),_e=""))):N instanceof m?_e="":y._isUint8Array(N)?(N=y._uint8ArrayToBuffer(N),_e=""):N!=null&&(Be=new B("chunk",["string","Buffer","Uint8Array"],N))),Be)M(C,Be);else if(N===null)Ae.state&=~we,Z(C,Ae);else if((Ae.state&J)!==0||N&&N.length>0)if(Se)if((Ae.state&re)!==0)M(C,new D);else{if(Ae.destroyed||Ae.errored)return!1;h(C,Ae,N,!0)}else if(Ae.ended)M(C,new U);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~we,Ae.decoder&&!_e?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?h(C,Ae,N,!1):K(C,Ae)):h(C,Ae,N,!1)}else Se||(Ae.state&=~we,K(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function h(C,N,_e,Se){N.flowing&&N.length===0&&!N.sync&&C.listenerCount("data")>0?((N.state&fe)!==0?N.awaitDrainWriters.clear():N.awaitDrainWriters=null,N.dataEmitted=!0,C.emit("data",_e)):(N.length+=N.objectMode?1:_e.length,Se?N.buffer.unshift(_e):N.buffer.push(_e),(N.state&ne)!==0&&de(C)),K(C,N)}ae.prototype.isPaused=function(){let C=this._readableState;return C[H]===!0||C.flowing===!1},ae.prototype.setEncoding=function(C){let N=new te(C);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let _e=this._readableState.buffer,Se="";for(let Ae of _e)Se+=N.write(Ae);return _e.clear(),Se!==""&&_e.push(Se),this._readableState.length=Se.length,this};var k=1073741824;function A(C){if(C>k)throw new L("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function $(C,N){return C<=0||N.length===0&&N.ended?0:(N.state&J)!==0?1:n(C)?N.flowing&&N.length?N.buffer.first().length:N.length:C<=N.length?C:N.ended?N.length:0}ae.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=s(C,10));let N=this._readableState,_e=C;if(C>N.highWaterMark&&(N.highWaterMark=A(C)),C!==0&&(N.state&=~V),C===0&&N.needReadable&&((N.highWaterMark!==0?N.length>=N.highWaterMark:N.length>0)||N.ended))return v("read: emitReadable",N.length,N.ended),N.length===0&&N.ended?ot(this):de(this),null;if(C=$(C,N),C===0&&N.ended)return N.length===0&&ot(this),null;let Se=(N.state&ne)!==0;if(v("need readable",Se),(N.length===0||N.length-C<N.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),N.state|=we|j,N.length===0&&(N.state|=ne);try{this._read(N.highWaterMark)}catch(Be){M(this,Be)}N.state&=~j,N.reading||(C=$(_e,N))}let Ae;return C>0?Ae=Ft(C,N):Ae=null,Ae===null?(N.needReadable=N.length<=N.highWaterMark,C=0):(N.length-=C,N.multiAwaitDrain?N.awaitDrainWriters.clear():N.awaitDrainWriters=null),N.length===0&&(N.ended||(N.needReadable=!0),_e!==C&&N.ended&&ot(this)),Ae!==null&&!N.errorEmitted&&!N.closeEmitted&&(N.dataEmitted=!0,this.emit("data",Ae)),Ae};function Z(C,N){if(v("onEofChunk"),!N.ended){if(N.decoder){let _e=N.decoder.end();_e&&_e.length&&(N.buffer.push(_e),N.length+=N.objectMode?1:_e.length)}N.ended=!0,N.sync?de(C):(N.needReadable=!1,N.emittedReadable=!0,ke(C))}}function de(C){let N=C._readableState;v("emitReadable",N.needReadable,N.emittedReadable),N.needReadable=!1,N.emittedReadable||(v("emitReadable",N.flowing),N.emittedReadable=!0,t.nextTick(ke,C))}function ke(C){let N=C._readableState;v("emitReadable_",N.destroyed,N.length,N.ended),!N.destroyed&&!N.errored&&(N.length||N.ended)&&(C.emit("readable"),N.emittedReadable=!1),N.needReadable=!N.flowing&&!N.ended&&N.length<=N.highWaterMark,nt(C)}function K(C,N){!N.readingMore&&N.constructed&&(N.readingMore=!0,t.nextTick(ie,C,N))}function ie(C,N){for(;!N.reading&&!N.ended&&(N.length<N.highWaterMark||N.flowing&&N.length===0);){let _e=N.length;if(v("maybeReadMore read 0"),C.read(0),_e===N.length)break}N.readingMore=!1}ae.prototype._read=function(C){throw new T("_read()")},ae.prototype.pipe=function(C,N){let _e=this,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,N);let Ae=(!N||N.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ve:Ot;Se.endEmitted?t.nextTick(Ae):_e.once("end",Ae),C.on("unpipe",Be);function Be(at,ut){v("onunpipe"),at===_e&&ut&&ut.hasUnpiped===!1&&(ut.hasUnpiped=!0,er())}function Ve(){v("onend"),C.end()}let Ze,Zt=!1;function er(){v("cleanup"),C.removeListener("close",st),C.removeListener("finish",_t),Ze&&C.removeListener("drain",Ze),C.removeListener("error",Pt),C.removeListener("unpipe",Be),_e.removeListener("end",Ve),_e.removeListener("end",Ot),_e.removeListener("data",pr),Zt=!0,Ze&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&Ze()}function tr(){Zt||(Se.pipes.length===1&&Se.pipes[0]===C?(v("false write response, pause",0),Se.awaitDrainWriters=C,Se.multiAwaitDrain=!1):Se.pipes.length>1&&Se.pipes.includes(C)&&(v("false write response, pause",Se.awaitDrainWriters.size),Se.awaitDrainWriters.add(C)),_e.pause()),Ze||(Ze=Ie(_e,C),C.on("drain",Ze))}_e.on("data",pr);function pr(at){v("ondata");let ut=C.write(at);v("dest.write",ut),ut===!1&&tr()}function Pt(at){if(v("onerror",at),Ot(),C.removeListener("error",Pt),C.listenerCount("error")===0){let ut=C._writableState||C._readableState;ut&&!ut.errorEmitted?M(C,at):C.emit("error",at)}}w(C,"error",Pt);function st(){C.removeListener("finish",_t),Ot()}C.once("close",st);function _t(){v("onfinish"),C.removeListener("close",st),Ot()}C.once("finish",_t);function Ot(){v("unpipe"),_e.unpipe(C)}return C.emit("pipe",_e),C.writableNeedDrain===!0?tr():Se.flowing||(v("pipe resume"),_e.resume()),C};function Ie(C,N){return function(){let _e=C._readableState;_e.awaitDrainWriters===N?(v("pipeOnDrain",1),_e.awaitDrainWriters=null):_e.multiAwaitDrain&&(v("pipeOnDrain",_e.awaitDrainWriters.size),_e.awaitDrainWriters.delete(N)),(!_e.awaitDrainWriters||_e.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}ae.prototype.unpipe=function(C){let N=this._readableState,_e={hasUnpiped:!1};if(N.pipes.length===0)return this;if(!C){let Ae=N.pipes;N.pipes=[],this.pause();for(let Be=0;Be<Ae.length;Be++)Ae[Be].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(N.pipes,C);return Se===-1?this:(N.pipes.splice(Se,1),N.pipes.length===0&&this.pause(),C.emit("unpipe",this,_e),this)},ae.prototype.on=function(C,N){let _e=y.prototype.on.call(this,C,N),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?de(this):Se.reading||t.nextTick(Pe,this)),_e},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,N){let _e=y.prototype.removeListener.call(this,C,N);return C==="readable"&&t.nextTick(Te,this),_e},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(C){let N=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Te,this),N};function Te(C){let N=C._readableState;N.readableListening=C.listenerCount("readable")>0,N.resumeScheduled&&N[H]===!1?N.flowing=!0:C.listenerCount("data")>0?C.resume():N.readableListening||(N.flowing=null)}function Pe(C){v("readable nexttick read 0"),C.read(0)}ae.prototype.resume=function(){let C=this._readableState;return C.flowing||(v("resume"),C.flowing=!C.readableListening,Me(this,C)),C[H]=!1,this};function Me(C,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(rt,C,N))}function rt(C,N){v("resume",N.reading),N.reading||C.read(0),N.resumeScheduled=!1,C.emit("resume"),nt(C),N.flowing&&!N.reading&&C.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[H]=!0,this};function nt(C){let N=C._readableState;for(v("flow",N.flowing);N.flowing&&C.read()!==null;);}ae.prototype.wrap=function(C){let N=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(N=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{M(this,Se)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{N&&C.resume&&(N=!1,C.resume())};let _e=l(C);for(let Se=1;Se<_e.length;Se++){let Ae=_e[Se];this[Ae]===void 0&&typeof C[Ae]=="function"&&(this[Ae]=C[Ae].bind(C))}return this},ae.prototype[g]=function(){return qe(this)},ae.prototype.iterator=function(C){return C!==void 0&&z(C,"options"),qe(this,C)};function qe(C,N){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let _e=it(C,N);return _e.stream=C,_e}async function*it(C,N){let _e=X;function Se(Ve){this===C?(_e(),_e=X):_e=Ve}C.on("readable",Se);let Ae,Be=x(C,{writable:!1},Ve=>{Ae=Ve?O(Ae,Ve):null,_e(),_e=X});try{for(;;){let Ve=C.destroyed?null:C.read();if(Ve!==null)yield Ve;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Ve){throw Ae=O(Ae,Ve),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",Se),Be())}}a(ae.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(ve.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[H]!==!1},set(C){this[H]=!!C}}}),ae._fromList=Ft;function Ft(C,N){if(N.length===0)return null;let _e;return N.objectMode?_e=N.buffer.shift():!C||C>=N.length?(N.decoder?_e=N.buffer.join(""):N.buffer.length===1?_e=N.buffer.first():_e=N.buffer.concat(N.length),N.buffer.clear()):_e=N.buffer.consume(C,N.decoder),_e}function ot(C){let N=C._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(Qe,N,C))}function Qe(C,N){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,N.emit("end"),N.writable&&N.allowHalfOpen===!1)t.nextTick(fr,N);else if(C.autoDestroy){let _e=N._writableState;(!_e||_e.autoDestroy&&(_e.finished||_e.writable===!1))&&N.destroy()}}}function fr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,N){return F(ae,C,N)};var $t;function Xt(){return $t===void 0&&($t={}),$t}ae.fromWeb=function(C,N){return Xt().newStreamReadableFromReadableStream(C,N)},ae.toWeb=function(C,N){return Xt().newReadableStreamFromStreamReadable(C,N)},ae.wrap=function(C,N){var _e,Se;return new ae({objectMode:(_e=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&_e!==void 0?_e:!0,...N,destroy(Ae,Be){E.destroyer(C,Ae),Be(Ae)}}).wrap(C)}}),wo=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=De();e.exports=z,z.WritableState=D;var{EventEmitter:p}=(Ut(),Re(Tt)),g=vo().Stream,{Buffer:f}=($e(),Re(Fe)),b=Yt(),{addAbortSignal:y}=Gr(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Yr(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:S,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:B}=Ke().codes,{errorOrDestroy:T}=b;l(z.prototype,g.prototype),l(z,g);function L(){}var U=u("kOnFinished");function D(R,q,ee){typeof ee!="boolean"&&(ee=q instanceof mt()),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[U]=[]}function oe(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}D.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},s(D.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function z(R){let q=this instanceof mt();if(!q&&!n(z,this))return new z(R);this._writableState=new D(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&&y(R.signal,this)),g.call(this,R),b.construct(this,()=>{let ee=this._writableState;ee.writing||we(this,ee),V(this,ee)})}s(z,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==z?!1:R&&R._writableState instanceof D}}),z.prototype.pipe=function(){T(this,new S)};function H(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 B(ee);typeof he!="function"&&(he=L)}if(q===null)throw new P;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 _("chunk",["string","Buffer","Uint8Array"],q);let ye;return fe.ending?ye=new O:fe.destroyed&&(ye=new E("write")),ye?(t.nextTick(he,ye),T(R,ye,!0),ye):(fe.pendingcb++,te(R,fe,q,ee,he))}z.prototype.write=function(R,q,ee){return H(this,R,q,ee)===!0},z.prototype.cork=function(){this._writableState.corked++},z.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},z.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=c(R)),!f.isEncoding(R))throw new B(R);return this._writableState.defaultEncoding=R,this};function te(R,q,ee,he,fe){let ye=q.objectMode?1:ee.length;q.length+=ye;let W=q.length<q.highWaterMark;return W||(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!==L&&(q.allNoop=!1)):(q.writelen=ye,q.writecb=fe,q.writing=!0,q.sync=!0,R._write(ee,he,q.onwrite),q.sync=!1),W&&!q.errored&&!q.destroyed}function F(R,q,ee,he,fe,ye,W){q.writelen=he,q.writecb=W,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new E("write")):ee?R._writev(fe,q.onwrite):R._write(fe,ye,q.onwrite),q.sync=!1}function X(R,q,ee,he){--q.pendingcb,he(ee),re(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(X,R,ee,q,fe):X(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(J,ee.afterWriteTickInfo)):be(R,ee,1,fe))}function J({stream:R,state:q,count:ee,cb:he}){return q.afterWriteTickInfo=null,be(R,q,ee,he)}function be(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&&re(q),V(R,q)}function re(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var q;let{chunk:ye,callback:W}=R.buffered[fe],me=R.objectMode?1:ye.length;R.length-=me,W((q=R.errored)!==null&&q!==void 0?q:new E("write"))}let ee=R[U].splice(0);for(let fe=0;fe<ee.length;fe++){var he;ee[fe]((he=R.errored)!==null&&he!==void 0?he:new E("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,ye=ee.length-he;if(!ye)return;let W=he;if(q.bufferProcessing=!0,ye>1&&R._writev){q.pendingcb-=ye-1;let me=q.allNoop?L:ae=>{for(let Oe=W;Oe<ee.length;++Oe)ee[Oe].callback(ae)},ve=q.allNoop&&W===0?ee:r(ee,W);ve.allBuffers=q.allBuffers,F(R,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=ee[W];ee[W++]=null;let Oe=fe?1:me.length;F(R,q,!1,Oe,me,ve,ae)}while(W<ee.length&&!q.writing);W===ee.length?oe(q):W>256?(ee.splice(0,W),q.bufferedIndex=0):q.bufferedIndex=W}q.bufferProcessing=!1}z.prototype._write=function(R,q,ee){if(this._writev)this._writev([{chunk:R,encoding:q}],ee);else throw new x("_write()")},z.prototype._writev=null,z.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 ye=H(this,R,q);ye instanceof o&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,V(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[U].push(ee)),this};function G(R){return R.ending&&!R.destroyed&&R.constructed&&R.length===0&&!R.errored&&R.buffered.length===0&&!R.finished&&!R.writing&&!R.errorEmitted&&!R.closeEmitted}function j(R,q){let ee=!1;function he(fe){if(ee){T(R,fe??v());return}if(ee=!0,q.pendingcb--,fe){let ye=q[U].splice(0);for(let W=0;W<ye.length;W++)ye[W](fe);T(R,fe,q.sync)}else G(q)&&(q.prefinished=!0,R.emit("prefinish"),q.pendingcb++,t.nextTick(Y,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,j(R,q)):(q.prefinished=!0,R.emit("prefinish")))}function V(R,q,ee){G(q)&&(ne(R,q),q.pendingcb===0&&(ee?(q.pendingcb++,t.nextTick((he,fe)=>{G(fe)?Y(he,fe):fe.pendingcb--},R,q)):G(q)&&(q.pendingcb++,Y(R,q))))}function Y(R,q){q.pendingcb--,q.finished=!0;let ee=q[U].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(z.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Q=b.destroy;z.prototype.destroy=function(R,q){let ee=this._writableState;return!ee.destroyed&&(ee.bufferedIndex<ee.buffered.length||ee[U].length)&&t.nextTick(re,ee),Q.call(this,R,q),this},z.prototype._undestroy=b.undestroy,z.prototype._destroy=function(R,q){q(R)},z.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ge;function se(){return ge===void 0&&(ge={}),ge}z.fromWeb=function(R,q){return se().newStreamWritableFromWritableStream(R,q)},z.toWeb=function(R){return se().newWritableStreamFromStreamWritable(R)}}),nu=pe((i,e)=>{le(),ue(),ce();var t=Dt(),r=($e(),Re(Fe)),{isReadable:o,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=bt(),g=Ct(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ke(),{destroyer:w}=Yt(),m=mt(),_=Jr(),x=wo(),{createDeferredPromise:v}=Ye(),S=Pa(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(U){return U instanceof E}:function(U){return!1},P=globalThis.AbortController||cr().AbortController,{FunctionPrototypeCall:O}=De(),B=class extends m{constructor(U){super(U),U?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),U?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function U(D,oe){if(u(D))return D;if(l(D))return L({readable:D});if(c(D))return L({writable:D});if(a(D))return L({writable:!1,readable:!1});if(d(D))return L({readable:_.fromWeb(D)});if(p(D))return L({writable:x.fromWeb(D)});if(typeof D=="function"){let{value:H,write:te,final:F,destroy:X}=T(D);if(s(H))return S(B,H,{objectMode:!0,write:te,final:F,destroy:X});let M=H?.then;if(typeof M=="function"){let J,be=O(M,H,re=>{if(re!=null)throw new y("nully","body",re)},re=>{w(J,re)});return J=new B({objectMode:!0,readable:!1,write:te,final(re){F(async()=>{try{await be,t.nextTick(re,null)}catch(we){t.nextTick(re,we)}})},destroy:X})}throw new y("Iterable, AsyncIterable or AsyncFunction",oe,H)}if(I(D))return U(D.arrayBuffer());if(s(D))return S(B,D,{objectMode:!0,writable:!1});if(d(D?.readable)&&p(D?.writable))return B.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){let H=D!=null&&D.readable?l(D?.readable)?D?.readable:U(D.readable):void 0,te=D!=null&&D.writable?c(D?.writable)?D?.writable:U(D.writable):void 0;return L({readable:H,writable:te})}let z=D?.then;if(typeof z=="function"){let H;return O(z,D,te=>{te!=null&&H.push(te),H.push(null)},te=>{w(H,te)}),H=new B({objectMode:!0,writable:!1,read(){}})}throw new b(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function T(U){let{promise:D,resolve:oe}=v(),z=new P,H=z.signal;return{value:U((async function*(){for(;;){let te=D;D=null;let{chunk:F,done:X,cb:M}=await te;if(t.nextTick(M),X)return;if(H.aborted)throw new f(void 0,{cause:H.reason});({promise:D,resolve:oe}=v()),yield F}})(),{signal:H}),write(te,F,X){let M=oe;oe=null,M({chunk:te,done:!1,cb:X})},final(te){let F=oe;oe=null,F({done:!0,cb:te})},destroy(te,F){z.abort(),F(te)}}}function L(U){let D=U.readable&&typeof U.readable.read!="function"?_.wrap(U.readable):U.readable,oe=U.writable,z=!!o(D),H=!!n(oe),te,F,X,M,J;function be(re){let we=M;M=null,we?we(re):re&&J.destroy(re)}return J=new B({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:z,writable:H}),H&&(g(oe,re=>{H=!1,re&&w(D,re),be(re)}),J._write=function(re,we,G){oe.write(re,we)?G():te=G},J._final=function(re){oe.end(),F=re},oe.on("drain",function(){if(te){let re=te;te=null,re()}}),oe.on("finish",function(){if(F){let re=F;F=null,re()}})),z&&(g(D,re=>{z=!1,re&&w(D,re),be(re)}),D.on("readable",function(){if(X){let re=X;X=null,re()}}),D.on("end",function(){J.push(null)}),J._read=function(){for(;;){let re=D.read();if(re===null){X=J._read;return}if(!J.push(re))return}}),J._destroy=function(re,we){!re&&M!==null&&(re=new f),X=null,te=null,F=null,M===null?we(re):(M=we,w(oe,re),w(D,re))},J}}),mt=pe((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=De();e.exports=l;var s=Jr(),a=wo();n(l.prototype,s.prototype),n(l,s);{let p=o(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);s.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=nu()),d(p,"body")}}),Oa=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=De();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ke().codes,n=mt(),{getHighWaterMark:s}=Yr();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?s(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 o("_transform()")},l.prototype._write=function(d,p,g){let f=this._readableState,b=this._writableState,y=f.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===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()}}}),Ma=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=De();e.exports=o;var r=Oa();t(o.prototype,r.prototype),t(o,r);function o(n){if(!(this instanceof o))return new o(n);r.call(this,n)}o.prototype._transform=function(n,s,a){a(null,n)}}),_o=pe((i,e)=>{le(),ue(),ce();var t=Dt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:s}=De(),a=Ct(),{once:l}=Ye(),c=Yt(),u=mt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:_}=dr(),{isIterable:x,isReadable:v,isReadableNodeStream:S,isNodeStream:E,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:B}=bt(),T=globalThis.AbortController||cr().AbortController,L,U,D;function oe(re,we,G){let j=!1;re.on("close",()=>{j=!0});let ne=a(re,{readable:we,writable:G},V=>{j=!V});return{destroy:V=>{j||(j=!0,c.destroyer(re,V||new b("pipe")))},cleanup:ne}}function z(re){return m(re[re.length-1],"streams[stream.length - 1]"),re.pop()}function H(re){if(x(re))return re;if(S(re))return te(re);throw new p("val",["Readable","Iterable","AsyncIterable"],re)}async function*te(re){U||(U=Jr()),yield*U.prototype[n].call(re)}async function F(re,we,G,{end:j}){let ne,V=null,Y=se=>{if(se&&(ne=se),V){let R=V;V=null,R()}},Q=()=>new o((se,R)=>{ne?R(ne):V=()=>{ne?R(ne):se()}});we.on("drain",Y);let ge=a(we,{readable:!1},Y);try{we.writableNeedDrain&&await Q();for await(let se of re)we.write(se)||await Q();j&&(we.end(),await Q()),G()}catch(se){G(ne!==se?d(ne,se):se)}finally{ge(),we.off("drain",Y)}}async function X(re,we,G,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let V of re)await ne.ready,ne.write(V).catch(()=>{});await ne.ready,j&&await ne.close(),G()}catch(V){try{await ne.abort(V),G(V)}catch(Y){G(Y)}}}function M(...re){return J(re,l(z(re)))}function J(re,we,G){if(re.length===1&&r(re[0])&&(re=re[0]),re.length<2)throw new f("streams");let j=new T,ne=j.signal,V=G?.signal,Y=[];_(V,"options.signal");function Q(){fe(new w)}D=D||Ye().addAbortListener;let ge;V&&(ge=D(V,Q));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[s](),j.abort(),ae&&(se||Y.forEach(h=>h()),t.nextTick(we,se,R))}}let ye;for(let ve=0;ve<re.length;ve++){let ae=re[ve],Oe=ve<re.length-1,h=ve>0,k=Oe||G?.end!==!1,A=ve===re.length-1;if(E(ae)){let $=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(Z)};if(k){let{destroy:Z,cleanup:de}=oe(ae,Oe,h);q.push(Z),v(ae)&&A&&Y.push(de)}ae.on("error",$),v(ae)&&A&&Y.push(()=>{ae.removeListener("error",$)})}if(ve===0)if(typeof ae=="function"){if(ye=ae({signal:ne}),!x(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else x(ae)||S(ae)||I(ae)?ye=ae:ye=u.from(ae);else if(typeof ae=="function"){if(I(ye)){var W;ye=H((W=ye)===null||W===void 0?void 0:W.readable)}else ye=H(ye);if(ye=ae(ye,{signal:ne}),Oe){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;L||(L=Ma());let $=new L({objectMode:!0}),Z=(me=ye)===null||me===void 0?void 0:me.then;if(typeof Z=="function")ee++,Z.call(ye,K=>{R=K,K!=null&&$.write(K),k&&$.end(),t.nextTick(he)},K=>{$.destroy(K),t.nextTick(he,K)});else if(x(ye,!0))ee++,F(ye,$,he,{end:k});else if(O(ye)||I(ye)){let K=ye.readable||ye;ee++,F(K,$,he,{end:k})}else throw new g("AsyncIterable or Promise","destination",ye);ye=$;let{destroy:de,cleanup:ke}=oe(ye,!1,!0);q.push(de),A&&Y.push(ke)}}else if(E(ae)){if(S(ye)){ee+=2;let $=be(ye,ae,he,{end:k});v(ae)&&A&&Y.push($)}else if(I(ye)||O(ye)){let $=ye.readable||ye;ee++,F($,ae,he,{end:k})}else if(x(ye))ee++,F(ye,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(P(ae)){if(S(ye))ee++,X(H(ye),ae,he,{end:k});else if(O(ye)||x(ye))ee++,X(ye,ae,he,{end:k});else if(I(ye))ee++,X(ye.readable,ae,he,{end:k});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ne!=null&&ne.aborted||V!=null&&V.aborted)&&t.nextTick(Q),ye}function be(re,we,G,{end:j}){let ne=!1;if(we.on("close",()=>{ne||G(new y)}),re.pipe(we,{end:!1}),j){let V=function(){ne=!0,we.end()};B(re)?t.nextTick(V):re.once("end",V)}else G();return a(re,{readable:!0,writable:!1},V=>{let Y=re._readableState;V&&V.code==="ERR_STREAM_PREMATURE_CLOSE"&&Y&&Y.ended&&!Y.errored&&!Y.errorEmitted?re.once("end",G).once("error",G):G(V)}),a(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:M}}),La=pe((i,e)=>{le(),ue(),ce();var{pipeline:t}=_o(),r=mt(),{destroyer:o}=Yt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=bt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ke(),b=Ct();e.exports=function(...y){if(y.length===0)throw new f("streams");if(y.length===1)return r.from(y[0]);let w=[...y];if(typeof y[0]=="function"&&(y[0]=r.from(y[0])),typeof y[y.length-1]=="function"){let T=y.length-1;y[T]=r.from(y[T])}for(let T=0;T<y.length;++T)if(!(!n(y[T])&&!l(y[T]))){if(T<y.length-1&&!(s(y[T])||d(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(y[T])||u(y[T])||c(y[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,_,x,v,S;function E(T){let L=v;v=null,L?L(T):T?S.destroy(T):!B&&!O&&S.destroy()}let I=y[0],P=t(y,E),O=!!(a(I)||u(I)||c(I)),B=!!(s(P)||d(P)||c(P));if(S=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:B}),O){if(n(I))S._write=function(L,U,D){I.write(L,U)?D():m=D},S._final=function(L){I.end(),_=L},I.on("drain",function(){if(m){let L=m;m=null,L()}});else if(l(I)){let L=(c(I)?I.writable:I).getWriter();S._write=async function(U,D,oe){try{await L.ready,L.write(U).catch(()=>{}),oe()}catch(z){oe(z)}},S._final=async function(U){try{await L.ready,L.close().catch(()=>{}),_=U}catch(D){U(D)}}}let T=c(P)?P.readable:P;b(T,()=>{if(_){let L=_;_=null,L()}})}if(B){if(n(P))P.on("readable",function(){if(x){let T=x;x=null,T()}}),P.on("end",function(){S.push(null)}),S._read=function(){for(;;){let T=P.read();if(T===null){x=S._read;return}if(!S.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();S._read=async function(){for(;;)try{let{value:L,done:U}=await T.read();if(!S.push(L))return;if(U){S.push(null);return}}catch{return}}}}return S._destroy=function(T,L){!T&&v!==null&&(T=new p),x=null,m=null,_=null,v===null?L(T):(v=L,n(P)&&o(P,T))},S}}),iu=pe((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||cr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=dr(),d=De().Symbol("kWeak"),p=De().Symbol("kResistStopPropagation"),{finished:g}=Ct(),f=La(),{addAbortSignalNoValidate:b}=Gr(),{isWritable:y,isNodeStream:w}=bt(),{deprecate:m}=Ye(),{ArrayPrototypePush:_,Boolean:x,MathFloor:v,Number:S,NumberIsNaN:E,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=De(),L=T("kEmpty"),U=T("kEof");function D(V,Y){if(Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),w(V)&&!y(V))throw new r("stream",V,"must be writable");let Q=f(this,V);return Y!=null&&Y.signal&&b(Y.signal,Q),Q}function oe(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal");let Q=1;Y?.concurrency!=null&&(Q=v(Y.concurrency));let ge=Q-1;return Y?.highWaterMark!=null&&(ge=v(Y.highWaterMark)),c(Q,"options.concurrency",1),c(ge,"options.highWaterMark",0),ge+=Q,(async function*(){let se=Ye().AbortSignalAny([Y?.signal].filter(x)),R=this,q=[],ee={signal:se},he,fe,ye=!1,W=0;function me(){ye=!0,ve()}function ve(){W-=1,ae()}function ae(){fe&&!ye&&W<Q&&q.length<ge&&(fe(),fe=null)}async function Oe(){try{for await(let h of R){if(ye)return;if(se.aborted)throw new a;try{if(h=V(h,ee),h===L)continue;h=O(h)}catch(k){h=P(k)}W+=1,B(h,ve,me),q.push(h),he&&(he(),he=null),!ye&&(q.length>=ge||W>=Q)&&await new I(k=>{fe=k})}q.push(U)}catch(h){let k=P(h);B(k,ve,me),q.push(k)}finally{ye=!0,he&&(he(),he=null)}}Oe();try{for(;;){for(;q.length>0;){let h=await q[0];if(h===U)return;if(se.aborted)throw new a;h!==L&&(yield h),q.shift(),ae()}await new I(h=>{he=h})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function z(V=void 0){return V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal"),(async function*(){let Y=0;for await(let ge of this){var Q;if(V!=null&&(Q=V.signal)!==null&&Q!==void 0&&Q.aborted)throw new a({cause:V.signal.reason});yield[Y++,ge]}}).call(this)}async function H(V,Y=void 0){for await(let Q of M.call(this,V,Y))return!0;return!1}async function te(V,Y=void 0){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);return!await H.call(this,async(...Q)=>!await V(...Q),Y)}async function F(V,Y){for await(let Q of M.call(this,V,Y))return Q}async function X(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function Q(ge,se){return await V(ge,se),L}for await(let ge of oe.call(this,Q,Y));}function M(V,Y){if(typeof V!="function")throw new o("fn",["Function","AsyncFunction"],V);async function Q(ge,se){return await V(ge,se)?ge:L}return oe.call(this,Q,Y)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function be(V,Y,Q){var ge;if(typeof V!="function")throw new o("reducer",["Function","AsyncFunction"],V);Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal");let se=arguments.length>1;if(Q!=null&&(ge=Q.signal)!==null&&ge!==void 0&&ge.aborted){let fe=new a(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let R=new t,q=R.signal;if(Q!=null&&Q.signal){let fe={once:!0,[d]:this,[p]:!0};Q.signal.addEventListener("abort",()=>R.abort(),fe)}let ee=!1;try{for await(let fe of this){var he;if(ee=!0,Q!=null&&(he=Q.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?Y=await V(Y,fe,{signal:q}):(Y=fe,se=!0)}if(!ee&&!se)throw new J}finally{R.abort()}return Y}async function re(V){V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal");let Y=[];for await(let ge of this){var Q;if(V!=null&&(Q=V.signal)!==null&&Q!==void 0&&Q.aborted)throw new a(void 0,{cause:V.signal.reason});_(Y,ge)}return Y}function we(V,Y){let Q=oe.call(this,V,Y);return(async function*(){for await(let ge of Q)yield*ge}).call(this)}function G(V){if(V=S(V),E(V))return 0;if(V<0)throw new s("number",">= 0",V);return V}function j(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var Q;if(Y!=null&&(Q=Y.signal)!==null&&Q!==void 0&&Q.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;V--<=0&&(yield se)}}).call(this)}function ne(V,Y=void 0){return Y!=null&&u(Y,"options"),Y?.signal!=null&&l(Y.signal,"options.signal"),V=G(V),(async function*(){var Q;if(Y!=null&&(Q=Y.signal)!==null&&Q!==void 0&&Q.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(V-- >0&&(yield se),V<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(z,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:M,flatMap:we,map:oe,take:ne,compose:D},e.exports.promiseReturningOperators={every:te,forEach:X,reduce:be,toArray:re,some:H,find:F}}),Ra=pe((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=De(),{isIterable:o,isNodeStream:n,isWebStream:s}=bt(),{pipelineImpl:a}=_o(),{finished:l}=Ct();Na();function c(...u){return new r((d,p)=>{let g,f,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!s(b)){let y=t(u);g=y.signal,f=y.end}a(u,(y,w)=>{y?p(y):d(w)},{signal:g,end:f})})}e.exports={finished:l,pipeline:c}}),Na=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=De(),{promisify:{custom:s}}=Ye(),{streamReturningOperators:a,promiseReturningOperators:l}=iu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=La(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Yr(),{pipeline:g}=_o(),{destroyer:f}=Yt(),b=Ct(),y=Ra(),w=bt(),m=e.exports=vo().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Jr();for(let x of o(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(S,this,E))},S=a[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let x of o(l)){let v=function(...E){if(new.target)throw c();return n(S,this,E)},S=l[x];r(v,"name",{__proto__:null,value:S.name}),r(v,"length",{__proto__:null,value:S.length}),r(m.Readable.prototype,x,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=wo(),m.Duplex=mt(),m.Transform=Oa(),m.PassThrough=Ma(),m.pipeline=g;var{addAbortSignal:_}=Gr();m.addAbortSignal=_,m.finished=b,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,s,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,s,{__proto__:null,enumerable:!0,get(){return y.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)}}),Bt=pe((i,e)=>{le(),ue(),ce();var t=Na(),r=Ra(),o=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=o,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}),ou=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 o=function(){};o.prototype=r.prototype,t.prototype=new o,t.prototype.constructor=t}}}),su=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),r=Symbol.for("BufferList");function o(n){if(!(this instanceof o))return new o(n);o._init.call(this,n)}o._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},o.prototype._new=function(n){return new o(n)},o.prototype._offset=function(n){if(n===0)return[0,0];let s=0;for(let a=0;a<this._bufs.length;a++){let l=s+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-s];s=l}},o.prototype._reverseOffset=function(n){let s=n[0],a=n[1];for(let l=0;l<s;l++)a+=this._bufs[l].length;return a},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(n){if(n>this.length||n<0)return;let s=this._offset(n);return this._bufs[s[0]][s[1]]},o.prototype.slice=function(n,s){return typeof n=="number"&&n<0&&(n+=this.length),typeof s=="number"&&s<0&&(s+=this.length),this.copy(null,0,n,s)},o.prototype.copy=function(n,s,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&&s||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 b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,s,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-f;if(p>y)this._bufs[b].copy(n,g,f),g+=y;else{this._bufs[b].copy(n,g,f,f+p),g+=y;break}p-=y,f&&(f=0)}return n.length>g?n.slice(0,g):n},o.prototype.shallowSlice=function(n,s){if(n=n||0,s=typeof s!="number"?this.length:s,n<0&&(n+=this.length),s<0&&(s+=this.length),n===s)return this._new();let a=this._offset(n),l=this._offset(s),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)},o.prototype.toString=function(n,s,a){return this.slice(s,a).toString(n)},o.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},o.prototype.duplicate=function(){let n=this._new();for(let s=0;s<this._bufs.length;s++)n.append(this._bufs[s]);return n},o.prototype.append=function(n){return this._attach(n,o.prototype._appendBuffer)},o.prototype.prepend=function(n){return this._attach(n,o.prototype._prependBuffer,!0)},o.prototype._attach=function(n,s,a){if(n==null)return this;if(n.buffer)s.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],s,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],s,a)}else typeof n=="number"&&(n=n.toString()),s.call(this,t.from(n));return this},o.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},o.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},o.prototype.indexOf=function(n,s,a){if(a===void 0&&typeof s=="string"&&(a=s,s=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)),s=Number(s||0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),n.length===0)return s>this.length?this.length:s;let l=this._offset(s),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},o.prototype._match=function(n,s){if(this.length-n<s.length)return!1;for(let a=0;a<s.length;a++)if(this.get(n+a)!==s[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 s in n)(function(a){n[a]===null?o.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:o.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(s)})(),o.prototype._isBufferList=function(n){return n instanceof o||o.isBufferList(n)},o.isBufferList=function(n){return n!=null&&n[r]},e.exports=o}),au=pe((i,e)=>{le(),ue(),ce();var t=Bt().Duplex,r=ou(),o=su();function n(s){if(!(this instanceof n))return new n(s);if(typeof s=="function"){this._callback=s;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)}),s=null}o._init.call(this,s),t.call(this)}r(n,t),Object.assign(n.prototype,o.prototype),n.prototype._new=function(s){return new n(s)},n.prototype._write=function(s,a,l){this._appendBuffer(s),typeof l=="function"&&l()},n.prototype._read=function(s){if(!this.length)return this.push(null);s=Math.min(s,this.length),this.push(this.slice(0,s)),this.consume(s)},n.prototype.end=function(s){t.prototype.end.call(this,s),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(s,a){this._bufs.length=0,this.length=0,a(s)},n.prototype._isBufferList=function(s){return s instanceof n||s instanceof o||n.isBufferList(s)},n.isBufferList=o.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=o}),lu=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}),ja=pe((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=($e(),Re(Fe));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 s=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+s.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let s=t.types[n];t.codes[s]=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 s=t.properties[n];t.propertiesCodes[s]=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 o(n){return[0,1,2].map(s=>[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)|s<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=o("publish"),t.SUBSCRIBE_HEADER=o("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=o("unsubscribe"),t.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("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"}}),cu=pe((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,o=r*60,n=o*24,s=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]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return f*a;case"weeks":case"week":case"w":return f*s;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*o;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>=o?Math.round(p/o)+"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>=o?d(p,g,o,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,f,b){var y=g>=f*1.5;return Math.round(p/f)+" "+b+(y?"s":"")}}),uu=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=cu(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let f=0;for(let b=0;b<g.length;b++)f=(f<<5)-f+g.charCodeAt(b),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=o;function n(g){let f,b=null,y,w;function m(..._){if(!m.enabled)return;let x=m,v=Number(new Date),S=v-(f||v);x.diff=S,x.prev=f,x.curr=v,f=v,_[0]=n.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let E=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";E++;let O=n.formatters[P];if(typeof O=="function"){let B=_[E];I=O.call(x,B),_.splice(E,1),E--}return I}),n.formatArgs.call(x,_),(x.log||n.log).apply(x,_)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=s,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(y!==n.namespaces&&(y=n.namespaces,w=n.enabled(g)),w),set:_=>{b=_}}),typeof n.init=="function"&&n.init(m),m}function s(g,f){let b=n(this.namespace+(typeof f>"u"?":":f)+g);return b.log=this.log,b}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 b of f)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,f){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<f.length&&(f[y]===g[b]||f[y]==="*"))f[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<f.length&&f[y]==="*";)y++;return y===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}),gt=pe((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=o,i.load=n,i.useColors=t,i.storage=s(),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 o(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 Ne<"u"&&"env"in Ne&&(l=Ne.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=uu()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),du=pe((i,e)=>{le(),ue(),ce();var t=au(),{EventEmitter:r}=(Ut(),Re(Tt)),o=lu(),n=ja(),s=gt()("mqtt-packet:parser"),a=class xi extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof xi?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new xi().parser(c)}_resetState(){s("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),s("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++,s("parse: state complete. _stateCounter is now: %d",this._stateCounter),s("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return s("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,s("_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)),s("_parseLength %d",c.value),!!c}_parsePayload(){s("_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 s("_parsePayload complete result: %s",c),c}_parseConnect(){s("_parseConnect");let c,u,d,p,g={},f=this.packet,b=this._parseString();if(b===null)return this._emitError(new Error("Cannot parse protocolId"));if(b!=="MQTT"&&b!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=b,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 y=!!(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=y,f.will.qos=w;else{if(y)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 _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.properties=_)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,s("_parseConnect: packet.clientId: %s",f.clientId),g.will){if(f.protocolVersion===5){let _=this._parseProperties();Object.getOwnPropertyNames(_).length&&(f.will.properties=_)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,s("_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,s("_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,s("_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,s("_parseConnect: complete"),f}_parseConnack(){s("_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)}s("_parseConnack: complete")}_parsePublish(){s("_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),s("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){s("_parseSubscribe");let c=this.packet,u,d,p,g,f,b,y;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(b=(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"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=b,y.rap=f,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),s("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){s("_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(){s("_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"));s("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){s("_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(){s("_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}s("_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(s("_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 s("_parseDisconnect result: true"),!0}_parseAuth(){s("_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),s("_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):(s("_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,s("_parseString: result: %s",p),p}_parseStringPair(){return s("_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,s("_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,s("_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,s("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){s("_parseVarByteNum");let u=4,d=0,p=1,g=0,f=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=p*(b&n.VARBYTEINT_MASK),p*=128,(b&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),f?c?f={bytes:d,value:g}:f=g:f=!1,s("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),s("_parseByte: result: %o",c),c}_parseByType(c){switch(s("_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(){s("_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 b=d[g][f.name];d[g][f.name]=[b],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 s("_newPacket"),this.packet&&(this._list.consume(this.packet.length),s("_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)),s("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(c){s("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),hu=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=($e(),Re(Fe)),r=65536,o={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function s(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++)o[u]=s(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:o,generateCache:a,generateNumber:s,genBufVariableByteInt:l,generate4ByteBuffer:c}}),fu=pe((i,e)=>{le(),ue(),ce(),typeof Ne>"u"||!Ne.version||Ne.version.indexOf("v0.")===0||Ne.version.indexOf("v1.")===0&&Ne.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=Ne;function t(r,o,n,s){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 Ne.nextTick(r);case 2:return Ne.nextTick(function(){r.call(null,o)});case 3:return Ne.nextTick(function(){r.call(null,o,n)});case 4:return Ne.nextTick(function(){r.call(null,o,n,s)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return Ne.nextTick(function(){r.apply(null,l)})}}}),Ua=pe((i,e)=>{le(),ue(),ce();var t=ja(),{Buffer:r}=($e(),Re(Fe)),o=r.allocUnsafe(0),n=r.from([0]),s=hu(),a=fu().nextTick,l=gt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,p=s.genBufVariableByteInt,g=s.generate4ByteBuffer,f=z,b=!0;function y(G,j,ne){switch(l("generate called"),j.cork&&(j.cork(),a(w,j)),b&&(b=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,j);case"connack":return _(G,j,ne);case"publish":return x(G,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,j,ne);case"subscribe":return S(G,j,ne);case"suback":return E(G,j,ne);case"unsubscribe":return I(G,j,ne);case"unsuback":return P(G,j,ne);case"pingreq":case"pingresp":return O(G,j);case"disconnect":return B(G,j,ne);case"auth":return T(G,j,ne);default:return j.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return f===z},set(G){G?((!c||Object.keys(c).length===0)&&(b=!0),f=z):(b=!1,f=H)}});function w(G){G.uncork()}function m(G,j,ne){let V=G||{},Y=V.protocolId||"MQTT",Q=V.protocolVersion||4,ge=V.will,se=V.clean,R=V.keepalive||0,q=V.clientId||"",ee=V.username,he=V.password,fe=V.properties;se===void 0&&(se=!0);let ye=0;if(typeof Y!="string"&&!r.isBuffer(Y))return j.destroy(new Error("Invalid protocolId")),!1;if(ye+=Y.length+2,Q!==3&&Q!==4&&Q!==5)return j.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof q=="string"||r.isBuffer(q))&&(q||Q>=4)&&(q||se))ye+=r.byteLength(q)+2;else{if(Q<4)return j.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return j.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof R!="number"||R<0||R>65535||R%1!==0)return j.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let W,me;if(Q===5){if(W=X(j,fe),!W)return!1;ye+=W.length}if(ge){if(typeof ge!="object")return j.destroy(new Error("Invalid will")),!1;if(!ge.topic||typeof ge.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(ge.topic)+2,ye+=2,ge.payload)if(ge.payload.length>=0)typeof ge.payload=="string"?ye+=r.byteLength(ge.payload):ye+=ge.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=X(j,ge.properties),!me)return!1;ye+=me.length}}let ve=!1;if(ee!=null)if(we(ee))ve=!0,ye+=r.byteLength(ee)+2;else return j.destroy(new Error("Invalid username")),!1;if(he!=null){if(!ve)return j.destroy(new Error("Username is required to use password")),!1;if(we(he))ye+=re(he)+2;else return j.destroy(new Error("Invalid password")),!1}j.write(t.CONNECT_HEADER),U(j,ye),F(j,Y),V.bridgeMode&&(Q+=128),j.write(Q===131?t.VERSION131:Q===132?t.VERSION132:Q===4?t.VERSION4:Q===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,j.write(r.from([ae])),f(j,R),Q===5&&W.write(),F(j,q),ge&&(Q===5&&me.write(),D(j,ge.topic),F(j,ge.payload)),ee!=null&&F(j,ee),he!=null&&F(j,he),!0}function _(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=V===5?Y.reasonCode:Y.returnCode,ge=Y.properties,se=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let R=null;if(V===5){if(R=X(j,ge),!R)return!1;se+=R.length}return j.write(t.CONNACK_HEADER),U(j,se),j.write(Y.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),R?.write(),!0}function x(G,j,ne){l("publish: packet: %o",G);let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.qos||0,ge=Y.retain?t.RETAIN_MASK:0,se=Y.topic,R=Y.payload||o,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 j.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(R)?he+=R.length:he+=r.byteLength(R),Q&&typeof q!="number")return j.destroy(new Error("Invalid messageId")),!1;Q&&(he+=2);let fe=null;if(V===5){if(fe=X(j,ee),!fe)return!1;he+=fe.length}return j.write(t.PUBLISH_HEADER[Q][Y.dup?1:0][ge?1:0]),U(j,he),f(j,re(se)),j.write(se),Q>0&&f(j,q),fe?.write(),l("publish: payload: %o",R),j.write(R)}function v(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.cmd||"puback",ge=Y.messageId,se=Y.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,q=Y.reasonCode,ee=Y.properties,he=V===5?3:2;if(Q==="pubrel"&&(R=1),typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;let fe=null;if(V===5&&typeof ee=="object"){if(fe=M(j,ee,ne,he),!fe)return!1;he+=fe.length}return j.write(t.ACKS[Q][R][se][0]),he===3&&(he+=q!==0?1:-1),U(j,he),f(j,ge),V===5&&he!==2&&j.write(r.from([q])),fe!==null?fe.write():he===4&&j.write(r.from([0])),!0}function S(G,j,ne){l("subscribe: packet: ");let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.dup?t.DUP_MASK:0,ge=Y.messageId,se=Y.subscriptions,R=Y.properties,q=0;if(typeof ge!="number")return j.destroy(new Error("Invalid messageId")),!1;q+=2;let ee=null;if(V===5){if(ee=X(j,R),!ee)return!1;q+=ee.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,W=se[fe].qos;if(typeof ye!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof W!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(V===5){if(typeof(se[fe].nl||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[fe].rh||0;if(typeof me!="number"||me>2)return j.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=r.byteLength(ye)+2+1}else return j.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),j.write(t.SUBSCRIBE_HEADER[1][Q?1:0][0]),U(j,q),f(j,ge),ee!==null&&ee.write();let he=!0;for(let fe of se){let ye=fe.topic,W=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;D(j,ye),Oe=t.SUBSCRIBE_OPTIONS_QOS[W],V===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=j.write(r.from([Oe]))}return he}function E(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.messageId,ge=Y.granted,se=Y.properties,R=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ge=="object"&&ge.length)for(let ee=0;ee<ge.length;ee+=1){if(typeof ge[ee]!="number")return j.destroy(new Error("Invalid qos vector")),!1;R+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let q=null;if(V===5){if(q=M(j,se,ne,R),!q)return!1;R+=q.length}return j.write(t.SUBACK_HEADER),U(j,R),f(j,Q),q!==null&&q.write(),j.write(r.from(ge))}function I(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.unsubscriptions,R=Y.properties,q=0;if(typeof Q!="number")return j.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 j.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return j.destroy(new Error("Invalid unsubscriptions")),!1;let ee=null;if(V===5){if(ee=X(j,R),!ee)return!1;q+=ee.length}j.write(t.UNSUBSCRIBE_HEADER[1][ge?1:0][0]),U(j,q),f(j,Q),ee!==null&&ee.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=D(j,se[fe]);return he}function P(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.messageId,ge=Y.dup?t.DUP_MASK:0,se=Y.granted,R=Y.properties,q=Y.cmd,ee=0,he=2;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(V===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[ye]!="number")return j.destroy(new Error("Invalid qos vector")),!1;he+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(V===5){if(fe=M(j,R,ne,he),!fe)return!1;he+=fe.length}return j.write(t.ACKS[q][ee][ge][0]),U(j,he),f(j,Q),fe!==null&&fe.write(),V===5&&j.write(r.from(se)),!0}function O(G,j,ne){return j.write(t.EMPTY[G.cmd])}function B(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.reasonCode,ge=Y.properties,se=V===5?1:0,R=null;if(V===5){if(R=M(j,ge,ne,se),!R)return!1;se+=R.length}return j.write(r.from([t.codes.disconnect<<4])),U(j,se),V===5&&j.write(r.from([Q])),R!==null&&R.write(),!0}function T(G,j,ne){let V=ne?ne.protocolVersion:4,Y=G||{},Q=Y.reasonCode,ge=Y.properties,se=V===5?1:0;V!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let R=M(j,ge,ne,se);return R?(se+=R.length,j.write(r.from([t.codes.auth<<4])),U(j,se),j.write(r.from([Q])),R!==null&&R.write(),!0):!1}var L={};function U(G,j){if(j>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=L[j];return ne||(ne=p(j),j<16384&&(L[j]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function D(G,j){let ne=r.byteLength(j);return f(G,ne),l("writeString: %s",j),G.write(j,"utf8")}function oe(G,j,ne){D(G,j),D(G,ne)}function z(G,j){return l("writeNumberCached: number: %d",j),l("writeNumberCached: %o",c[j]),G.write(c[j])}function H(G,j){let ne=u(j);return l("writeNumberGenerated: %o",ne),G.write(ne)}function te(G,j){let ne=g(j);return l("write4ByteNumber: %o",ne),G.write(ne)}function F(G,j){typeof j=="string"?D(G,j):j?(f(G,j.length),G.write(j)):f(G,0)}function X(G,j){if(typeof j!="object"||j.length!=null)return{length:1,write(){be(G,{},0)}};let ne=0;function V(Y,Q){let ge=t.propertiesTypes[Y],se=0;switch(ge){case"byte":{if(typeof Q!="boolean")return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=2;break}case"binary":{if(Q&&Q===null)return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return G.destroy(new Error(`Invalid ${Y}: ${Q}`)),!1;se+=Object.getOwnPropertyNames(Q).reduce((R,q)=>{let ee=Q[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(Q[q].toString()),R},0);break}default:return G.destroy(new Error(`Invalid property ${Y}: ${Q}`)),!1}return se}if(j)for(let Y in j){let Q=0,ge=0,se=j[Y];if(se!==void 0){if(Array.isArray(se))for(let R=0;R<se.length;R++){if(ge=V(Y,se[R]),!ge)return!1;Q+=ge}else{if(ge=V(Y,se),!ge)return!1;Q=ge}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){be(G,j,ne)}}}function M(G,j,ne,V){let Y=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ge=X(G,j);if(Q)for(;V+ge.length>Q;){let se=Y.shift();if(se&&j[se])delete j[se],ge=X(G,j);else return!1}return ge}function J(G,j,ne){switch(t.propertiesTypes[j]){case"byte":{G.write(r.from([t.properties[j]])),G.write(r.from([+ne]));break}case"int8":{G.write(r.from([t.properties[j]])),G.write(r.from([ne]));break}case"binary":{G.write(r.from([t.properties[j]])),F(G,ne);break}case"int16":{G.write(r.from([t.properties[j]])),f(G,ne);break}case"int32":{G.write(r.from([t.properties[j]])),te(G,ne);break}case"var":{G.write(r.from([t.properties[j]])),U(G,ne);break}case"string":{G.write(r.from([t.properties[j]])),D(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(V=>{let Y=ne[V];Array.isArray(Y)?Y.forEach(Q=>{G.write(r.from([t.properties[j]])),oe(G,V.toString(),Q.toString())}):(G.write(r.from([t.properties[j]])),oe(G,V.toString(),Y.toString()))});break}default:return G.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function be(G,j,ne){U(G,ne);for(let V in j)if(Object.prototype.hasOwnProperty.call(j,V)&&j[V]!=null){let Y=j[V];if(Array.isArray(Y))for(let Q=0;Q<Y.length;Q++)J(G,V,Y[Q]);else J(G,V,Y)}}function re(G){return G?G instanceof r?G.length:r.byteLength(G):0}function we(G){return typeof G=="string"||G instanceof r}e.exports=y}),pu=pe((i,e)=>{le(),ue(),ce();var t=Ua(),{EventEmitter:r}=(Ut(),Re(Tt)),{Buffer:o}=($e(),Re(Fe));function n(a,l){let c=new s;return t(a,c,l),c.concat()}var s=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]=o.byteLength(c[d]),a+=l[d];let p=o.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}),mu=pe(i=>{le(),ue(),ce(),i.parser=du().parser,i.generate=pu(),i.writeToStream=Ua()}),gu=pe((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof zr?zr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return o(n);let s=new Map;if(s.set(Date,d=>new Date(d)),s.set(Map,(d,p)=>new Map(l(Array.from(d),p))),s.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)s.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 b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?f[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?f[y]=a(w,p):ArrayBuffer.isView(w)?f[y]=t(w):f[y]=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=s.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=s.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=s.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=s.get(f.constructor))?p[g]=a(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function o(n){let s=[],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 b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],_=g[m];if(typeof _!="object"||_===null)y[m]=_;else if(_.constructor!==Object&&(c=l.get(_.constructor)))y[m]=c(_,f);else if(ArrayBuffer.isView(_))y[m]=t(_);else{let x=s.indexOf(_);x!==-1?y[m]=a[x]:y[m]=f(_)}}return y}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={};s.push(g),a.push(f);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[b]=c(y,d);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=s.indexOf(y);w!==-1?f[b]=a[w]:f[b]=d(y)}}return s.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={};s.push(g),a.push(f);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)f[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))f[b]=c(y,p);else if(ArrayBuffer.isView(y))f[b]=t(y);else{let w=s.indexOf(y);w!==-1?f[b]=a[w]:f[b]=p(y)}}return s.pop(),a.pop(),f}}}),bu=pe((i,e)=>{le(),ue(),ce(),e.exports=gu()()}),Da=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.validateTopics=t;function e(r){let o=r.split("/");for(let n=0;n<o.length;n++)if(o[n]!=="+"){if(o[n]==="#")return n===o.length-1;if(o[n].indexOf("+")!==-1||o[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let o=0;o<r.length;o++)if(!e(r[o]))return r[o];return null}}),Ba=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Bt(),t={objectMode:!0},r={clean:!0},o=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,s){return this._inflights.set(n.messageId,n),s&&s(),this}createStream(){let n=new e.Readable(t),s=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{s.push(c)}),n._read=()=>{!a&&l<s.length?n.push(s[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,s){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),s(null,a)):s&&s(new Error("missing packet")),this}get(n,s){let a=this._inflights.get(n.messageId);return a?s(null,a):s&&s(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=o}),yu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,o,n)=>{r.log("handlePublish: packet %o",o),n=typeof n<"u"?n:r.noop;let s=o.topic.toString(),a=o.payload,{qos:l}=o,{messageId:c}=o,{options:u}=r;if(r.options.protocolVersion===5){let d;if(o.properties&&(d=o.properties.topicAlias),typeof d<"u")if(s.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)s=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",s,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(s,d))r.log("handlePublish :: registered topic: %s - alias: %d",s,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(s,a,o,(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(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,o,(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",s,a,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",s,a,o),r.handleMessage(o,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),vu=pe((i,e)=>{e.exports={version:"5.15.0"}}),Jt=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 Fa extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Fa.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class $a extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,$a.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(o,n,s=!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))(s||c!=="constructor")&&Object.defineProperty(o.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof Ne?.nextTick=="function"?Ne.nextTick:o=>{setTimeout(o,0)},i.MQTTJS_VERSION=vu().version}),Qr=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=Jt();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,o)=>{let{messageId:n}=o,s=o.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",s),s){case"pubcomp":case"puback":{let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=o.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,o)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=o.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,o);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,o);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),wu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Jt(),t=Qr(),r=(o,n)=>{let{options:s}=o,a=s.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);o.emit("error",c);return}o.handleAuth(n,(c,u)=>{if(c){o.emit("error",c);return}if(l===24)o.reconnecting=!1,o._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);o.emit("error",d)}})};i.default=r}),_u=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 Ne=="object"&&Ne?Ne:{},o=(g,f,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,b,y):console.error(`[${b}] ${f}: ${g}`)},n=globalThis.AbortController,s=globalThis.AbortSignal;if(typeof n>"u"){s=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(b,y){this._onabort.push(y)}},n=class{constructor(){f()}signal=new s;abort(b){if(!this.signal.aborted){this.signal.reason=b,this.signal.aborted=!0;for(let y of this.signal._onabort)y(b);this.signal.onabort?.(b)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!1,o("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 sr{heap;length;static#l=!1;static create(f){let b=c(f);if(!b)return[];sr.#l=!0;let y=new sr(f,b);return sr.#l=!1,y}constructor(f,b){if(!sr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class qa{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#f;#_;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#y,isBackgroundFetch:b=>f.#t(b),backgroundFetch:(b,y,w,m)=>f.#R(b,y,w,m),moveToTail:b=>f.#C(b),indexes:b=>f.#k(b),rindexes:b=>f.#x(b),isStale:b=>f.#p(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}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:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:_,updateAgeOnHas:x,allowStale:v,dispose:S,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:B=0,sizeCalculation:T,fetchMethod:L,memoMethod:U,noDeleteOnFetchRejection:D,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:z,allowStaleOnFetchAbort:H,ignoreFetchAbort:te}=f;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let F=b?c(b):Array;if(!F)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=O,this.maxEntrySize=B||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(U!==void 0&&typeof U!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=U,L!==void 0&&typeof L!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=L,this.#A=!!L,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new F(b),this.#h=new F(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof S=="function"&&(this.#m=S),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#_=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!D,this.allowStaleOnFetchRejection=!!z,this.allowStaleOnFetchAbort=!!H,this.ignoreFetchAbort=!!te,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=!!_,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||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 X="LRU_CACHE_UNBOUNDED";a(X)&&(t.add(X),o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",X,qa))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),b=new u(this.#l);this.#f=f,this.#w=b,this.#j=(m,_,x=e.now())=>{if(b[m]=_!==0?x:0,f[m]=_,_!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},_+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=f[m]!==0?e.now():0},this.#E=(m,_)=>{if(f[_]){let x=f[_],v=b[_];if(!x||!v)return;m.ttl=x,m.start=v,m.now=y||w();let S=m.now-v;m.remainingTTL=x-S}};let y=0,w=()=>{let m=e.now();if(this.ttlResolution>0){y=m;let _=setTimeout(()=>y=0,this.ttlResolution);_.unref&&_.unref()}return m};this.getRemainingTTL=m=>{let _=this.#n.get(m);if(_===void 0)return 0;let x=f[_],v=b[_];if(!x||!v)return 1/0;let S=(y||w())-v;return x-S},this.#p=m=>{let _=b[m],x=f[m];return!!x&&!!_&&(y||w())-_>x}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#b=0,this.#v=f,this.#T=b=>{this.#b-=f[b],f[b]=0},this.#U=(b,y,w,m)=>{if(this.#t(y))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(y,b),!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=(b,y,w)=>{if(f[b]=y,this.#d){let m=this.#d-f[b];for(;this.#b>m;)this.#L(!0)}this.#b+=f[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=f=>{};#M=(f,b,y)=>{};#U=(f,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:f=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#D(b)||((f||!this.#p(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:f=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#D(b)||((f||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#D(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#k())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#x())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#k()){let b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*rkeys(){for(let f of this.#x()){let b=this.#r[f];b!==void 0&&!this.#t(this.#e[f])&&(yield b)}}*values(){for(let f of this.#k())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#x())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,b={}){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(f,b=this){for(let y of this.#k()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}rforEach(f,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(b,m,this.#r[y],this)}}purgeStale(){let f=!1;for(let b of this.#x({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),f=!0);return f}info(f){let b=this.#n.get(f);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let _=this.#f[b],x=this.#w[b];if(_&&x){let v=_-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let f=[];for(let b of this.#k({allowStale:!0})){let y=this.#r[b],w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||y===void 0)continue;let _={value:m};if(this.#f&&this.#w){_.ttl=this.#f[b];let x=e.now()-this.#w[b];_.start=Math.floor(Date.now()-x)}this.#v&&(_.size=this.#v[b]),f.unshift([y,_])}return f}load(f){this.clear();for(let[b,y]of f){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(f,b,y={}){if(b===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:_=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:S=this.noUpdateTTL}=y,E=this.#U(f,b,y.size||0,x);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#L(!1):this.#i,this.#r[I]=f,this.#e[I]=b,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"),S=!1;else{this.#C(I);let P=this.#e[I];if(b!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!_&&(this.#_&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else _||(this.#_&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]));if(this.#T(I),this.#M(I,E,v),this.#e[I]=b,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#N(),this.#f&&(S||this.#j(I,w,m),v&&this.#E(v,I)),!_&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.shift();)this.#g?.(...O)}return this}pop(){try{for(;this.#i;){let f=this.#e[this.#a];if(this.#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,b;for(;b=f?.shift();)this.#g?.(...b)}}}#L(f){let b=this.#a,y=this.#r[b],w=this.#e[b];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),f&&(this.#r[b]=void 0,this.#e[b]=void 0,this.#y.push(b)),this.#i===1?(this.#a=this.#o=0,this.#y.length=0):this.#a=this.#c[b],this.#n.delete(y),this.#i--,b}has(f,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(f);if(m!==void 0){let _=this.#e[m];if(this.#t(_)&&_.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(f);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#R(f,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let _=new n,{signal:x}=y;x?.addEventListener("abort",()=>_.abort(x.reason),{signal:_.signal});let v={signal:_.signal,options:y,context:w},S=(T,L=!1)=>{let{aborted:U}=_.signal,D=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(U&&!L?(y.status.fetchAborted=!0,y.status.fetchError=_.signal.reason,D&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),U&&!D&&!L)return I(_.signal.reason);let oe=O;return this.#e[b]===O&&(T===void 0?oe.__staleWhileFetching?this.#e[b]=oe.__staleWhileFetching:this.#S(f,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(f,T,v.options))),T},E=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:L}=_.signal,U=L&&y.allowStaleOnFetchAbort,D=U||y.allowStaleOnFetchRejection,oe=D||y.noDeleteOnFetchRejection,z=O;if(this.#e[b]===O&&(!oe||z.__staleWhileFetching===void 0?this.#S(f,"fetch"):U||(this.#e[b]=z.__staleWhileFetching)),D)return y.status&&z.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),z.__staleWhileFetching;if(z.__returned===z)throw T},P=(T,L)=>{let U=this.#P?.(f,m,v);U&&U instanceof Promise&&U.then(D=>T(D===void 0?void 0:D),L),_.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=D=>S(D,!0)))})};y.status&&(y.status.fetchDispatched=!0);let O=new Promise(P).then(S,E),B=Object.assign(O,{__abortController:_,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(f,B,{...v.options,status:void 0}),b=this.#n.get(f)):this.#e[b]=B,B}#t(f){if(!this.#A)return!1;let b=f;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(f,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:_=this.ttl,noDisposeOnSet:x=this.noDisposeOnSet,size:v=0,sizeCalculation:S=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:T,forceRefresh:L=!1,status:U,signal:D}=b;if(!this.#A)return U&&(U.fetch="get"),this.get(f,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:U});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:_,noDisposeOnSet:x,size:v,sizeCalculation:S,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:U,signal:D},z=this.#n.get(f);if(z===void 0){U&&(U.fetch="miss");let H=this.#R(f,z,oe,T);return H.__returned=H}else{let H=this.#e[z];if(this.#t(H)){let M=y&&H.__staleWhileFetching!==void 0;return U&&(U.fetch="inflight",M&&(U.returnedStale=!0)),M?H.__staleWhileFetching:H.__returned=H}let te=this.#p(z);if(!L&&!te)return U&&(U.fetch="hit"),this.#C(z),w&&this.#I(z),U&&this.#E(U,z),H;let F=this.#R(f,z,oe,T),X=F.__staleWhileFetching!==void 0&&y;return U&&(U.fetch=te?"stale":"refresh",X&&te&&(U.returnedStale=!0)),X?F.__staleWhileFetching:F.__returned=F}}async forceFetch(f,b={}){let y=await this.fetch(f,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(f,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,..._}=b,x=this.get(f,_);if(!m&&x!==void 0)return x;let v=y(f,x,{options:_,context:w});return this.set(f,v,_),v}get(f,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:_}=b,x=this.#n.get(f);if(x!==void 0){let v=this.#e[x],S=this.#t(v);return _&&this.#E(_,x),this.#p(x)?(_&&(_.get="stale"),S?(_&&y&&v.__staleWhileFetching!==void 0&&(_.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(f,"expire"),_&&y&&(_.returnedStale=!0),y?v:void 0)):(_&&(_.get="hit"),S?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else _&&(_.get="miss")}#B(f,b){this.#h[b]=f,this.#c[f]=b}#C(f){f!==this.#o&&(f===this.#a?this.#a=this.#c[f]:this.#B(this.#h[f],this.#c[f]),this.#B(this.#o,f),this.#o=f)}delete(f){return this.#S(f,"delete")}#S(f,b){let y=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(y=!0,this.#i===1)this.#F(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#_||this.#u)&&(this.#_&&this.#m?.(m,f,b),this.#u&&this.#s?.push([m,f,b])),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 _=this.#h[w];this.#c[_]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#y.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return y}clear(){return this.#F("delete")}#F(f){for(let b of this.#x({allowStale:!0})){let y=this.#e[b];if(this.#t(y))y.__abortController.abort(new Error("deleted"));else{let w=this.#r[b];this.#_&&this.#m?.(y,w,f),this.#u&&this.#s?.push([y,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.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};i.LRUCache=p}),yt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(o=0){this.iteratorType=o}equals(o){return this.o===o.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}),ku=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Base{constructor(o=[]){super(),this.S=[];let n=this;o.forEach(function(s){n.push(s)})}clear(){this.i=0,this.S=[]}push(o){return this.S.push(o),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}),xu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Base{constructor(o=[]){super(),this.j=0,this.q=[];let n=this;o.forEach(function(s){n.push(s)})}clear(){this.q=[],this.i=this.j=0}push(o){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let s=this.i;for(let a=0;a<s;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=o}else this.q[this.j+this.i]=o;return++this.i}pop(){if(this.i===0)return;let o=this.q[this.j++];return this.i-=1,o}front(){if(this.i!==0)return this.q[this.j]}},r=t;i.default=r}),Su=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Base{constructor(o=[],n=function(a,l){return a>l?-1:a<l?1:0},s=!0){if(super(),this.v=n,Array.isArray(o))this.C=s?[...o]:o;else{this.C=[];let l=this;o.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(o){let n=this.C[o];for(;o>0;){let s=o-1>>1,a=this.C[s];if(this.v(a,n)<=0)break;this.C[o]=a,o=s}this.C[o]=n}k(o,n){let s=this.C[o];for(;o<n;){let a=o<<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,s)>=0)break;this.C[o]=c,o=a}this.C[o]=s}clear(){this.i=0,this.C.length=0}push(o){this.C.push(o),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let o=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),o}top(){return this.C[0]}find(o){return this.C.indexOf(o)>=0}remove(o){let n=this.C.indexOf(o);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(o){let n=this.C.indexOf(o);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;i.default=r}),ko=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Container{},r=t;i.default=r}),vt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ha=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=yt(),t=vt(),r=class extends e.ContainerIterator{constructor(o,n){super(n),this.o=o,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(o){this.container.setElementByPos(this.o,o)}};i.RandomIterator=r}),Eu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(ko()),t=Ha();function r(a){return a&&a.t?a:{default:a}}var o=class Wa extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Wa(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 o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-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 o(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)()}},s=n;i.default=s}),Au=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(ko()),t=yt(),r=vt();function o(l){return l&&l.t?l:{default:l}}var n=class za 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 za(this.o,this.h,this.container,this.iteratorType)}},s=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=s;i.default=a}),Iu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(ko()),t=Ha();function r(a){return a&&a.t?a:{default:a}}var o=class Va extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Va(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 o(0,this)}end(){return new o(this.i,this)}rBegin(){return new o(this.i-1,this,1)}rEnd(){return new o(-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 o(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)()}},s=n;i.default=s}),Tu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.TreeNode=void 0;var e=class{constructor(r,o){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=o}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 o=r.tt;for(;o.U===r;)r=o,o=r.tt;r=o}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let o=r.tt;for(;o.W===r;)r=o,o=r.tt;return r.W!==o?o:r}}te(){let r=this.tt,o=this.W,n=o.U;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.U=this,this.tt=o,this.W=n,n&&(n.tt=this),o}se(){let r=this.tt,o=this.U,n=o.W;return r.tt===this?r.tt=o:r.U===this?r.U=o:r.W=o,o.tt=r,o.W=this,this.tt=o,this.U=n,n&&(n.tt=this),o}};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}),Ka=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Tu(),t=yt(),r=vt(),o=class extends t.Container{constructor(s=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=s,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:b,curNode:y}=g;f.ie(),b.ie(),y.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(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)s=s.W;else if(c>0)l=s,s=s.U;else return s}return l}Z(s,a){let l=this.h;for(;s;)this.v(s.u,a)<=0?s=s.W:(l=s,s=s.U);return l}$(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)l=s,s=s.W;else if(c>0)s=s.U;else return s}return l}rr(s,a){let l=this.h;for(;s;)this.v(s.u,a)<0?(l=s,s=s.W):s=s.U;return l}ue(s){for(;;){let a=s.tt;if(a===this.h)return;if(s.ee===1){s.ee=0;return}if(s===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,s=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,s=a)}}}fe(s){if(this.i===1)return this.clear(),this.h;let a=s;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[s.u,a.u]=[a.u,s.u],[s.l,a.l]=[a.l,s.l],s=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(s,a){return s===void 0?!1:this.oe(s.U,a)||a(s)?!0:this.oe(s.W,a)}he(s){for(;;){let a=s.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,s=l;continue}else if(s===a.W){if(s.ee=0,s.U&&(s.U.tt=a),s.W&&(s.W.tt=l),a.W=s.U,l.U=s.W,s.U=a,s.W=l,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}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,s=l;continue}else if(s===a.U){if(s.ee=0,s.U&&(s.U.tt=l),s.W&&(s.W.tt=a),l.W=s.U,a.U=s.W,s.U=l,s.W=a,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(s,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(s,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,s);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(s,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,s);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(s,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 b=this.v(f.u,s);if(b===0){f.l=a;return}else if(b>0){let y=f.L(),w=this.v(y.u,s);if(w===0){y.l=a;return}else w<0&&(c=new this.re(s,a),y.W===void 0?(y.W=c,c.tt=y):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,s);if(f>0){if(c.U===void 0){c.U=new this.re(s,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(s,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(s,a){for(;s;){let l=this.v(s.u,a);if(l<0)s=s.W;else if(l>0)s=s.U;else return s}return s||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(s,a){let l=s.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(s){if(s<0||s>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return s===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(s){if(this.i===0)return!1;let a=this.I(this.Y,s);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(s){let a=s.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return s.iteratorType===0?l&&s.next():(!l||a.U===void 0)&&s.next(),this.V(a),s}forEach(s){let a=0;for(let l of this)s(l,a++,this)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===s){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let s=function(a){return a?Math.max(s(a.U),s(a.W))+1:0};return s(this.Y)}},n=o;i.default=n}),Ga=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=vt(),r=class extends e.ContainerIterator{constructor(n,s,a){super(a),this.o=n,this.h=s,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,s=this.h.tt;if(n===this.h)return s?s.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==s;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},o=r;i.default=o}),Cu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Ka()),t=o(Ga()),r=vt();function o(l){return l&&l.t?l:{default:l}}var n=class Ya 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 Ya(this.o,this.h,this.container,this.iteratorType)}},s=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=s;i.default=a}),Pu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Ka()),t=o(Ga()),r=vt();function o(l){return l&&l.t?l:{default:l}}var n=class Ja 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 Ja(this.o,this.h,this.container,this.iteratorType)}},s=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=s;i.default=a}),Qa=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"}}),Xa=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=yt(),t=o(Qa()),r=vt();function o(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 s=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=s}),Ou=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Xa(),t=vt(),r=class Za 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 Za(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(s=[]){super();let a=this;s.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(s,a){return this.M(s,void 0,a)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=this.p;for(;s--;)a=a.B;return a.u}find(s,a){let l=this.I(s,a);return new r(l,this.h,this)}forEach(s){let a=0,l=this.p;for(;l!==this.h;)s(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let s=this.p;for(;s!==this.h;)yield s.u,s=s.B}).bind(this)()}},n=o;i.default=n}),Mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Xa(),t=o(Qa()),r=vt();function o(l){return l&&l.t?l:{default:l}}var n=class el 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 el(this.o,this.h,this.container,this.iteratorType)}},s=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=s;i.default=a}),Lu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return s.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 o.default}});var e=d(ku()),t=d(xu()),r=d(Su()),o=d(Eu()),n=d(Au()),s=d(Iu()),a=d(Cu()),l=d(Pu()),c=d(Ou()),u=d(Mu());function d(p){return p&&p.t?p:{default:p}}}),Ru=pe((i,e)=>{le(),ue(),ce();var t=Lu().OrderedSet,r=gt()("number-allocator:trace"),o=gt()("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 s(a,l){if(!(this instanceof s))return new s(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}s.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},s.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},s.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},s.prototype.free=function(a){if(a<this.min||a>this.max){o("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)},s.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},s.prototype.intervalCount=function(){return this.ss.size()},s.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=s}),tl=pe((i,e)=>{le(),ue(),ce();var t=Ru();e.exports.NumberAllocator=t}),Nu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=_u(),t=tl(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(o){o>0&&(this.aliasToTopic=new e.LRUCache({max:o}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,o),this.max=o,this.length=0)}put(o,n){if(n===0||n>this.max)return!1;let s=this.aliasToTopic.get(n);return s&&delete this.topicToAlias[s],this.aliasToTopic.set(n,o),this.topicToAlias[o]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(o){return this.aliasToTopic.get(o)}getAliasByTopic(o){let n=this.topicToAlias[o];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}),ju=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=Qr(),r=e(Nu()),o=Jt(),n=(s,a)=>{s.log("_handleConnack");let{options:l}=s,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(s.connackTimer),delete s.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){s.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(s.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)s.reconnecting=!1,s._onConnect(a);else if(c>0){let u=new o.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);s.emit("error",u),s.options.reconnectOnConnackError&&s._cleanUp(!0)}};i.default=n}),Uu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,o)=>{t.log("handling pubrel packet");let n=typeof o<"u"?o:t.noop,{messageId:s}=r,a={cmd:"pubcomp",messageId:s};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}),Du=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(yu()),r=e(wu()),o=e(ju()),n=e(Qr()),s=e(Uu()),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,s.default)(l,c,u);break;case"connack":(0,o.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}),rl=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}),Bu=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}),Fu=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((Ut(),Re(Tt))),r=Jt(),o=class{};i.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Xr=pe((i,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o){return typeof o}:function(o){return o&&typeof Symbol=="function"&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=pe((i,e)=>{le(),ue(),ce();var t=Xr().default;function r(o,n){if(t(o)!="object"||!o)return o;var s=o[Symbol.toPrimitive];if(s!==void 0){var a=s.call(o,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(o)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),qu=pe((i,e)=>{le(),ue(),ce();var t=Xr().default,r=$u();function o(n){var s=r(n,"string");return t(s)=="symbol"?s:s+""}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((i,e)=>{le(),ue(),ce();var t=qu();function r(o,n,s){return(n=t(n))in o?Object.defineProperty(o,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):o[n]=s,o}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=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}),zu=pe((i,e)=>{le(),ue(),ce();function t(r,o){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var s,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,o===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(s=l.call(n)).done)&&(u.push(s.value),u.length!==o);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}),Vu=pe((i,e)=>{le(),ue(),ce();function t(r,o){(o==null||o>r.length)&&(o=r.length);for(var n=0,s=Array(o);n<o;n++)s[n]=r[n];return s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ku=pe((i,e)=>{le(),ue(),ce();var t=Vu();function r(o,n){if(o){if(typeof o=="string")return t(o,n);var s={}.toString.call(o).slice(8,-1);return s==="Object"&&o.constructor&&(s=o.constructor.name),s==="Map"||s==="Set"?Array.from(o):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(o,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Gu=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}),Yu=pe((i,e)=>{le(),ue(),ce();var t=Wu(),r=zu(),o=Ku(),n=Gu();function s(a,l){return t(a)||r(a,l)||o(a,l)||n()}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),nl=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 b=g(f);return f.add(b),b}},o=function(g){return function(f,b){return g.set(f,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,f){return function(b){var y=f.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<s){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=o(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Ju=pe((i,e)=>{le(),ue(),ce();function t(o,n,s,a,l,c,u){try{var d=o[c](u),p=d.value}catch(g){return void s(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(o){return function(){var n=this,s=arguments;return new Promise(function(a,l){var c=o.apply(n,s);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}),il=pe((i,e)=>{le(),ue(),ce();function t(r,o){this.v=r,this.k=o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ol=pe((i,e)=>{le(),ue(),ce();function t(r,o,n,s){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(b){return this._invoke(g,f,b)})}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,o,n,s)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),sl=pe((i,e)=>{le(),ue(),ce();var t=ol();function r(){var o,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,_,x){var v=m&&m.prototype instanceof d?m:d,S=Object.create(v.prototype);return t(S,"_invoke",(function(E,I,P){var O,B,T,L=0,U=P||[],D=!1,oe={p:0,n:0,v:o,a:z,f:z.bind(o,4),d:function(H,te){return O=H,B=0,T=o,oe.n=te,u}};function z(H,te){for(B=H,T=te,n=0;!D&&L&&!F&&n<U.length;n++){var F,X=U[n],M=oe.p,J=X[2];H>3?(F=J===te)&&(T=X[(B=X[4])?5:(B=3,3)],X[4]=X[5]=o):X[0]<=M&&((F=H<2&&M<X[1])?(B=0,oe.v=te,oe.n=X[1]):M<J&&(F=H<3||X[0]>te||te>J)&&(X[4]=H,X[5]=te,oe.n=J,B=0))}if(F||H>1)return u;throw D=!0,te}return function(H,te,F){if(L>1)throw TypeError("Generator is already running");for(D&&te===1&&z(te,F),B=te,T=F;(n=B<2?o:T)||!D;){O||(B?B<3?(B>1&&(oe.n=-1),z(B,T)):oe.n=T:oe.v=T);try{if(L=2,O){if(B||(H="next"),n=O[H]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,B<2&&(B=0)}else B===1&&(n=O.return)&&n.call(O),B<2&&(T=TypeError("The iterator does not provide a '"+H+"' method"),B=1);O=o}else if((n=(D=oe.n<0)?T:E.call(I,oe))!==u)break}catch(X){O=o,B=1,T=X}finally{L=1}}return{value:n,done:D}}})(w,_,x),!0),S}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(f);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return p.prototype=g,t(b,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),al=pe((i,e)=>{le(),ue(),ce();var t=il(),r=ol();function o(n,s){function a(c,u,d,p){try{var g=n[c](u),f=g.value;return f instanceof t?s.resolve(f.v).then(function(b){a("next",b,d,p)},function(b){a("throw",b,d,p)}):s.resolve(f).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,p)})}catch(b){p(b)}}var l;this.next||(r(o.prototype),r(o.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new s(function(g,f){a(c,d,g,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),ll=pe((i,e)=>{le(),ue(),ce();var t=sl(),r=al();function o(n,s,a,l,c){return new r(t().w(n,s,a,l),c||Promise)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Qu=pe((i,e)=>{le(),ue(),ce();var t=ll();function r(o,n,s,a,l){var c=t(o,n,s,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}),Xu=pe((i,e)=>{le(),ue(),ce();function t(r){var o=Object(r),n=[];for(var s in o)n.unshift(s);return function a(){for(;n.length;)if((s=n.pop())in o)return a.value=s,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Zu=pe((i,e)=>{le(),ue(),ce();var t=Xr().default;function r(o){if(o!=null){var n=o[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(n)return n.call(o);if(typeof o.next=="function")return o;if(!isNaN(o.length))return{next:function(){return o&&s>=o.length&&(o=void 0),{value:o&&o[s++],done:!o}}}}throw new TypeError(t(o)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ed=pe((i,e)=>{le(),ue(),ce();var t=il(),r=sl(),o=Qu(),n=ll(),s=al(),a=Xu(),l=Zu();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(_){w||(w={stop:function(){return m(_.a,2)},catch:function(){return _.v},abrupt:function(x,v){return m(_.a,f[x],v)},delegateYield:function(x,v,S){return w.resultName=v,m(_.d,l(x),S)},finish:function(x){return m(_.f,x)}},m=function(x,v,S){_.p=w.prev,_.n=w.next;try{return x(v,S)}finally{w.next=_.n}}),w.resultName&&(w[w.resultName]=_.v,w.resultName=void 0),w.sent=_.v,w.next=_.n;try{return y.call(this,w)}finally{_.p=w.prev,_.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,_){return u.w(b(y),w,m,_&&_.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:s,async:function(y,w,m,_,x){return(g(w)?n:o)(b(y),w,m,_,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}),td=pe((i,e)=>{le(),ue(),ce();var t=ed()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),rd=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Hu(),Yu(),nl(),Ju(),td()):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,o,n,s,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%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(_){var x=_.call;return s(a.mark(function v(){var S,E,I,P;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return S=new MessageChannel,E=S.port1,I=S.port2,O.next=1,x("connect",{port:E},[E]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(_){var x=_.call;return(function(){var v=s(a.mark(function S(E){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(E),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,x("disconnect",{portId:I});case 2:case"end":return P.stop()}},S)}));return function(S){return v.apply(this,arguments)}})()},isSupported:function(_){var x=_.call;return function(){return x("isSupported")}}})};function g(m,_){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);_&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function f(m){for(var _=1;_<arguments.length;_++){var x=arguments[_]!=null?arguments[_]:{};_%2?g(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):g(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var b=new WeakMap,y=function(m){if(b.has(m))return b.get(m);var _=new Map;return b.set(m,_),_},w=function(m){var _=p(m);return function(x){var v=y(x);x.addEventListener("message",function(U){var D=U.data,oe=D.id;if(oe!==null&&v.has(oe)){var z=v.get(oe),H=z.reject,te=z.resolve;v.delete(oe),D.error===void 0?te(D.result):H(new Error(D.error.message))}}),l(x)&&x.start();for(var S=function(U){var D=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(z,H){var te=n.generateUniqueNumber(v);v.set(te,{reject:H,resolve:z}),D===null?x.postMessage({id:te,method:U},oe):x.postMessage({id:te,method:U,params:D},oe)})},E=function(U,D){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:U,params:D},oe)},I={},P=0,O=Object.entries(_);P<O.length;P++){var B=o(O[P],2),T=B[0],L=B[1];I=f(f({},I),{},r({},T,L({call:S,notify:E})))}return f({},I)}};t.createBroker=w})}),nd=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Xr(),rd(),nl()):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,o,n){var s=new Map([[0,null]]),a=new Map([[0,null]]),l=o.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){s.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,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);s.set(m,w);var _=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var x=s.get(m);if(x===void 0)throw new Error("The timer is in an undefined state.");x===w&&(p.apply(void 0,b),s.get(m)===w&&_())})};return _(),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,b=new Array(f>2?f-2:0),y=2;y<f;y++)b[y-2]=arguments[y];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 _=a.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(a.delete(m),p.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),id=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,nd()):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 o=function(d,p){var g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(f);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),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)})()})();`,s=o(r.load,n),a=function(d){return s().clearInterval(d)},l=function(d){return s().clearTimeout(d)},c=function(){var d;return(d=s()).setInterval.apply(d,arguments)},u=function(){var d;return(d=s()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Zr=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&&Ne?.versions?!Object.prototype.hasOwnProperty.call(Ne.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",o=e()||t()||r();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=o}),od=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 o=id(),n=r(Zr()),s={set:o.setInterval,clear:o.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return s;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?s:a}};i.default=l}),cl=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=e(od()),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(o,n){this.client=o,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(o.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(o){if(o*=1e3,isNaN(o)||o<=0||o>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${o}`);this._keepalive=o,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${o}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let o=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+o,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,S,E,I){I===void 0&&(I=E);var P=Object.getOwnPropertyDescriptor(S,E);(!P||("get"in P?!S.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return S[E]}}),Object.defineProperty(v,I,P)}:function(v,S,E,I){I===void 0&&(I=E),v[I]=S[E]}),t=i&&i.__setModuleDefault||(Object.create?function(v,S){Object.defineProperty(v,"default",{enumerable:!0,value:S})}:function(v,S){v.default=S}),r=i&&i.__importStar||(function(){var v=function(S){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var P in E)Object.prototype.hasOwnProperty.call(E,P)&&(I[I.length]=P);return I},v(S)};return function(S){if(S&&S.__esModule)return S;var E={};if(S!=null)for(var I=v(S),P=0;P<I.length;P++)I[P]!=="default"&&e(E,S,I[P]);return t(E,S),E}})(),o=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=o(mu()),s=Bt(),a=o(bu()),l=o(gt()),c=r(Da()),u=o(Ba()),d=o(Du()),p=o(rl()),g=o(Bu()),f=Jt(),b=Fu(),y=o(cl()),w=r(Zr()),m=globalThis.setImmediate||((...v)=>{let S=v.shift();(0,f.nextTick)(()=>{S(...v)})}),_={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 Ei extends b.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(S,E){super(),this.options=E||{};for(let I in _)typeof this.options[I]>"u"?this.options[I]=_[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Ei.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:Ei.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=S,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,P=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let B=null;if(!O){this._resubscribe();return}B=O.packet,this.log("deliver :: call _sendPacket for %o",B);let T=!0;B.messageId&&B.messageId!==0&&(this.messageIdProvider.register(B.messageId)||(T=!1)),T?this._sendPacket(B,L=>{O.cb&&O.cb(L),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",B.messageId),P())};this.log("connect :: sending queued packets"),P()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(S,E){E()}handleMessage(S,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let S=new s.Writable,E=n.default.parser(this.options),I=null,P=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),E.on("packet",U=>{this.log("parser :: on packet push to packets array."),P.push(U)});let O=()=>{this.log("work :: getting next packet in queue");let U=P.shift();if(U)this.log("work :: packet pulled from queue"),(0,d.default)(this,U,B);else{this.log("work :: no packets in queue");let D=I;I=null,this.log("work :: done flag is %s",!!D),D&&D()}},B=()=>{if(P.length)(0,f.nextTick)(O);else{let U=I;I=null,U()}};S._write=(U,D,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(U),O()};let T=U=>{this.log("streamErrorHandler :: error",U.message),U.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",U)):this.noop(U)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(S),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 L={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&&(L.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(L.properties||(L.properties={}),this.topicAliasRecv&&(L.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(L),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 U={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(U)}}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(S,E,I,P){this.log("publish :: message `%s` to topic `%s`",E,S);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:B,retain:T,dup:L,properties:U,cbStorePut:D}=I;if(this._checkDisconnecting(P))return this;let oe=()=>{let z=0;if((B===1||B===2)&&(z=this._nextId(),z===null))return this.log("No messageId left"),!1;let H={cmd:"publish",topic:S,payload:E,qos:B,retain:T,messageId:z,dup:L};switch(O.protocolVersion===5&&(H.properties=U),this.log("publish :: qos",B),B){case 1:case 2:this.outgoing[H.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",H.cmd),this._sendPacket(H,void 0,D);break;default:this.log("MqttClient:publish: packet cmd: %s",H.cmd),this._sendPacket(H,P,D);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(S,E,I){return new Promise((P,O)=>{this.publish(S,E,I,(B,T)=>{B?O(B):P(T)})})}subscribe(S,E,I){let P=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let O=!1,B=[];typeof S=="string"?(S=[S],B=S):Array.isArray(S)?B=S:typeof S=="object"&&(O=S.resubscribe,delete S.resubscribe,B=Object.keys(S));let T=c.validateTopics(B);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let L={qos:0};P===5&&(L.nl=!1,L.rap=!1,L.rh=0),E={...L,...E};let{properties:U}=E,D=[],oe=(te,F)=>{if(F=F||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,te)||this._resubscribeTopics[te].qos<F.qos||O){let X={topic:te,qos:F.qos};P===5&&(X.nl=F.nl,X.rap=F.rap,X.rh=F.rh,X.properties=U),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",X.topic,X.qos),D.push(X)}};if(Array.isArray(S)?S.forEach(te=>{this.log("subscribe: array topic %s",te),oe(te)}):Object.keys(S).forEach(te=>{this.log("subscribe: object topic %s, %o",te,S[te]),oe(te,S[te])}),!D.length)return I(null,[]),this;let z=(te,F)=>{let X={cmd:"subscribe",subscriptions:te,messageId:F};if(U&&(X.properties=U),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];te.forEach(be=>{if(this.options.reconnectPeriod>0){let re={qos:be.qos};P===5&&(re.nl=be.nl||!1,re.rap=be.rap||!1,re.rh=be.rh||0,re.properties=be.properties),this._resubscribeTopics[be.topic]=re,J.push(be.topic)}}),this.messageIdToTopic[X.messageId]=J}let M=new Promise((J,be)=>{this.outgoing[X.messageId]={volatile:!0,cb(re,we){if(!re){let{granted:G}=we;for(let j=0;j<G.length;j+=1)te[j].qos=G[j]}re?be(new f.ErrorWithSubackPacket(re.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(X),M},H=()=>{let te=this.options.subscribeBatchSize??D.length,F=[];for(let X=0;X<D.length;X+=te){let M=D.slice(X,X+te),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;F.push(z(M,J))}return Promise.all(F).then(X=>{I(null,D,X.at(-1))}).catch(X=>{I(X,D,X.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!H())&&this._storeProcessingQueue.push({invoke:H,callback:I}),this}subscribeAsync(S,E){return new Promise((I,P)=>{this.subscribe(S,E,(O,B)=>{O?P(O):I(B)})})}unsubscribe(S,E,I){typeof S=="string"&&(S=[S]),typeof E=="function"&&(I=E),I=I||this.noop;let P=c.validateTopics(S);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let B=this._nextId();if(B===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:B,unsubscriptions:[]};return typeof S=="string"?T.unsubscriptions=[S]:Array.isArray(S)&&(T.unsubscriptions=S),this.options.resubscribe&&T.unsubscriptions.forEach(L=>{delete this._resubscribeTopics[L]}),typeof E=="object"&&E.properties&&(T.properties=E.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(S,E){return new Promise((I,P)=>{this.unsubscribe(S,E,(O,B)=>{O?P(O):I(B)})})}end(S,E,I){this.log("end :: (%s)",this.options.clientId),(S==null||typeof S!="boolean")&&(I=I||E,E=S,S=!1),typeof E!="object"&&(I=I||E,E=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(B=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let L=B||T;this.log("end :: closeStores: invoking callback with args"),I(L)}})}),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,S),this._cleanUp(S,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(P)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!S&&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(S,E){return new Promise((I,P)=>{this.end(S,E,O=>{O?P(O):I()})})}removeOutgoingMessage(S){if(this.outgoing[S]){let{cb:E}=this.outgoing[S];this._removeOutgoingAndStoreMessage(S,()=>{E(new Error("Message removed"))})}return this}reconnect(S){this.log("client reconnect");let E=()=>{S?(this.options.incomingStore=S.incomingStore,this.options.outgoingStore=S.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(S=>{this.outgoing[S].volatile&&typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(S=>{typeof this.outgoing[S].cb=="function"&&(this.outgoing[S].cb(new Error("Connection closed")),delete this.outgoing[S])}))}_removeTopicAliasAndRecoverTopicName(S){let E;S.properties&&(E=S.properties.topicAlias);let I=S.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");S.topic=I}E&&delete S.properties.topicAlias}_checkDisconnecting(S){return this.disconnecting&&(S&&S!==this.noop?S(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(S,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",S),S)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let P={cmd:"disconnect",...I};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(P,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),m(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),E&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",E),E())}_storeAndSend(S,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",S.cmd);let P=S,O;if(P.cmd==="publish"&&(P=(0,a.default)(S),O=this._removeTopicAliasAndRecoverTopicName(P),O))return E&&E(O);this.outgoingStore.put(P,B=>{if(B)return E&&E(B);I(),this._writePacket(S,E)})}_applyTopicAlias(S){if(this.options.protocolVersion===5&&S.cmd==="publish"){let E;S.properties&&(E=S.properties.topicAlias);let I=S.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?(S.topic="",S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),S.properties={...S.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(S.topic="",S.properties={...S.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(S){this.log("noop ::",S)}_writePacket(S,E){this.log("_writePacket :: packet: %O",S),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",S),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(S,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(S,E,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let O=this._applyTopicAlias(S);if(O){E(O);return}if(!this.connected){if(S.cmd==="auth"){this._writePacket(S,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(S,E,I);return}if(P){this._writePacket(S,E);return}switch(S.cmd){case"publish":break;case"pubrel":this._storeAndSend(S,E,I);return;default:this._writePacket(S,E);return}switch(S.qos){case 2:case 1:this._storeAndSend(S,E,I);break;default:this._writePacket(S,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(S,E,I){this.log("_storePacket :: packet: %o",S),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let P=S;if(P.cmd==="publish"){P=(0,a.default)(S);let B=this._removeTopicAliasAndRecoverTopicName(P);if(B)return E&&E(B)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:E}):O>0?(E=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,B=>{if(B)return E&&E(B);I()})):E&&E(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(S=!1){this.keepaliveManager&&this.options.keepalive&&(S||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 S=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&S.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<S.length;E++){let I={};I[S[E]]=this._resubscribeTopics[S[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[S[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(S){if(this.disconnected){this.emit("connect",S);return}this.connackPacket=S,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),P=()=>{I.destroy(),I=null,this._flushStoreProcessingQueue(),O()},O=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",P),I.on("error",T=>{O(),this._flushStoreProcessingQueue(),this.removeListener("close",P),this.emit("error",T)});let B=()=>{if(!I)return;let T=I.read(1),L;if(!T){I.once("readable",B);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){B();return}!this.disconnecting&&!this.reconnectTimer?(L=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(U,D){L&&L(U,D),B()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let L in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[L]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",S)):E()}),B()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let S=this._storeProcessingQueue[0];if(S&&S.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let S of this._storeProcessingQueue)S.cbStorePut&&S.cbStorePut(new Error("Connection closed")),S.callback&&S.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(S,E){delete this.outgoing[S],this.outgoingStore.del({messageId:S},(I,P)=>{E(I,P),this.messageIdProvider.deallocate(S),this._invokeStoreProcessingQueue()})}};i.default=x}),sd=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=tl(),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 ad(){if(Ai)return _r;Ai=!0;let i=2147483647,e=36,t=1,r=26,o=38,n=700,s=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,b=String.fromCharCode;function y(O){throw new RangeError(p[O])}function w(O,B){let T=[],L=O.length;for(;L--;)T[L]=B(O[L]);return T}function m(O,B){let T=O.split("@"),L="";T.length>1&&(L=T[0]+"@",O=T[1]),O=O.replace(d,".");let U=O.split("."),D=w(U,B).join(".");return L+D}function _(O){let B=[],T=0,L=O.length;for(;T<L;){let U=O.charCodeAt(T++);if(U>=55296&&U<=56319&&T<L){let D=O.charCodeAt(T++);(D&64512)==56320?B.push(((U&1023)<<10)+(D&1023)+65536):(B.push(U),T--)}else B.push(U)}return B}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},S=function(O,B){return O+22+75*(O<26)-((B!=0)<<5)},E=function(O,B,T){let L=0;for(O=T?f(O/n):O>>1,O+=f(O/B);O>g*r>>1;L+=e)O=f(O/g);return f(L+(g+1)*O/(O+o))},I=function(O){let B=[],T=O.length,L=0,U=a,D=s,oe=O.lastIndexOf(l);oe<0&&(oe=0);for(let z=0;z<oe;++z)O.charCodeAt(z)>=128&&y("not-basic"),B.push(O.charCodeAt(z));for(let z=oe>0?oe+1:0;z<T;){let H=L;for(let F=1,X=e;;X+=e){z>=T&&y("invalid-input");let M=v(O.charCodeAt(z++));M>=e&&y("invalid-input"),M>f((i-L)/F)&&y("overflow"),L+=M*F;let J=X<=D?t:X>=D+r?r:X-D;if(M<J)break;let be=e-J;F>f(i/be)&&y("overflow"),F*=be}let te=B.length+1;D=E(L-H,te,H==0),f(L/te)>i-U&&y("overflow"),U+=f(L/te),L%=te,B.splice(L++,0,U)}return String.fromCodePoint(...B)},P=function(O){let B=[];O=_(O);let T=O.length,L=a,U=0,D=s;for(let H of O)H<128&&B.push(b(H));let oe=B.length,z=oe;for(oe&&B.push(l);z<T;){let H=i;for(let F of O)F>=L&&F<H&&(H=F);let te=z+1;H-L>f((i-U)/te)&&y("overflow"),U+=(H-L)*te,L=H;for(let F of O)if(F<L&&++U>i&&y("overflow"),F===L){let X=U;for(let M=e;;M+=e){let J=M<=D?t:M>=D+r?r:M-D;if(X<J)break;let be=X-J,re=e-J;B.push(b(S(J+be%re,0))),X=f(be/re)}B.push(b(S(X,0))),D=E(U,te,z===oe),U=0,++z}++U,++L}return B.join("")};return _r={version:"2.3.1",ucs2:{decode:_,encode:x},decode:I,encode:P,toASCII:function(O){return m(O,function(B){return u.test(B)?"xn--"+P(B):B})},toUnicode:function(O){return m(O,function(B){return c.test(B)?I(B.slice(4).toLowerCase()):B})}},_r}var _r,Ai,At,ld=Je(()=>{le(),ue(),ce(),_r={},Ai=!1,At=ad(),At.decode,At.encode,At.toASCII,At.toUnicode,At.ucs2,At.version});function cd(){return Ti||(Ti=!0,Ii=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 o=Object.getOwnPropertySymbols(i);if(o.length!==1||o[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}),Ii}function ud(){return Pi||(Pi=!0,Ci=Error),Ci}function dd(){return Mi||(Mi=!0,Oi=EvalError),Oi}function hd(){return Ri||(Ri=!0,Li=RangeError),Li}function fd(){return ji||(ji=!0,Ni=ReferenceError),Ni}function ul(){return Di||(Di=!0,Ui=SyntaxError),Ui}function hr(){return Fi||(Fi=!0,Bi=TypeError),Bi}function pd(){return qi||(qi=!0,$i=URIError),$i}function md(){if(Hi)return kr;Hi=!0;var i=typeof Symbol<"u"&&Symbol,e=cd();return kr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},kr}function gd(){if(Wi)return xr;Wi=!0;var i={__proto__:null,foo:{}},e=Object;return xr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},xr}function bd(){if(zi)return Sr;zi=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",o=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},s=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 Sr=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 y=l.apply(this,o(c,arguments));return Object(y)===y?y:this}return l.apply(a,o(c,arguments))},p=t(0,l.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+s(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var b=function(){};b.prototype=l.prototype,u.prototype=new b,b.prototype=null}return u},Sr}function xo(){if(Vi)return Er;Vi=!0;var i=bd();return Er=Function.prototype.bind||i,Er}function yd(){if(Ki)return Ar;Ki=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=xo();return Ar=t.call(i,e),Ar}function Qt(){if(Gi)return Ir;Gi=!0;var i,e=ud(),t=dd(),r=hd(),o=fd(),n=ul(),s=hr(),a=pd(),l=Function,c=function(z){try{return l('"use strict"; return ('+z+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new s},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=md()(),f=gd()(),b=Object.getPrototypeOf||(f?function(z){return z.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?i:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%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%":y,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?i:b(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%":o,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?i:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):i,"%Symbol%":g?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":s,"%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(b)try{null.error}catch(z){var _=b(b(z));m["%Error.prototype%"]=_}var x=function z(H){var te;if(H==="%AsyncFunction%")te=c("async function () {}");else if(H==="%GeneratorFunction%")te=c("function* () {}");else if(H==="%AsyncGeneratorFunction%")te=c("async function* () {}");else if(H==="%AsyncGenerator%"){var F=z("%AsyncGeneratorFunction%");F&&(te=F.prototype)}else if(H==="%AsyncIteratorPrototype%"){var X=z("%AsyncGenerator%");X&&b&&(te=b(X.prototype))}return m[H]=te,te},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"]},S=xo(),E=yd(),I=S.call(Function.call,Array.prototype.concat),P=S.call(Function.apply,Array.prototype.splice),O=S.call(Function.call,String.prototype.replace),B=S.call(Function.call,String.prototype.slice),T=S.call(Function.call,RegExp.prototype.exec),L=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,U=/\\(\\)?/g,D=function(z){var H=B(z,0,1),te=B(z,-1);if(H==="%"&&te!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(te==="%"&&H!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var F=[];return O(z,L,function(X,M,J,be){F[F.length]=J?O(be,U,"$1"):M||X}),F},oe=function(z,H){var te=z,F;if(E(v,te)&&(F=v[te],te="%"+F[0]+"%"),E(m,te)){var X=m[te];if(X===y&&(X=x(te)),typeof X>"u"&&!H)throw new s("intrinsic "+z+" exists, but is not available. Please file an issue!");return{alias:F,name:te,value:X}}throw new n("intrinsic "+z+" does not exist!")};return Ir=function(z,H){if(typeof z!="string"||z.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof H!="boolean")throw new s('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,z)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var te=D(z),F=te.length>0?te[0]:"",X=oe("%"+F+"%",H),M=X.name,J=X.value,be=!1,re=X.alias;re&&(F=re[0],P(te,I([0,1],re)));for(var we=1,G=!0;we<te.length;we+=1){var j=te[we],ne=B(j,0,1),V=B(j,-1);if((ne==='"'||ne==="'"||ne==="`"||V==='"'||V==="'"||V==="`")&&ne!==V)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!G)&&(be=!0),F+="."+j,M="%"+F+"%",E(m,M))J=m[M];else if(J!=null){if(!(j in J)){if(!H)throw new s("base intrinsic for "+z+" exists, but the property is not available.");return}if(u&&we+1>=te.length){var Y=u(J,j);G=!!Y,G&&"get"in Y&&!("originalValue"in Y.get)?J=Y.get:J=J[j]}else G=E(J,j),J=J[j];G&&!be&&(m[M]=J)}}return J},Ir}function So(){if(Yi)return Tr;Yi=!0;var i=Qt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Tr=e,Tr}function dl(){if(Ji)return Cr;Ji=!0;var i=Qt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Cr=e,Cr}function vd(){if(Qi)return Pr;Qi=!0;var i=So(),e=ul(),t=hr(),r=dl();return Pr=function(o,n,s){if(!o||typeof o!="object"&&typeof o!="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(o,n);if(i)i(o,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:s,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)o[n]=s;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Pr}function wd(){if(Xi)return Or;Xi=!0;var i=So(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Or=e,Or}function _d(){if(Zi)return Mr;Zi=!0;var i=Qt(),e=vd(),t=wd()(),r=dl(),o=hr(),n=i("%Math.floor%");return Mr=function(s,a){if(typeof s!="function")throw new o("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new o("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in s&&r){var d=r(s,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(s,"length",a,!0,!0):e(s,"length",a)),s},Mr}function kd(){if(eo)return Wt;eo=!0;var i=xo(),e=Qt(),t=_d(),r=hr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||i.call(n,o),a=So(),l=e("%Math.max%");Wt=function(u){if(typeof u!="function")throw new r("a function is required");var d=s(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return s(i,o,arguments)};return a?a(Wt,"apply",{value:c}):Wt.apply=c,Wt}function xd(){if(to)return Lr;to=!0;var i=Qt(),e=kd(),t=e(i("String.prototype.indexOf"));return Lr=function(r,o){var n=i(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Lr}var Ii,Ti,Ci,Pi,Oi,Mi,Li,Ri,Ni,ji,Ui,Di,Bi,Fi,$i,qi,kr,Hi,xr,Wi,Sr,zi,Er,Vi,Ar,Ki,Ir,Gi,Tr,Yi,Cr,Ji,Pr,Qi,Or,Xi,Mr,Zi,Wt,eo,Lr,to,Sd=Je(()=>{le(),ue(),ce(),Ii={},Ti=!1,Ci={},Pi=!1,Oi={},Mi=!1,Li={},Ri=!1,Ni={},ji=!1,Ui={},Di=!1,Bi={},Fi=!1,$i={},qi=!1,kr={},Hi=!1,xr={},Wi=!1,Sr={},zi=!1,Er={},Vi=!1,Ar={},Ki=!1,Ir={},Gi=!1,Tr={},Yi=!1,Cr={},Ji=!1,Pr={},Qi=!1,Or={},Xi=!1,Mr={},Zi=!1,Wt={},eo=!1,Lr={},to=!1});function Eo(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Ed(){!jt||!Rt||(jt=!1,Rt.length?ct=Rt.concat(ct):lr=-1,ct.length&&hl())}function hl(){if(!jt){var i=setTimeout(Ed,0);jt=!0;for(var e=ct.length;e;){for(Rt=ct,ct=[];++lr<e;)Rt&&Rt[lr].run();lr=-1,e=ct.length}Rt=null,jt=!1,clearTimeout(i)}}function Ad(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];ct.push(new fl(i,e)),ct.length===1&&!jt&&setTimeout(hl,0)}function fl(i,e){this.fun=i,this.array=e}function We(){}function Id(i){Eo("_linkedBinding")}function Td(i){Eo("dlopen")}function Cd(){return[]}function Pd(){return[]}function Od(i,e){if(!i)throw new Error(e||"assertion error")}function Md(){return!1}function Ld(){return pt.now()/1e3}function nn(i){var e=Math.floor((Date.now()-pt.now())*.001),t=pt.now()*.001,r=Math.floor(t)+e,o=Math.floor(t%1*1e9);return i&&(r=r-i[0],o=o-i[1],o<0&&(r--,o+=Rr)),[r,o]}function kt(){return Ao}function Rd(i){return[]}var ct,jt,Rt,lr,Bo,Fo,$o,qo,Ho,Wo,zo,Vo,Ko,Go,Yo,Jo,Qo,Xo,Zo,es,ts,rs,ns,is,os,mr,ss,as,ls,cs,us,ds,hs,fs,ps,ms,gs,bs,ys,vs,ws,_s,ks,xs,Ss,Es,As,Is,Ts,Cs,Ps,pt,on,Rr,Os,Ms,Ls,Rs,Ns,js,Us,Ds,Bs,Fs,$s,Ao,pl=Je(()=>{le(),ue(),ce(),ct=[],jt=!1,lr=-1,fl.prototype.run=function(){this.fun.apply(null,this.array)},Bo="browser",Fo="x64",$o="browser",qo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ho=["/usr/bin/node"],Wo=[],zo="v16.8.0",Vo={},Ko=function(i,e){console.warn((e?e+": ":"")+i)},Go=function(i){Eo("binding")},Yo=function(i){return 0},Jo=function(){return"/"},Qo=function(i){},Xo={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Zo=We,es=[],ts={},rs=!1,ns={},is=We,os=We,mr=function(){return{}},ss=mr,as=mr,ls=We,cs=We,us=We,ds={},hs={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},fs=We,ps=We,ms=We,gs=We,bs=We,ys=We,vs=We,ws=void 0,_s=void 0,ks=void 0,xs=We,Ss=2,Es=1,As="/bin/usr/node",Is=9229,Ts="node",Cs=[],Ps=We,pt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},pt.now===void 0&&(on=Date.now(),pt.timing&&pt.timing.navigationStart&&(on=pt.timing.navigationStart),pt.now=()=>Date.now()-on),Rr=1e9,nn.bigint=function(i){var e=nn(i);return typeof BigInt>"u"?e[0]*Rr+e[1]:BigInt(e[0]*Rr)+BigInt(e[1])},Os=10,Ms={},Ls=0,Rs=kt,Ns=kt,js=kt,Us=kt,Ds=kt,Bs=We,Fs=kt,$s=kt,Ao={version:zo,versions:Vo,arch:Fo,platform:$o,release:Xo,_rawDebug:Zo,moduleLoadList:es,binding:Go,_linkedBinding:Id,_events:Ms,_eventsCount:Ls,_maxListeners:Os,on:kt,addListener:Rs,once:Ns,off:js,removeListener:Us,removeAllListeners:Ds,emit:Bs,prependListener:Fs,prependOnceListener:$s,listeners:Rd,domain:ts,_exiting:rs,config:ns,dlopen:Td,uptime:Ld,_getActiveRequests:Cd,_getActiveHandles:Pd,reallyExit:is,_kill:os,cpuUsage:mr,resourceUsage:ss,memoryUsage:as,kill:ls,exit:cs,openStdin:us,allowedNodeEnvironmentFlags:ds,assert:Od,features:hs,_fatalExceptions:fs,setUncaughtExceptionCaptureCallback:ps,hasUncaughtExceptionCaptureCallback:Md,emitWarning:Ko,nextTick:Ad,_tickCallback:ms,_debugProcess:gs,_debugEnd:bs,_startProfilerIdleNotifier:ys,_stopProfilerIdleNotifier:vs,stdout:ws,stdin:ks,stderr:_s,abort:xs,umask:Yo,chdir:Qo,cwd:Jo,env:qo,title:Bo,argv:Ho,execArgv:Wo,pid:Ss,ppid:Es,execPath:As,debugPort:Is,hrtime:nn,argv0:Ts,_preload_modules:Cs,setSourceMapsEnabled:Ps}});function Nd(){if(ro)return Nr;ro=!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,s){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}}s&&(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,s){var a=s.dir||s.root,l=s.base||(s.name||"")+(s.ext||"");return a?a===s.root?a+l:a+n+l:l}var o={resolve:function(){for(var n="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,s=c.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var s=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&a&&(n+="/"),s?"/"+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,s=0;s<arguments.length;++s){var a=arguments[s];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":o.normalize(n)},relative:function(n,s){if(e(n),e(s),n===s||(n=o.resolve(n),s=o.resolve(s),n===s))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<s.length&&s.charCodeAt(u)===47;++u);for(var d=s.length,p=d-u,g=c<p?c:p,f=-1,b=0;b<=g;++b){if(b===g){if(p>g){if(s.charCodeAt(u+b)===47)return s.slice(u+b+1);if(b===0)return s.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?f=b:b===0&&(f=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(f=b)}var m="";for(b=a+f+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+f):(u+=f,s.charCodeAt(u)===47&&++u,s.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var s=n.charCodeAt(0),a=s===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(s=n.charCodeAt(u),s===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var d=s.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===s.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 s=-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?s===-1?s=d:u!==1&&(u=1):s!==-1&&(u=-1)}return s===-1||l===-1||u===0||u===1&&s===l-1&&s===a+1?"":n.slice(s,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 s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var a=n.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,f=n.length-1,b=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:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||p===-1||b===0||b===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?s.base=s.name=n.slice(1,p):s.base=s.name=n.slice(d,p)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,p)):(s.name=n.slice(d,u),s.base=n.slice(d,p)),s.ext=n.slice(u,p)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Nr=o,Nr}var Nr,ro,no,jd=Je(()=>{le(),ue(),ce(),pl(),Nr={},ro=!1,no=Nd()}),ml={};Gt(ml,{URL:()=>El,Url:()=>wl,default:()=>ze,fileURLToPath:()=>bl,format:()=>_l,parse:()=>Sl,pathToFileURL:()=>yl,resolve:()=>kl,resolveObject:()=>xl});function Ud(){if(io)return jr;io=!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,o=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=o&&n&&typeof n.get=="function"?n.get:null,a=o&&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,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,_=String.prototype.replace,x=String.prototype.toUpperCase,v=String.prototype.toLowerCase,S=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,B=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,U=typeof Symbol=="function"&&typeof Symbol.iterator=="object",D=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===U||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,z=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(K){return K.__proto__}:null);function H(K,ie){if(K===1/0||K===-1/0||K!==K||K&&K>-1e3&&K<1e3||S.call(/e/,ie))return ie;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof K=="number"){var Te=K<0?-O(-K):O(K);if(Te!==K){var Pe=String(Te),Me=m.call(ie,Pe.length+1);return _.call(Pe,Ie,"$&_")+"."+_.call(_.call(Me,/([0-9]{3})/g,"$&_"),/_$/,"")}}return _.call(ie,Ie,"$&_")}var te=vl,F=te.custom,X=Y(F)?F:null;jr=function K(ie,Ie,Te,Pe){var Me=Ie||{};if(se(Me,"quoteStyle")&&Me.quoteStyle!=="single"&&Me.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Me,"maxStringLength")&&(typeof Me.maxStringLength=="number"?Me.maxStringLength<0&&Me.maxStringLength!==1/0:Me.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var rt=se(Me,"customInspect")?Me.customInspect:!0;if(typeof rt!="boolean"&&rt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Me,"indent")&&Me.indent!==null&&Me.indent!==" "&&!(parseInt(Me.indent,10)===Me.indent&&Me.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Me,"numericSeparator")&&typeof Me.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var nt=Me.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,Me);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var qe=String(ie);return nt?H(ie,qe):qe}if(typeof ie=="bigint"){var it=String(ie)+"n";return nt?H(ie,it):it}var Ft=typeof Me.depth>"u"?5:Me.depth;if(typeof Te>"u"&&(Te=0),Te>=Ft&&Ft>0&&typeof ie=="object")return be(ie)?"[Array]":"[Object]";var ot=Z(Me,Te);if(typeof Pe>"u")Pe=[];else if(ee(Pe,ie)>=0)return"[Circular]";function Qe(st,_t,Ot){if(_t&&(Pe=P.call(Pe),Pe.push(_t)),Ot){var at={depth:Me.depth};return se(Me,"quoteStyle")&&(at.quoteStyle=Me.quoteStyle),K(st,at,Te+1,Pe)}return K(st,Me,Te+1,Pe)}if(typeof ie=="function"&&!we(ie)){var fr=q(ie),$t=ke(ie,Qe);return"[Function"+(fr?": "+fr:" (anonymous)")+"]"+($t.length>0?" { "+I.call($t,", ")+" }":"")}if(Y(ie)){var Xt=U?_.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):L.call(ie);return typeof ie=="object"&&!U?h(Xt):Xt}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),N=ie.attributes||[],_e=0;_e<N.length;_e++)C+=" "+N[_e].name+"="+M(J(N[_e].value),"double",Me);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(be(ie)){if(ie.length===0)return"[]";var Se=ke(ie,Qe);return ot&&!$(Se)?"["+de(Se,ot)+"]":"[ "+I.call(Se,", ")+" ]"}if(G(ie)){var Ae=ke(ie,Qe);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+Qe(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&&rt){if(X&&typeof ie[X]=="function"&&te)return te(ie,{depth:Ft-Te});if(rt!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Be=[];return r&&r.call(ie,function(st,_t){Be.push(Qe(_t,ie,!0)+" => "+Qe(st,ie))}),A("Map",t.call(ie),Be,ot)}if(W(ie)){var Ve=[];return a&&a.call(ie,function(st){Ve.push(Qe(st,ie))}),A("Set",s.call(ie),Ve,ot)}if(fe(ie))return k("WeakMap");if(me(ie))return k("WeakSet");if(ye(ie))return k("WeakRef");if(ne(ie))return h(Qe(Number(ie)));if(Q(ie))return h(Qe(B.call(ie)));if(V(ie))return h(f.call(ie));if(j(ie))return h(Qe(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Ur<"u"&&ie===Ur)return"{ [object globalThis] }";if(!re(ie)&&!we(ie)){var Ze=ke(ie,Qe),Zt=z?z(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,er=ie instanceof Object?"":"null prototype",tr=!Zt&&D&&Object(ie)===ie&&D in ie?m.call(R(ie),8,-1):er?"Object":"",pr=Zt||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Pt=pr+(tr||er?"["+I.call(E.call([],tr||[],er||[]),": ")+"] ":"");return Ze.length===0?Pt+"{}":ot?Pt+"{"+de(Ze,ot)+"}":Pt+"{ "+I.call(Ze,", ")+" }"}return String(ie)};function M(K,ie,Ie){var Te=(Ie.quoteStyle||ie)==="double"?'"':"'";return Te+K+Te}function J(K){return _.call(String(K),/"/g,""")}function be(K){return R(K)==="[object Array]"&&(!D||!(typeof K=="object"&&D in K))}function re(K){return R(K)==="[object Date]"&&(!D||!(typeof K=="object"&&D in K))}function we(K){return R(K)==="[object RegExp]"&&(!D||!(typeof K=="object"&&D in K))}function G(K){return R(K)==="[object Error]"&&(!D||!(typeof K=="object"&&D in K))}function j(K){return R(K)==="[object String]"&&(!D||!(typeof K=="object"&&D in K))}function ne(K){return R(K)==="[object Number]"&&(!D||!(typeof K=="object"&&D in K))}function V(K){return R(K)==="[object Boolean]"&&(!D||!(typeof K=="object"&&D in K))}function Y(K){if(U)return K&&typeof K=="object"&&K instanceof Symbol;if(typeof K=="symbol")return!0;if(!K||typeof K!="object"||!L)return!1;try{return L.call(K),!0}catch{}return!1}function Q(K){if(!K||typeof K!="object"||!B)return!1;try{return B.call(K),!0}catch{}return!1}var ge=Object.prototype.hasOwnProperty||function(K){return K in(this||Ur)};function se(K,ie){return ge.call(K,ie)}function R(K){return b.call(K)}function q(K){if(K.name)return K.name;var ie=w.call(y.call(K),/^function\s*([\w$]+)/);return ie?ie[1]:null}function ee(K,ie){if(K.indexOf)return K.indexOf(ie);for(var Ie=0,Te=K.length;Ie<Te;Ie++)if(K[Ie]===ie)return Ie;return-1}function he(K){if(!t||!K||typeof K!="object")return!1;try{t.call(K);try{s.call(K)}catch{return!0}return K instanceof Map}catch{}return!1}function fe(K){if(!c||!K||typeof K!="object")return!1;try{c.call(K,c);try{d.call(K,d)}catch{return!0}return K instanceof WeakMap}catch{}return!1}function ye(K){if(!g||!K||typeof K!="object")return!1;try{return g.call(K),!0}catch{}return!1}function W(K){if(!s||!K||typeof K!="object")return!1;try{s.call(K);try{t.call(K)}catch{return!0}return K instanceof Set}catch{}return!1}function me(K){if(!d||!K||typeof K!="object")return!1;try{d.call(K,d);try{c.call(K,c)}catch{return!0}return K instanceof WeakSet}catch{}return!1}function ve(K){return!K||typeof K!="object"?!1:typeof HTMLElement<"u"&&K instanceof HTMLElement?!0:typeof K.nodeName=="string"&&typeof K.getAttribute=="function"}function ae(K,ie){if(K.length>ie.maxStringLength){var Ie=K.length-ie.maxStringLength,Te="... "+Ie+" more character"+(Ie>1?"s":"");return ae(m.call(K,0,ie.maxStringLength),ie)+Te}var Pe=_.call(_.call(K,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return M(Pe,"single",ie)}function Oe(K){var ie=K.charCodeAt(0),Ie={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ie?"\\"+Ie:"\\x"+(ie<16?"0":"")+x.call(ie.toString(16))}function h(K){return"Object("+K+")"}function k(K){return K+" { ? }"}function A(K,ie,Ie,Te){var Pe=Te?de(Ie,Te):I.call(Ie,", ");return K+" ("+ie+") {"+Pe+"}"}function $(K){for(var ie=0;ie<K.length;ie++)if(ee(K[ie],`
|
|
4
|
+
`)>=0)return!1;return!0}function Z(K,ie){var Ie;if(K.indent===" ")Ie=" ";else if(typeof K.indent=="number"&&K.indent>0)Ie=I.call(Array(K.indent+1)," ");else return null;return{base:Ie,prev:I.call(Array(ie+1),Ie)}}function de(K,ie){if(K.length===0)return"";var Ie=`
|
|
5
|
+
`+ie.prev+ie.base;return Ie+I.call(K,","+Ie)+`
|
|
6
|
+
`+ie.prev}function ke(K,ie){var Ie=be(K),Te=[];if(Ie){Te.length=K.length;for(var Pe=0;Pe<K.length;Pe++)Te[Pe]=se(K,Pe)?ie(K[Pe],K):""}var Me=typeof T=="function"?T(K):[],rt;if(U){rt={};for(var nt=0;nt<Me.length;nt++)rt["$"+Me[nt]]=Me[nt]}for(var qe in K)se(K,qe)&&(Ie&&String(Number(qe))===qe&&qe<K.length||U&&rt["$"+qe]instanceof Symbol||(S.call(/[^\w$]/,qe)?Te.push(ie(qe,K)+": "+ie(K[qe],K)):Te.push(qe+": "+ie(K[qe],K))));if(typeof T=="function")for(var it=0;it<Me.length;it++)oe.call(K,Me[it])&&Te.push("["+ie(Me[it])+"]: "+ie(K[Me[it]],K));return Te}return jr}function Dd(){if(oo)return Dr;oo=!0;var i=Qt(),e=xd(),t=Ud(),r=hr(),o=i("%WeakMap%",!0),n=i("%Map%",!0),s=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(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},g=function(y,w){var m=p(y,w);return m&&m.value},f=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return Dr=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return s(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},Dr}function Io(){if(so)return Br;so=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Br={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Br}function gl(){if(ao)return Fr;ao=!0;var i=Io(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},s=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.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,_)),t(w)&&t(m)?(m.forEach(function(v,S){if(e.call(w,S)){var E=w[S];E&&typeof E=="object"&&v&&typeof v=="object"?w[S]=y(E,v,_):w.push(v)}else w[S]=v}),w):Object.keys(m).reduce(function(v,S){var E=m[S];return e.call(v,S)?v[S]=y(v[S],E,_):v[S]=E,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var S="",E=0;E<v.length;E+=c){for(var I=v.length>=c?v.slice(E,E+c):v,P=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||x===i.RFC1738&&(B===40||B===41)){P[P.length]=I.charAt(O);continue}if(B<128){P[P.length]=r[B];continue}if(B<2048){P[P.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){P[P.length]=r[224|B>>12]+r[128|B>>6&63]+r[128|B&63];continue}O+=1,B=65536+((B&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}S+=P.join("")}return S},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],S=Object.keys(v),E=0;E<S.length;++E){var I=S[E],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Fr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:s},Fr}function Bd(){if(lo)return $r;lo=!0;var i=Dd(),e=gl(),t=Io(),r=Object.prototype.hasOwnProperty,o={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},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(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,_,x,v,S,E,I,P,O,B,T,L,U,D,oe,z){for(var H=y,te=z,F=0,X=!1;(te=te.get(p))!==void 0&&!X;){var M=te.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");X=!0}typeof te.get(p)>"u"&&(F=0)}if(typeof P=="function"?H=P(w,H):H instanceof Date?H=T(H):m==="comma"&&n(H)&&(H=e.maybeMap(H,function(R){return R instanceof Date?T(R):R})),H===null){if(v)return I&&!D?I(w,u.encoder,oe,"key",L):w;H=""}if(d(H)||e.isBuffer(H)){if(I){var J=D?w:I(w,u.encoder,oe,"key",L);return[U(J)+"="+U(I(H,u.encoder,oe,"value",L))]}return[U(w)+"="+U(String(H))]}var be=[];if(typeof H>"u")return be;var re;if(m==="comma"&&n(H))D&&I&&(H=e.maybeMap(H,I)),re=[{value:H.length>0?H.join(",")||null:void 0}];else if(n(P))re=P;else{var we=Object.keys(H);re=O?we.sort(O):we}var G=E?w.replace(/\./g,"%2E"):w,j=_&&n(H)&&H.length===1?G+"[]":G;if(x&&n(H)&&H.length===0)return j+"[]";for(var ne=0;ne<re.length;++ne){var V=re[ne],Y=typeof V=="object"&&typeof V.value<"u"?V.value:H[V];if(!(S&&Y===null)){var Q=B&&E?V.replace(/\./g,"%2E"):V,ge=n(H)?typeof m=="function"?m(j,Q):j:j+(B?"."+Q:"["+Q+"]");z.set(y,F);var se=i();se.set(p,z),a(be,b(Y,ge,m,_,x,v,S,E,m==="comma"&&D&&n(H)?null:I,P,O,B,T,L,U,D,oe,se))}}return be},f=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.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 b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],_=u.filter;(typeof b.filter=="function"||n(b.filter))&&(_=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return $r=function(b,y){var w=b,m=f(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var S=o[m.arrayFormat],E=S==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=i(),P=0;P<_.length;++P){var O=_[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,S,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 B=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},$r}function Fd(){if(co)return qr;co=!0;var i=gl(),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},o=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},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var f={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,_,x=g.charset;if(g.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===s&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],S=v.indexOf("]="),E=S===-1?v.indexOf("="):S+1,I,P;E===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,x,"key"),P=i.maybeMap(n(v.slice(E+1),g),function(B){return g.decoder(B,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(f,I);O&&g.duplicates==="combine"?f[I]=i.combine(f[I],P):(!O||g.duplicates==="last")&&(f[I]=P)}return f},c=function(p,g,f,b){for(var y=b?g:n(g,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);else{m=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,S=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(S)&&_!==v&&String(S)===v&&S>=0&&f.parseArrays&&S<=f.arrayLimit?(m=[],m[S]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,f,b){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var S=0;f.depth>0&&(_=m.exec(y))!==null&&S<f.depth;){if(S+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,g,f,b)}},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 b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,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 qr=function(p,g){var f=d(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var _=w[m],x=u(_,b[_],f,typeof p=="string");y=i.merge(y,x,f)}return f.allowSparse===!0?y:i.compact(y)},qr}function $d(){if(uo)return Hr;uo=!0;var i=Bd(),e=Fd(),t=Io();return Hr={formats:t,parse:e,stringify:i},Hr}function qd(){if(ho)return It;ho=!0;var i=At;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]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
+
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),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},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=$d();function w(v,S,E){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,S,E),I}e.prototype.parse=function(v,S,E){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(P);var T=v;if(T=T.trim(),!E&&v.split("#").length===1){var L=o.exec(T);if(L)return this.path=T,this.href=T,this.pathname=L[1],L[2]?(this.search=L[2],S?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):S&&(this.search="",this.query={}),this}var U=t.exec(T);if(U){U=U[0];var D=U.toLowerCase();this.protocol=D,T=T.substr(U.length)}if(E||U||T.match(/^\/\/[^@/]+@[^@/]+/)){var oe=T.substr(0,2)==="//";oe&&!(U&&f[U])&&(T=T.substr(2),this.slashes=!0)}if(!f[U]&&(oe||U&&!b[U])){for(var z=-1,H=0;H<c.length;H++){var te=T.indexOf(c[H]);te!==-1&&(z===-1||te<z)&&(z=te)}var F,X;z===-1?X=T.lastIndexOf("@"):X=T.lastIndexOf("@",z),X!==-1&&(F=T.slice(0,X),T=T.slice(X+1),this.auth=decodeURIComponent(F)),z=-1;for(var H=0;H<l.length;H++){var te=T.indexOf(l[H]);te!==-1&&(z===-1||te<z)&&(z=te)}z===-1&&(z=T.length),this.host=T.slice(0,z),T=T.slice(z),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var J=this.hostname.split(/\./),H=0,be=J.length;H<be;H++){var re=J[H];if(re&&!re.match(d)){for(var we="",G=0,j=re.length;G<j;G++)re.charCodeAt(G)>127?we+="x":we+=re[G];if(!we.match(d)){var ne=J.slice(0,H),V=J.slice(H+1),Y=re.match(p);Y&&(ne.push(Y[1]),V.unshift(Y[2])),V.length&&(T="/"+V.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 Q=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+Q,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[D])for(var H=0,be=a.length;H<be;H++){var se=a[H];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),S&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):S&&(this.search="",this.query={}),T&&(this.pathname=T),b[D]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",he=this.search||"";this.path=Q+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 S=this.protocol||"",E=this.pathname||"",I=this.hash||"",P=!1,O="";this.host?P=v+this.host:this.hostname&&(P=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(P+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||O&&"?"+O||"";return S&&S.substr(-1)!==":"&&(S+=":"),this.slashes||(!S||b[S])&&P!==!1?(P="//"+(P||""),E&&E.charAt(0)!=="/"&&(E="/"+E)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),S+P+E+B+I};function _(v,S){return w(v,!1,!0).resolve(S)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,S){return v?w(v,!1,!0).resolveObject(S):S}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var S=new e;S.parse(v,!1,!0),v=S}for(var E=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];E[O]=this[O]}if(E.hash=v.hash,v.href==="")return E.href=E.format(),E;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var L=B[T];L!=="protocol"&&(E[L]=v[L])}return b[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(!b[v.protocol]){for(var U=Object.keys(v),D=0;D<U.length;D++){var oe=U[D];E[oe]=v[oe]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),E.pathname=be.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var z=E.pathname||"",H=E.search||"";E.path=z+H}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var te=E.pathname&&E.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",X=F||te||E.host&&v.pathname,M=X,J=E.pathname&&E.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],re=E.protocol&&!b[E.protocol];if(re&&(E.hostname="",E.port=null,E.host&&(J[0]===""?J[0]=E.host:J.unshift(E.host)),E.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),X=X&&(be[0]===""||J[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,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),E.search=v.search,E.query=v.query;else if(v.search!=null){if(re){E.host=J.shift(),E.hostname=E.host;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return E.search=v.search,E.query=v.query,(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E}if(!J.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var G=J.slice(-1)[0],j=(E.host||v.host||J.length>1)&&(G==="."||G==="..")||G==="",ne=0,V=J.length;V>=0;V--)G=J[V],G==="."?J.splice(V,1):G===".."?(J.splice(V,1),ne++):ne&&(J.splice(V,1),ne--);if(!X&&!M)for(;ne--;ne)J.unshift("..");X&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),j&&J.join("/").substr(-1)!=="/"&&J.push("");var Y=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(re){E.hostname=Y?"":J.length?J.shift():"",E.host=E.hostname;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return X=X||E.host&&J.length,X&&!Y&&J.unshift(""),J.length>0?E.pathname=J.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,S=r.exec(v);S&&(S=S[0],S!==":"&&(this.port=S.substr(1)),v=v.substr(0,v.length-S.length)),v&&(this.hostname=v)},It.parse=w,It.resolve=_,It.resolveObject=x,It.format=m,It.Url=e,It}function bl(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 Vr?Hd(i):Wd(i)}function Hd(i){let e=i.hostname,t=i.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Pl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<Tl||r>Cl||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Wd(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 yl(i){let e=no.resolve(i),t=i.charCodeAt(i.length-1);(t===Il||Vr&&t===Al)&&e[e.length-1]!==no.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Ol,"%25")),!Vr&&e.includes("\\")&&(e=e.replace(Ml,"%5C")),e.includes(`
|
|
8
|
+
`)&&(e=e.replace(Ll,"%0A")),e.includes("\r")&&(e=e.replace(Rl,"%0D")),e.includes(" ")&&(e=e.replace(Nl,"%09")),r.pathname=e,r}var vl,jr,io,Ur,Dr,oo,Br,so,Fr,ao,$r,lo,qr,co,Hr,uo,It,ho,ze,qs,wl,_l,kl,xl,Sl,El,Al,Il,Tl,Cl,Vr,Pl,Ol,Ml,Ll,Rl,Nl,zd=Je(()=>{le(),ue(),ce(),ld(),Sd(),jd(),pl(),vl=Object.freeze(Object.create(null)),jr={},io=!1,Ur=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Dr={},oo=!1,Br={},so=!1,Fr={},ao=!1,$r={},lo=!1,qr={},co=!1,Hr={},uo=!1,It={},ho=!1,ze=qd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,qs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=yl,ze.fileURLToPath=bl,wl=ze.Url,_l=ze.format,kl=ze.resolve,xl=ze.resolveObject,Sl=ze.parse,El=ze.URL,Al=92,Il=47,Tl=97,Cl=122,Vr=qs==="win32",Pl=/\//g,Ol=/%/g,Ml=/\\/g,Ll=/\n/g,Rl=/\r/g,Nl=/\t/g}),Vd=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")}}),To=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=Bt(),t=($e(),Re(Fe));function r(n,s){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",s)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,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,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};i.BufferedDuplex=o}),gr=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=($e(),Re(Fe)),r=e(Vd()),o=e(gt()),n=Bt(),s=e(Zr()),a=To(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}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={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),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 _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let _=d(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),S=r.default.createWebSocketStream(v,_.wsOptions);return S.url=x,v.on("close",()=>{S.destroy()}),S};i.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,S=!m.objectMode,E=f(w,m),I=O(m,D,oe);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{E.close()});let P=typeof E.addEventListener<"u";E.readyState===E.OPEN?(_=I,_.socket=E):(_=new a.BufferedDuplex(m,I,E),P?E.addEventListener("open",B):E.onopen=B),P?(E.addEventListener("close",T),E.addEventListener("error",L),E.addEventListener("message",U)):(E.onclose=T,E.onerror=L,E.onmessage=U);function O(z,H,te){let F=new n.Transform({objectMode:z.objectMode});return F._write=H,F._flush=te,F}function B(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(z){l("WebSocket onClose",z),_.end(),_.destroy()}function L(z){l("WebSocket onError",z);let H=new Error("WebSocket error");H.event=z,_.destroy(H)}async function U(z){if(!I||!I.readable||!I.writable)return;let{data:H}=z;H instanceof ArrayBuffer?H=t.Buffer.from(H):H instanceof Blob?H=t.Buffer.from(await new Response(H).arrayBuffer()):H=t.Buffer.from(H,"utf8"),I.push(H)}function D(z,H,te){if(E.bufferedAmount>x){setTimeout(D,v,z,H,te);return}S&&typeof z=="string"&&(z=t.Buffer.from(z,"utf8"));try{E.send(z)}catch(F){return te(F)}te()}function oe(z){E.close(),z()}return _};i.browserStreamBuilder=y}),Co={};Gt(Co,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>jl,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 jl,Ul=Je(()=>{le(),ue(),ce(),jl={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),Dl=pe((i,e)=>{le(),ue(),ce(),e.exports={}}),Hs=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((Ul(),Re(Co))),r=e(gt()),o=e(Dl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.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=s}),Bl={};Gt(Bl,{default:()=>Fl});var Fl,Kd=Je(()=>{le(),ue(),ce(),Fl={}}),Ws=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=(Kd(),Re(Bl)),r=e((Ul(),Re(Co))),o=e(gt()),n=e(Dl()),s=(0,o.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,s("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}),zs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Bt(),r=To(),o,n,s;function a(){let p=new t.Transform;return p._write=(g,f,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{o.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",b=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){o.onOpen(()=>{s.socketReady()}),o.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),o.onError(p=>{let g=new Error(p.errMsg);s.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 b=c(g,p);o=wx.connectSocket({url:b,protocols:[f]}),n=a(),s=new r.BufferedDuplex(g,n,o),s._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{o.close({fail(){s._destroy(w,m)}})},0),s),u(),s};i.default=d}),Vs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=($e(),Re(Fe)),t=Bt(),r=To(),o,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(f,b,y)=>{o.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},g._flush=f=>{o.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 b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,f)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{s.socketReady()}),o.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)}}),o.onSocketClose(()=>{s.end(),s.destroy()}),o.onSocketError(g=>{s.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 b=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,g);return o=f.my,o.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(f,n,o),d(),s};i.default=p}),Gd=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(gt()),r=e((zd(),Re(ml))),o=e(Si()),n=e(Zr());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var s=(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(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,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 Ne<"u"&&(p.socksProxy=Ne.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=gr().streamBuilder,a.wss=gr().streamBuilder,a.mqtt=Hs().default,a.tcp=Hs().default,a.ssl=Ws().default,a.tls=a.ssl,a.mqtts=Ws().default):(a.ws=gr().browserStreamBuilder,a.wss=gr().browserStreamBuilder,a.wx=zs().default,a.wxs=zs().default,a.ali=Vs().default,a.alis=Vs().default)),!a[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let f=new o.default(g,p);return f.on("error",()=>{}),f}function u(d,p,g=!0){return new Promise((f,b)=>{let y=c(d,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),b(_)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}i.default=c}),Ks=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,f,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(f,b);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[b]}}),Object.defineProperty(g,y,w)}:function(g,f,b,y){y===void 0&&(y=b),g[y]=f[b]}),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(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(f)};return function(f){if(f&&f.__esModule)return f;var b={};if(f!=null)for(var y=g(f),w=0;w<y.length;w++)y[w]!=="default"&&e(b,f,y[w]);return t(b,f),b}})(),o=i&&i.__exportStar||function(g,f){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(f,b)&&e(f,g,b)},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 s=n(Si());i.MqttClient=s.default;var a=n(rl());i.DefaultMessageIdProvider=a.default;var l=n(sd());i.UniqueMessageIdProvider=l.default;var c=n(Ba());i.Store=c.default;var u=r(Gd());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(cl());i.KeepaliveManager=d.default,i.Client=s.default,o(Si(),i),o(Jt(),i),o(Da(),i);var p=Qr();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Yd=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(s,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(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=i&&i.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=i&&i.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(Ks());i.default=n,o(Ks(),i)});const Jd=Yd();const Qd={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}/#"},Xd=300,Zd={templateId:"7",type:"link",isDeepLink:!0},eh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class $l{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={...Qd,...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,o={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&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,s)=>{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(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Jd.connect(this.config.mqttEndpoint,o),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[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=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 o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Zd,...this.config.fileTemplate??{},...th(t)},o={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??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Xd){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,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 o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.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 o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...eh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={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:o,senderFullname:o,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:s}}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,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function th(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function ql(i,e){return(i.sender??"").toString()===e}function Hl(i,e){const t=(i.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function Po(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 o=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=i.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Wl(i){const e=Po(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 o=r[0],n=o.action,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function Gs(i,e,t){const r=Hl(i,t),o=Po(i),n=Wl(i);let s="";o.innerMessage?s=o.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?o.contentType!=="300"&&(s=i.text):s=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"?rh(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function rh(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class zl extends mo{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 sa(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new aa,this.conversationManager=new ca(e.conversationId),this.usesAikaara()&&(this.connection=new oa(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 $l({...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 o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),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),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(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 o=r.map(l=>Gs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){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 o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);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 o=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:o.fileName,fileUrl:o.url,cloudFileId:o.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 o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,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 o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=Gs(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(ql(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);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:o,role:s.role==="tool"?"system":s.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||"",o=e.content||"";o?this.messageStore.updateStreaming(o):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,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ys={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 nh(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function ih(i,e,t){const r=nh(i.name||"");if(r&&e&&e[r])return e[r];const o=i.type;return o&&o.trim().length>0?o:r&&Ys[r]?Ys[r]:t}function sn(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function oh(i,e){const t=e.split(".");let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Vl(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=ih(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),s={fileName:o,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=sn(c,s),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=oh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,b=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(sn(JSON.stringify(i.registerBody??{}),s)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:i.viewerTemplate?sn(i.viewerTemplate,s):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Oo(i){return{async upload(e,t){const r=new FormData,o=i.fieldName??"file";r.append(o,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 s=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:s,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 sh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Kl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??sh;return{async fetchMessages(o,n){const s=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,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 ah="^[A-Z]{4}[0-9]{5}[A-Z]$",lh="^[A-Z]{4}0[A-Z0-9]{6}$",Gl="^[0-9]{6}$",ch={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"},uh={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:ah,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"},dh={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:Gl}]},{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"},hh={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"},fh={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"},ph={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"},mh={id:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureExpenditure",type:"number",label:"Expenditure on Agriculture",currency:"₹",min:0},{id:"agricultureLandGroup",type:"group",title:"Land Details",hint:"Optional - leave blank if you only need to report income",fields:[{id:"agricultureLandInAcre",type:"number",label:"Land Area (Acres)",min:0},{id:"agricultureLandDistrict",type:"text",label:"District"},{id:"agricultureLandPincode",type:"text",label:"Pincode",maxLength:6,pattern:Gl},{id:"agricultureLandOwner",type:"radio",label:"Ownership",options:[{value:"Owned",label:"Owned"},{value:"Held on lease",label:"Held on lease"}]},{id:"agricultureLandType",type:"radio",label:"Type of Land",options:[{value:"Irrigated",label:"Irrigated"},{value:"Rain-fed",label:"Rain-fed"}]}]}],submitLabel:"Save"},gh={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:lh,maxLength:11}]}],submitLabel:"Save"},bh=[uh,ph,hh,fh,ch,dh,mh,gh];function yh(i,e){const t=i||{},r={userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Mh()};r.us80cAmount=xe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=xe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=xe(t.us80dForParentsAmount),r.hasParentOverSixty=ur(t.hasParentOverSixty),r.preventiveHealthCheckUp=xe(t.preventiveHealthCheckUp),r.medicalExpenditure=xe(t.medicalExpenditure),r.savingBankInterest=xe(t.savingBankInterest),r.fdInterest=xe(t.fdInterest),r.dividend=xe(t.dividend),r.anyOtherIncome=xe(t.anyOtherIncome),r.cryptoSellValue=xe(t.cryptoSellPrice),r.cryptoPurchaseAmount=xe(t.cryptoPurchasePrice),r.vdaPurchaseCost=xe(t.cryptoPurchasePrice);const o=(xe(t.bizReceiptsBank)??0)+(xe(t.bizReceiptsCash)??0),n=(xe(t.profReceiptsBank)??0)+(xe(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||o>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?o||void 0:n||void 0,r.agricultureDetails={income:xe(t.agricultureIncome)},r.exemptIncomeAmount=xe(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),xe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(xe(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:xe(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=an(t.hpDetails,vh);l.length&&(r.hpDetails=l);const c=an(t.salaryDetails,wh);if(c.length){r.salaryIncome=c;const u=an(t.salaryDetails,p=>({grossSalary:xe(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=en(t.salaryDetails)[0]??{};r.hraAmount=xe(d.hraReceived),r.leaveTravelAllowanceAmount=xe(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=xe(d.leaveEncashment),r.anyOtherAllowanceAmount=xe(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return et(r)}function vh(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:Kr(i.sanctionDate),totalLoanAmount:xe(i.totalLoanAmount),loanOutstandingAmount:xe(i.outstandingAmount),interest:xe(i.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Ee(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:ur(i.hasRentalIncome),homeLoanInterest:xe(i.homeLoanInterest),homeLoanPrinciple:xe(i.homeLoanPrinciple),housePropertyAddress:Ee(i.housePropertyAddress),housePropertyPincode:Ee(i.housePropertyPincode),rentalIncome:xe(i.rentalIncome),nameOfTenant:Ee(i.nameOfTenant),propertyTax:xe(i.propertyTax),hasCoOwnedProperty:ur(i.hasCoOwnedProperty),coOwnerName:Ee(i.coOwnerName),coOwnerPan:Ee(i.coOwnerPan),coOwnerShare:Ee(i.coOwnerShare),loanDetails:t?[e]:void 0}}function wh(i){return{grossSalaryIncome:xe(i.grossSalary),salary:xe(i.basicSalary),employer:{employerName:Ee(i.employerName),employerTan:Ee(i.employerTan)},allowance:{hraAmount:xe(i.hraReceived),leaveTravelAllowanceAmount:xe(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:xe(i.leaveEncashment),anyOtherAllowanceAmount:xe(i.anyOtherAllowance)}}}function _h(i,e){const t=[];for(const r of i){const o=Ee(r.employerName),n=Ee(r.employerTan),s=xe(r.grossSalary),a=xe(r.basicSalary),l=xe(r.totalTdsDeposited);o===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function kh(i,e){const t=Ee(i.aadhaarNumber),r=Ee(i.bankAccountNumber),o=Ee(i.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function xh(i,e){return{userId:tt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:xe(i.savingBankInterest)??0,fdInterest:xe(i.fdInterest)??0,dividend:xe(i.dividend)??0,anyOtherIncome:xe(i.anyOtherIncome)??0,familyPension:xe(i.familyPension)??0}}function Sh(i,e){const t=xe(i.cryptoSellPrice),r=xe(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Eh(i,e){const t=(o,n,s,a)=>{const l=Ee(i[o]),c=Ee(i[n]),u=xe(i[s]),d=xe(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(o=>o!==null);return r.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Ah(i){return Ee(i.lenderName)!==void 0||Ee(i.loanAccountNumber)!==void 0||xe(i.totalLoanAmount)!==void 0||xe(i.outstandingAmount)!==void 0||xe(i.homeLoanInterest)!==void 0}function Yl(i){const e=Ee(i.typeOfHouseProperty)?.toUpperCase();return xe(i.rentalIncome)!==void 0||Ee(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Ih(i,e){const t=en(i.hpDetails).filter(Ah).map(r=>{const o=et({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:Kr(r.sanctionDate),totalLoanAmount:xe(r.totalLoanAmount),loanOutstandingAmount:xe(r.outstandingAmount),interest:xe(r.homeLoanInterest)});return et({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:xe(r.homeLoanInterest),homeLoanPrinciple:xe(r.homeLoanPrinciple),propertyTax:xe(r.propertyTax),eligible80EEAAmount:xe(r.eligible80EEAAmount),eligible80EEAmount:xe(r.eligible80EEAmount),hasCoOwnedProperty:ur(r.hasCoOwnedProperty)??!1,hasRentalIncome:Yl(r),loanDetails:[o]})});return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Th(i,e){const t=en(i.hpDetails).filter(Yl).map(r=>et({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:xe(r.rentalIncome),propertyTax:xe(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:xe(r.homeLoanInterest)}));return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Ch(i,e){const t=i||{},r=g=>({userId:tt(e.userId),assessmentYear:e.assessmentYear,deductions:et(g)}),o=[],n=xe(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?o.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 s=Ee(t.us80ccd1bPanNo),a=xe(t.us80ccd1bAmount);a!==void 0&&o.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=xe(t.us80ccd2Amount);l!==void 0&&o.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=xe(t.us80eInterest);c!==void 0&&o.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:Kr(t.us80eLoanSanctionDate),totalLoanAmount:xe(t.us80eLoanAmount),loanOutstandingAmount:xe(t.us80eOutstandingLoan)}));const u=xe(t.us80eeInterest);u!==void 0&&o.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:Kr(t.us80eeLoanSanctionDate),totalLoanAmount:xe(t.us80eeLoanAmount),loanOutstandingAmount:xe(t.us80eeOutstandingLoan),vehicleRegistrationNumber:Ee(t.us80eeVehicleRegistrationNumber)}));const d=xe(t.us80dForSelfAndFamilyAmount);d!==void 0&&o.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=xe(t.us80dForParentsAmount);return p!==void 0&&o.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:ur(t.hasParentOverSixty)??!1})),o}function Ph(i,e){const t=i||{},r=xe(t.us80gDonationAmount),o=Ee(t.us80gNameOfCharity);return r===void 0&&o===void 0?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,donations80g:[et({name:o,panNumber:Ee(t.us80gCharityPan),amountOtherThanCash:r,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode)})]}}function Oh(i,e){const t=i||{},r=xe(t.agricultureIncome),o=xe(t.agricultureExpenditure),n=et({landInAcre:xe(t.agricultureLandInAcre),nameOfDistrict:Ee(t.agricultureLandDistrict),pinCode:Ee(t.agricultureLandPincode),owner:Ee(t.agricultureLandOwner),typeOfLand:Ee(t.agricultureLandType)})??{},s=Object.keys(n).length>0;return r===void 0&&o===void 0&&!s?null:{userId:tt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:et({income:r,expenditure:o??0,agricultureLandDetails:s?[n]:void 0})}}function tt(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function xe(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 ur(i){return i===!0||i===!1?i:void 0}function Mh(){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 Kr(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 en(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function an(i,e){return en(i).map(t=>et(e(t))).filter(t=>t!==void 0)}function et(i){if(Array.isArray(i)){const e=i.map(et).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 o=et(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return i}function Lh(i){const e=i&&typeof i=="object"?i:{},t={},r=je(e.employers),o=je(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(L=>{const U=ln(L.salary),D=ln(L.perquisites),oe=ln(L.profitsInLieuOfSalaryType),z=U+D+oe,H=Uh(L.allowance);return{employerName:Ce(L.employerName),employerTan:Ce(L.employerTAN),basicSalary:U||void 0,grossSalary:z||void 0,hraReceived:H.hra,leaveTravelAllowance:H.lta,leaveEncashment:H.leaveEncashment,anyOtherAllowance:H.other,totalTdsDeposited:jh(L,o,r)??Le(L.totalTdsDeposited)}}));const n=je(e.houseProperties);n.length&&(t.hpDetails=n.map(L=>{const U=je(L.loanDetails),D=U.length?U[0]:void 0,oe=Le(L.grossAnnualRentReceived),z=U.length?U.reduce((M,J)=>M+(Le(J.interest)??0),0):void 0,H=je(L.tenant),te=je(L.coOwners),F=H[0],X=te[0];return{typeOfHouseProperty:Ce(L.propertyType),loanTakenFrom:Ce(D?.loanTakenFrom),lenderName:Ce(D?.bankOrInstituteName),loanAccountNumber:Ce(D?.loanAccountNo),sanctionDate:Js(D?.loanSanctionDate),totalLoanAmount:Le(D?.totalLoanAmount),outstandingAmount:Le(D?.loanOutstandingAmount),homeLoanInterest:z,homeLoanPrinciple:void 0,housePropertyAddress:Ce(L.address),housePropertyPincode:Ce(L.pinCode),rentalIncome:oe,nameOfTenant:Ce(F?.name),tenantPanNumber:Ce(F?.panNumber),eligible80EEAmount:Le(L.eligible80EEAmount),eligible80EEAAmount:Le(L.eligible80EEAAmount),propertyTax:Le(L.propertyTax),hasCoOwnedProperty:te.length>0,coOwnerName:Ce(X?.name),coOwnerPan:Ce(X?.panNumber),coOwnerShare:Le(X?.share)?.toString()}}));const s=je(e.deductionUS80CDetails),a=xt(s.map(L=>Le(L.amount))),l=s.find(L=>Ce(L.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=je(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=je(e.deductionUS80DDetails),p=d.find(L=>Ce(L.policyFor)?.toUpperCase()==="DEPENDANT")??je(e.insurances).find(L=>Ce(L.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(L=>Ce(L.policyFor)?.toUpperCase()==="PARENTS")??je(e.insurances).find(L=>Ce(L.policyFor)?.toUpperCase()==="PARENTS"),f=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Le(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??f?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??f?.accountNo),t.us80dForParentsAmount=Le(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??b?.accountNo),t.hasParentOverSixty=Dh(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=je(e.donations)[0];t.us80gDonationAmount=Le(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 _=je(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(_?.loanTakenFrom),t.us80eeBankName=Ce(_?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(_?.loanAccountNo),t.us80eeLoanSanctionDate=Js(_?.loanSanctionDate),t.us80eeLoanAmount=Le(_?.totalLoanAmount),t.us80eeOutstandingLoan=Le(_?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(_?.vehicleRegistrationNo);const x=je(e.insurances);t.preventiveHealthCheckUp=xt(x.map(L=>Le(L.preventiveCheckUp))),t.medicalExpenditure=xt(x.map(L=>Le(L.medicalExpenditure)));const v=je(e.incomes),S=L=>xt(v.filter(U=>Ce(U.incomeType)===L).map(U=>Le(U.amount)));t.savingBankInterest=S("SAVING_INTEREST"),t.fdInterest=S("FD_RD_INTEREST"),t.anyOtherIncome=S("ANY_OTHER"),t.familyPension=S("FAMILY_PENSION"),t.dividend=xt(je(e.dividendIncomes).map(L=>Le(L.income)));const E=e.business;if(E){const L=je(E.presumptiveIncomes),U=z=>{const H=je(z.incomes),te=F=>Le(H.find(X=>Ce(X.incomeType)===F)?.receipts)??0;return te("ANY_OTHER")>0?!0:te("BANK")>0||te("CASH")>0?!1:!!Ce(z.businessType)?.toUpperCase().includes("PROFESSION")},D=z=>L.find(H=>U(H)===z),oe=(z,H)=>{if(!z)return;const te=je(z.incomes),F=M=>Le(te.find(J=>Ce(J.incomeType)===M)?.receipts),X=F("BANK")||F("ANY_OTHER");t[H.name]=Ce(z.businessType),t[H.nature]=Ce(z.natureOfBusiness),t[H.bank]=X||void 0,t[H.cash]=F("CASH")||void 0,t[H.net]=xt(te.map(M=>Le(M.presumptiveIncome)))||void 0};oe(D(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),oe(D(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const I=je(e.capitalGain).filter(L=>Ce(L.assetType)?.toUpperCase()==="VDA").flatMap(L=>je(L.assetDetails));I.length&&(t.cryptoSellPrice=xt(I.map(L=>Le(L.sellValue))),t.cryptoPurchasePrice=xt(I.map(L=>Le(L.purchaseCost))));const P=e.agriculturalDetails;t.agricultureIncome=Le(P?.income),t.agricultureExpenditure=Le(P?.expenditure);const B=je(P?.agricultureLandDetails??P?.agriculturalLandDetails??e.agriculturalLandDetails)[0];B&&(t.agricultureLandInAcre=Le(B.landInAcre),t.agricultureLandDistrict=Ce(B.nameOfDistrict),t.agricultureLandPincode=Ce(B.pinCode),t.agricultureLandOwner=Rh(B.owner),t.agricultureLandType=Nh(B.typeOfLand)),t.aadhaarNumber=Ce(e.aadharNumber);const T=je(e.bankDetails)[0];return T&&(t.bankAccountNumber=Ce(T.accountNumber),t.bankIfscCode=Ce(T.ifsCode)),Jl(t)}function Rh(i){const e=Ce(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function Nh(i){const e=Ce(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function Js(i){const e=Ce(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function ln(i){return je(i).reduce((e,t)=>e+(Le(t.taxableAmount)??0),0)}function jh(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 o=Ce(i.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===o)return Le(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Le(e[0].totalTdsDeposited)}function Uh(i){const e=je(i);if(!e.length)return{};let t,r,o,n;for(const s of e){const a=Le(s.exemptAmount)??Le(s.allowanceAmount);switch(Ce(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Le(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function xt(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function je(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 Dh(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 Jl(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Jl(o):o):e[t]=r);return e}function cn(){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=Yh(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 o=Jh(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):Xh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Qh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Zh(),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 o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return Lh(Mo(await r.json().catch(()=>({}))))}async function Fh(i,e){const t=await i.getToken(),r=i.userId,o={...yh(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Mo(await a.json().catch(()=>({})))}async function $h(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function qh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Qs(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Hh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Wh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function zh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function Vh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Kh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Gh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function wt(i,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(o["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:o,body:JSON.stringify(t)});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Mo(await n.json().catch(()=>({})))}function Yh(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 Jh(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 Qh(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(i))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function Xh(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function Mo(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Zh(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}class ef{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new zl(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??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};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(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:bh,data:{}});const t=cn();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=cn();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=_h(n,o);s&&await $h(r,s)}else if(e==="bank-details"){const n=kh(t,o);n&&await qh(r,n)}else if(e==="other-sources")await Qs(r,xh(t,o));else if(e==="business-profession"){const n=Eh(t,o);n&&await Hh(r,n)}else if(e==="crypto-income"){const n=Sh(t,o);n&&await Gh(r,n)}else if(e==="agricultural-income"){const n=Oh(t,o);n&&await Wh(r,n)}else if(e==="deductions"){for(const s of Ch(t,o))await zh(r,s);const n=Ph(t,o);n&&await Qs(r,n)}else if(e==="house-property"){const n=Ih(t,o);n&&await Vh(r,n);const s=Th(t,o);s&&await Kh(r,s)}}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=cn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Fh(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 Ql 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||$c,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Ro,position:this.getAttribute("position")||this._config.position||Fc,width:Number(this.getAttribute("width"))||this._config.width||jc,height:Number(this.getAttribute("height"))||this._config.height||Uc,fontFamily:this._config.fontFamily||Bc,borderRadius:this._config.borderRadius??Dc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||No,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||qc,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,o){if(typeof document>"u")return;const n=document.documentElement,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??o),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}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(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${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;
|
|
12
12
|
z-index: 9999;
|
|
13
13
|
bottom: var(--aikaara-offset-y);
|
|
14
14
|
${e.position==="bottom-left"?"left":"right"}: var(--aikaara-offset-x);
|
|
15
|
-
`,
|
|
15
|
+
`,o=`
|
|
16
16
|
font-family: var(--aikaara-font);
|
|
17
17
|
display: flex;
|
|
18
18
|
flex-direction: column;
|
|
@@ -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||
|
|
44
|
+
--aikaara-primary-hover: ${this.darkenColor(e.primaryColor||Ro)};
|
|
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
|
|
@@ -60,7 +60,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
60
60
|
--aikaara-offset-x: ${e.offset?.x??20}px;
|
|
61
61
|
--aikaara-offset-y: ${e.offset?.y??20}px;
|
|
62
62
|
${this.themeVars(e.themeTokens)}
|
|
63
|
-
${t?
|
|
63
|
+
${t?o:r}
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
.aikaara-panel {
|
|
@@ -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||
|
|
115
|
+
placeholder="${e.placeholder||No}"
|
|
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
|
|
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 ef(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),o=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|o<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class Xl 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
|
|
157
|
+
`}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const tf=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Zl extends HTMLElement{shadow;actions=tf;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 o=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:o,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"),o=this.getAttribute("status")||"connected",n=o==="connected"?"#10b981":o==="connecting"||o==="reconnecting"?"#f59e0b":"#ef4444",s=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
|
|
317
|
+
`}setStatus(e){this.setAttribute("status",e)}}const rf=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,nf=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,of={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function sf(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>of[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(/&/gi,"&")}function zt(i){if(rf.test(i))return i;const e=nf.test(i)?sf(i):i;let t=af(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,o,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,o,n)=>{const s=/[.,!?;:]+$/.exec(n),a=s?s[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${o}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function af(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return i.replace(/[&<>"']/g,t=>e[t])}const lf=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"]),cf={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 Vt(i){const e=document.createElement("template");return e.innerHTML=i,ec(e.content),e.innerHTML}function ec(i){const e=Array.from(i.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,o=r.tagName.toLowerCase();if(!lf.has(o)){const a=document.createTextNode(r.textContent||"");i.replaceChild(a,t);continue}const n=cf[o]||new Set,s=Array.from(r.attributes);for(const a of s)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")}ec(t)}}function tc(i,e={}){const{width:t=600,height:r=700,closeOnTypes:o}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),s=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(i,"aikaara_popup",`width=${t},height=${r},left=${n},top=${s},resizable=yes,scrollbars=yes,status=yes`);if(!a)return null;const l=u=>{if(u.source!==a)return;const d=u.data?.type;o&&typeof d=="string"&&!o.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 uf(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 o=Math.round(r/60);if(o<24)return`${o} hr ago`;const n=Math.round(o/24);return n===1?"Yesterday":n<7?`${n} d ago`:i.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class rc 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(o=>r.includes(o)):!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(s=>s&&s.tagName==="A");if(!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment"))return;const o=this.linkHandlers.some(s=>Xs(r.href,s.match));r.target==="_self"&&!o||t.some(s=>{if(!s||!s.classList)return!1;const a=s.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">${Vt(zt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const
|
|
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">${Vt(zt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const o=r.externalId??r.id;this.appendMessageElement(r,t.get(o))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let o=e.length-1;o>=0;o--)if(e[o].role==="user"){r=o;break}for(let o=0;o<e.length;o++){const n=e[o];if(n.role==="user"){const s=n.metadata?.attributes?.action;if(s){const a=df(s);if(s.message_id&&t.set(s.message_id,a),Object.keys(a).length>0)for(let l=o-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&&o<r){const s=n.externalId??n.id;t.has(s)||t.set(s,{})}}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=Vt(zt(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 o=document.createElement("div");o.classList.add("bubble",e.role);const s=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?o.classList.add("attachment-only"):o.textContent=e.content:s?e.content&&(o.innerHTML=Vt(zt(e.content))):(o.innerHTML=Vt(zt(e.content||"")),e.status==="streaming"&&o.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):o.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)}o.appendChild(d)}const u=!(o.childNodes.length===0&&(o.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(o),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 uf(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=>Xs(e,g.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){tc(e);return}const n=this.getOrCreateModal(),s=r?.title??t??"Link";if(o==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,s));return}const a=hf(e),l=nc(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(fo(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,s,g=>{const f=r.props??{setData:p};for(const[y,w]of Object.entries(f)){const m=g[y];typeof m=="function"&&m.call(g,w)}const b=y=>{const w=y,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",b),g.addEventListener("aikaara-select",b)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function df(i){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,o]of Object.entries(i))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}function Xs(i,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(i)}function hf(i){try{const e=new URL(i),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function nc(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function fo(i,e){if(typeof i=="string")return nc(i,e);if(Array.isArray(i))return i.map(t=>fo(t,e));if(i&&typeof i=="object"){const t={};for(const[r,o]of Object.entries(i))t[r]=fo(o,e);return t}return i}class ic 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")||"",o=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",s=this.getAttribute("template-id")||"",a=this.getAttribute("inner-message")||"",l=e==="user"?document.createTextNode(t).textContent||"":Vt(zt(t)),c=e==="user"&&o,u=o==="sending"?"○":o==="sent"?"✓":o==="delivered"||o==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
479
479
|
<style>
|
|
480
480
|
:host { display: flex; flex-direction: column; }
|
|
481
481
|
:host([role="user"]) { align-items: flex-end; }
|
|
@@ -514,7 +514,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
514
514
|
}
|
|
515
515
|
.status {
|
|
516
516
|
font-size: 10px;
|
|
517
|
-
color: ${
|
|
517
|
+
color: ${o==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
|
|
518
518
|
margin-left: 4px;
|
|
519
519
|
}
|
|
520
520
|
.attachments {
|
|
@@ -553,14 +553,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
553
553
|
</div>
|
|
554
554
|
`:""}
|
|
555
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="${Zs(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
|
-
📎 ${
|
|
557
|
-
</a>`).join("")}</div>`:""}}function Zs(
|
|
556
|
+
📎 ${ff(t.fileName)}
|
|
557
|
+
</a>`).join("")}</div>`:""}}function Zs(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function ff(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class oc 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")??"",o=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",s=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"/>
|
|
561
561
|
</svg>
|
|
562
562
|
</button>
|
|
563
|
-
<input type="file" ${r?`accept="${r}"`:""} ${
|
|
563
|
+
<input type="file" ${r?`accept="${r}"`:""} ${o?"multiple":""} />`:"",l=`
|
|
564
564
|
<button class="send-btn" aria-label="Send message" type="button" disabled>
|
|
565
565
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
566
566
|
<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
|
|
@@ -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
|
|
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 sc 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
|
|
669
|
+
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class ac 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=Vt(zt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class
|
|
718
|
+
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Vt(zt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class lc 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 un=new Map;function
|
|
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 un=new Map;function cc(i){const e=un.get(i);if(e)return e;const t=new Promise((r,o)=>{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",()=>o(new Error(`Failed to load ${i}`)),{once:!0}));return}const s=document.createElement("script");s.src=i,s.async=!0,s.crossOrigin="anonymous",s.dataset.aikaaraSrc=i,s.addEventListener("load",()=>{s.dataset.aikaaraReady="1",r()},{once:!0}),s.addEventListener("error",()=>{un.delete(i),o(new Error(`Failed to load ${i}`))},{once:!0}),document.head.appendChild(s)});return un.set(i,t),t}function pf(i,e=5e3){return new Promise((t,r)=>{const o=setTimeout(()=>r(new Error(`Custom element <${i}> not registered within ${e}ms`)),e);customElements.whenDefined(i).then(()=>{clearTimeout(o),t()})})}const mf={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>require("./AikaaraPaymentLink-mK1C7vwW.cjs")).then(({registerAikaaraPaymentLink:i})=>i())};function gf(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 uc 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 o=vf(t.attributes.action);if(Object.keys(o).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(o))}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 o=localStorage.getItem(`aikaara_form:${r}`);o&&(e=JSON.parse(o))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o,s=n.getName?.();s&&r[s]?.length&&n.setPreSelected?.(r[s])})}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?
|
|
760
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?gf(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=mf[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,s)):r?.scriptUrl&&!customElements.get(o)&&cc(r.scriptUrl).then(()=>pf(o)).then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,s)),customElements.get(o)){const s=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof s[a]=="function")try{s[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}s.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(s),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&s.setConsumedValues?.(this._consumedValues),s.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const s=this.payloadData;if(s.length>0&&s.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:s.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 s)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const s=this.payloadData;typeof s.message=="string"&&(s.okLabel||s.action||s.ok)&&this.mountModal(s)}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 o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);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(()=>require("./AikaaraLinkButton-8s80ku63.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{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:yf(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 bf=new Set(["type","url","name","openLinkInNewTab","orderId"]);function yf(i){const e={};for(const[t,r]of Object.entries(i))bf.has(t)||(e[t]=r);return e}function vf(i){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(i))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));return t}class dc 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;
|
|
@@ -784,7 +784,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
784
784
|
</style>
|
|
785
785
|
<span class="pill">${ea(e)}</span>
|
|
786
786
|
${t?`<span class="sub">${ea(t)}</span>`:""}
|
|
787
|
-
`}}function ea(
|
|
787
|
+
`}}function ea(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class hc 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,o=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const s=t[0],a=this.selected.has(s.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 {
|
|
@@ -911,17 +911,17 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
911
911
|
}
|
|
912
912
|
</style>
|
|
913
913
|
${e?`<div class="title">${Mt(e)}</div>`:""}
|
|
914
|
-
<div class="grid" role="${
|
|
914
|
+
<div class="grid" role="${o?"group":"radiogroup"}" aria-label="${Mt(e??this.data.name)}">
|
|
915
915
|
${t.map(s=>`
|
|
916
916
|
<button class="opt" type="button"
|
|
917
917
|
data-value="${dn(s.value)}"
|
|
918
|
-
role="${
|
|
918
|
+
role="${o?"checkbox":"radio"}"
|
|
919
919
|
aria-pressed="${this.selected.has(s.value)}"
|
|
920
920
|
${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
|
|
921
921
|
${Mt(s.label)}
|
|
922
922
|
</button>`).join("")}
|
|
923
923
|
</div>
|
|
924
|
-
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(s=>{s.addEventListener("click",()=>this.toggle(s.dataset.value||""))})}}function Mt(
|
|
924
|
+
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(s=>{s.addEventListener("click",()=>this.toggle(s.dataset.value||""))})}}function Mt(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function dn(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class fc 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(o=>{(o.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(o=>{const n=o.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(o=>{const n=o.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">${
|
|
943
|
-
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function
|
|
942
|
+
<button type="button">${wf(e)}</button>
|
|
943
|
+
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function wf(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class pc 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 {
|
|
@@ -988,7 +988,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
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 hn(
|
|
991
|
+
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function hn(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class mc 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,o=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,7 +1022,7 @@ 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>${rr(e)}${
|
|
1025
|
+
<label>${rr(e)}${o}</label>
|
|
1026
1026
|
<input
|
|
1027
1027
|
type="text"
|
|
1028
1028
|
placeholder="${rr(t)}"
|
|
@@ -1031,7 +1031,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1031
1031
|
aria-invalid="false"
|
|
1032
1032
|
/>
|
|
1033
1033
|
<div class="error" role="alert">${rr(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 rr(
|
|
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 rr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class gc 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"),o=this.tokenGetter??r;if(!o){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},s=Object.keys(n).find(c=>c.toLowerCase()==="x-api-key"),a=this.apiKey??this.getAttribute("api-key")??(s?n[s]:void 0);a&&(s&&s!=="X-Api-Key"&&delete n[s],n["X-Api-Key"]=a);const l=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Lc({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:o,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 bc 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 o=!1;this.iframe.addEventListener("load",()=>{o=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{o||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const o=this.shadow.querySelector(".modal-title");o&&(o.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const s=document.createElement(e);n.appendChild(s),requestAnimationFrame(()=>r?.(s))}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
|
|
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 _f=[{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"}],kf=[{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 yc extends HTMLElement{shadow;data=null;columns=kf;features=_f;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;
|
|
@@ -1141,29 +1141,29 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1141
1141
|
</tr>
|
|
1142
1142
|
</thead>
|
|
1143
1143
|
<tbody>
|
|
1144
|
-
${t.map((r,
|
|
1144
|
+
${t.map((r,o)=>`
|
|
1145
1145
|
<tr>
|
|
1146
1146
|
<td>${fn(r.label)}</td>
|
|
1147
|
-
${e.map(n=>n.features[
|
|
1147
|
+
${e.map(n=>n.features[o]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
|
|
1148
1148
|
</tr>`).join("")}
|
|
1149
1149
|
<tr class="price-row">
|
|
1150
1150
|
<td>Price (excl. GST)</td>
|
|
1151
|
-
${e.map(r=>{const
|
|
1151
|
+
${e.map(r=>{const o=this.priceFor(r);return`<td>${o!=null?"₹"+Math.round(o):"—"}</td>`}).join("")}
|
|
1152
1152
|
</tr>
|
|
1153
1153
|
</tbody>
|
|
1154
1154
|
</table>
|
|
1155
1155
|
<div class="actions">
|
|
1156
|
-
${e.map((r,
|
|
1156
|
+
${e.map((r,o)=>{const n=this.priceFor(r),s=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${o}" type="button">
|
|
1157
1157
|
<span>${fn(s)}</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
|
|
1161
|
+
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const o=Number(r.dataset.col),n=e[o];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function fn(i){return i.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class vc 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("[]"),o=r?t.slice(0,-2):t,n=this.data[o];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(o=>o.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
1164
|
<button class="icon-btn close-btn" type="button" aria-label="Close">${ta}</button>
|
|
1165
|
-
`;const r=this.shadow.querySelector(".modal-body"),
|
|
1166
|
-
<button class="chip" type="button" data-section-id="${
|
|
1165
|
+
`;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(s=>`
|
|
1166
|
+
<button class="chip" type="button" data-section-id="${Sf(s.id)}">
|
|
1167
1167
|
<span class="chip-icon">${s.icon??"📄"}</span>
|
|
1168
1168
|
<span class="chip-label">${ra(s.title)}</span>
|
|
1169
1169
|
</button>`).join("");r.innerHTML=`
|
|
@@ -1175,15 +1175,15 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1175
1175
|
<div class="intro-sub">Select a category to edit</div>
|
|
1176
1176
|
</div>
|
|
1177
1177
|
</div>
|
|
1178
|
-
<div class="chip-grid">${
|
|
1178
|
+
<div class="chip-grid">${o}</div>
|
|
1179
1179
|
</div>
|
|
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 & Recalculate</button>
|
|
1182
1182
|
`,this.bindCommon(),r.querySelectorAll(".chip").forEach(s=>{s.addEventListener("click",()=>{const a=s.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">${
|
|
1183
|
+
<button class="icon-btn back-btn" type="button" aria-label="Back">${xf}</button>
|
|
1184
1184
|
<div class="modal-title">${ra(t?.title??"Edit")}</div>
|
|
1185
1185
|
<button class="icon-btn close-btn" type="button" aria-label="Close">${ta}</button>
|
|
1186
|
-
`;const
|
|
1186
|
+
`;const o=this.shadow.querySelector(".modal-footer");o.style.display="none",o.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(o=>o.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",(o=>{const n=o.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">
|
|
1189
1189
|
<div class="modal view-picker" role="dialog" aria-modal="true" aria-label="Correct Your ITR Details">
|
|
@@ -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 ta='<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>',
|
|
1324
|
+
`}}const ta='<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>',xf='<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 Sf(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ra(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class wc 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 o=this.getEntries(),n={...o[e]||{}};n[t]=r,o[e]=n,this.isRepeatable()?this.value=o: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=s=>{if(!s)return null;const a=t[s.field];return"equals"in s?a===s.equals:Array.isArray(s.in)?s.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||[],o=>{if(!this.fieldVisible(o,t)||o.type==="group")return;const n=t[o.id],s=`${r}.${o.id}`;if(o.required&&(n==null||n==="")){this.errors.set(s,"Required");return}if(o.type==="text"&&typeof n=="string"&&(o.pattern&&n&&!new RegExp(o.pattern).test(n)?this.errors.set(s,"Invalid format"):o.maxLength&&n.length>o.maxLength&&this.errors.set(s,`Max ${o.maxLength} characters`)),o.type==="textarea"&&typeof n=="string"&&o.maxLength&&n.length>o.maxLength&&this.errors.set(s,`Max ${o.maxLength} characters`),o.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=o;Number.isNaN(a)?this.errors.set(s,"Must be a number"):l.min!==void 0&&a<l.min?this.errors.set(s,`Minimum ${l.min}`):l.max!==void 0&&a>l.max&&this.errors.set(s,`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((o,n)=>this.renderEntry(o,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">
|
|
@@ -1341,10 +1341,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1341
1341
|
</button>
|
|
1342
1342
|
</div>
|
|
1343
1343
|
</div>
|
|
1344
|
-
`,this.bindHandlers()}renderEntry(e,t){const
|
|
1344
|
+
`,this.bindHandlers()}renderEntry(e,t){const o=this.isRepeatable()&&this.schema?.repeatable?this.schema.repeatable.labelTemplate.replace("{index}",String(t+1)):"",n=this.isRepeatable()&&this.getEntries().length>1?`<button class="remove-btn" type="button" data-entry-index="${t}" data-action="remove-entry" aria-label="Remove">Remove</button>`:"",s=(this.schema?.fields||[]).map(l=>this.renderField(l,e,t)).join("");return`<section class="entry-card">${o?`<div class="entry-header">
|
|
1345
1345
|
<span class="entry-label">
|
|
1346
1346
|
${this.schema?.entryIcon?`<span class="entry-icon">${this.schema.entryIcon}</span>`:""}
|
|
1347
|
-
${Ge(
|
|
1347
|
+
${Ge(o)}
|
|
1348
1348
|
</span>
|
|
1349
1349
|
${n}
|
|
1350
1350
|
</div>`:""}<div class="entry-body">${s}</div></section>`}renderField(e,t,r){if(!this.fieldVisible(e,t))return"";if(e.type==="group"){const d=e,p=d.fields.map(b=>this.renderField(b,t,r)).join("");if(!d.collapsible)return`
|
|
@@ -1354,29 +1354,29 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1354
1354
|
<div class="group-body">${p}</div>
|
|
1355
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="${
|
|
1357
|
+
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${St(g)}" aria-expanded="${!f}">
|
|
1358
1358
|
<span class="group-title">${Ge(d.title??"")}</span>
|
|
1359
1359
|
<span class="group-chevron" aria-hidden="true"></span>
|
|
1360
1360
|
</button>
|
|
1361
1361
|
${d.hint&&!f?`<div class="group-hint">${Ge(d.hint)}</div>`:""}
|
|
1362
1362
|
<div class="group-body" ${f?"hidden":""}>${p}</div>
|
|
1363
|
-
</fieldset>`}const
|
|
1363
|
+
</fieldset>`}const o=`${r}.${e.id}`,n=this.errors.get(o),s=n?"has-error":"",a=e.required?'<span class="req">*</span>':"",l=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ge(e.label)} ${a}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ge(n)}</div>`:"";return`
|
|
1364
1364
|
<div class="field ${s}" data-field-id="${e.id}" data-entry-index="${r}">
|
|
1365
1365
|
${l}
|
|
1366
1366
|
${c}
|
|
1367
1367
|
${u}
|
|
1368
|
-
</div>`}renderInput(e,t,r){const
|
|
1368
|
+
</div>`}renderInput(e,t,r){const o=t[e.id],n=this.fieldHtmlId(e,r),s=`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}" ${s} value="${St(String(o??""))}" placeholder="${St(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""} ${c}/>`}if(e.type==="textarea"){const a=e;return`<textarea class="input textarea" id="${n}" ${s} rows="${a.rows??4}" placeholder="${St(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Ge(String(o??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Ge(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}" ${s} value="${
|
|
1372
|
-
</div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${s} value="${
|
|
1371
|
+
<input type="number" class="input ${u}" id="${n}" ${s} value="${St(String(o??""))}" placeholder="${St(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}" ${s} value="${St(String(o??""))}"/>`;if(e.type==="radio")return`
|
|
1373
1373
|
<div class="radio-group">
|
|
1374
|
-
${e.options.map(l=>{const c=
|
|
1374
|
+
${e.options.map(l=>{const c=o===l.value?"checked":"",u=`${n}-${l.value}`;return`
|
|
1375
1375
|
<label class="radio-item ${c?"selected":""}" for="${u}">
|
|
1376
|
-
<input type="radio" id="${u}" ${s} name="${n}" value="${
|
|
1376
|
+
<input type="radio" id="${u}" ${s} name="${n}" value="${St(l.value)}" ${c}/>
|
|
1377
1377
|
<span class="radio-label">${Ge(l.label)}</span>
|
|
1378
1378
|
</label>`}).join("")}
|
|
1379
|
-
</div>`;if(e.type==="yes-no"){const a=
|
|
1379
|
+
</div>`;if(e.type==="yes-no"){const a=o===!0?"checked":"",l=o===!1?"checked":"";return`
|
|
1380
1380
|
<div class="radio-group">
|
|
1381
1381
|
<label class="radio-item ${a?"selected":""}">
|
|
1382
1382
|
<input type="radio" ${s} name="${n}" value="true" ${a}/>
|
|
@@ -1388,9 +1388,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1388
1388
|
</label>
|
|
1389
1389
|
</div>`}return e.type==="checkbox"?`
|
|
1390
1390
|
<label class="checkbox-item">
|
|
1391
|
-
<input type="checkbox" id="${n}" ${s} ${
|
|
1391
|
+
<input type="checkbox" id="${n}" ${s} ${o===!0?"checked":""}/>
|
|
1392
1392
|
<span class="checkbox-label">${Ge(e.label??"")}</span>
|
|
1393
|
-
</label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,
|
|
1393
|
+
</label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,o=Number(t.dataset.entryIndex||0),s=t.type==="radio"||t.type==="checkbox"?"change":"input";t.addEventListener(s,()=>{let a;t.type==="checkbox"?a=t.checked:t.type==="radio"?t.value==="true"?a=!0:t.value==="false"?a=!1:a=t.value:t.type==="number"?a=t.value===""?null:Number(t.value):a=t.value,s==="input"?this.setEntryNoRender(o,r,a):this.setEntry(o,r,a)})}),this.shadow.querySelector('[data-action="save"]')?.addEventListener("click",()=>this.handleSubmit()),this.shadow.querySelector('[data-action="add-entry"]')?.addEventListener("click",()=>this.addEntry()),this.shadow.querySelectorAll('[data-action="toggle-group"]').forEach(e=>{e.addEventListener("click",()=>{const t=e.dataset.groupKey;this.collapsed.has(t)?this.collapsed.delete(t):this.collapsed.add(t),this.render()})}),this.shadow.querySelectorAll('[data-action="remove-entry"]').forEach(e=>{e.addEventListener("click",()=>{const t=Number(e.dataset.entryIndex||0);this.removeEntry(t)})})}css(){return`
|
|
1394
1394
|
/* Pure-flex height chain — no percentage heights, which do not
|
|
1395
1395
|
resolve reliably through a max-height-only flex ancestor. The
|
|
1396
1396
|
modal makes this element a flex item (flex:1; min-height:0); we
|
|
@@ -1596,4 +1596,4 @@ 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 xt(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ge(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function wc(){const o=[["aikaara-chat-widget",Jl],["aikaara-chat-bubble",Ql],["aikaara-chat-header",Xl],["aikaara-message-list",tc],["aikaara-message-bubble",nc],["aikaara-chat-input",ic],["aikaara-typing-indicator",oc],["aikaara-streaming-message",sc],["aikaara-error-banner",ac],["aikaara-template-renderer",cc],["aikaara-system-pill",uc],["aikaara-option-list",dc],["aikaara-submit-action",hc],["aikaara-modal-action",fc],["aikaara-text-input",pc],["aikaara-chat",mc],["aikaara-link-modal",gc],["aikaara-compare-plans",bc],["aikaara-smart-edit-modal",yc],["aikaara-schema-form",vc]];for(const[e,t]of o)customElements.get(e)||customElements.define(e,t)}wc();function br(o,e,t=""){if(!e)return t;const r=e.split(".");let i=o;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function na(o){try{const e=o.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 Kt(o){return typeof o=="function"?await o():o}class _c{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=na(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 Kt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",s={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",s.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,s);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=br(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=br(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=br(l,this.descriptor.fullNamePath??"data.fullName"),b=br(l,this.descriptor.userPath??"data.userId"),y=na(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:f,userId:b,expiresAt:y},this.cache}}async function kc(o){const e={};for(const t of o.spec){const r=await wf(t,o.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 wf(o,e){const t=o.key??o.name;switch(o.source){case"cookie":return _f(t);case"localStorage":return yr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return yr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return yr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return yr(()=>document.querySelector(`meta[name="${kf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[o.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function _f(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===o||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function yr(o){try{return o()}catch{return}}function kf(o){return o.replace(/["\\]/g,"\\$&")}const xf=1800;class xc{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 kc({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 i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)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(i,{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??xf;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 Sf=3e4,Ef=2e3,Af=100;async function Sc(o){const{descriptor:e}=o,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!o.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:o.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=If(r);if(!i)throw new Xe("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Tf(r);if(!i)throw new Xe("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=Rf(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Sf;return{token:await Mf({type:r,key:i,origins:n,timeoutMs:s}),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 i=Cf(r);if(!i)throw new Xe("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Xe("storage","storage.key not configured");const s=Pf(r,i,n);if(!s)throw new Xe("storage",`${r}Storage["${i}"] not set`);return{token:s,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Ef,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Af,s=await Of(r,i,n);if(!s)throw new Xe("global",`window.${r} not present`);return{token:s,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Ec{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 If(o){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))===o)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Tf(o){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(o)??void 0}catch{return}}function Cf(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===o||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Pf(o,e,t){if(!(typeof window>"u"))try{const i=(o==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const s=Ac(n,t);return typeof s=="string"?s:void 0}catch{return}}async function Of(o,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Ac(window,o);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Mf(o){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${o.timeoutMs}ms`))},o.timeoutMs),n=s=>{if(o.origins.length>0&&!o.origins.includes(s.origin))return;const a=s.data;if(!a||typeof a!="object")return;const l=a;if(o.type&&l.type!==o.type)return;const c=l[o.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Rf(o){return o?o.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Ac(o,e){if(!e)return o;const t=e.split(".").filter(Boolean);let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function Nf(){const o=typeof crypto<"u"?crypto:null;if(o?.randomUUID)return o.randomUUID();if(o?.getRandomValues){const e=new Uint8Array(16);o.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 Lf="aikaara_chat:requestId";function Ro(o,e,t){const r=`${Lf}:${o}:${e}`;return t?`${r}:${t}`:r}function Ic(o,e,t){try{return localStorage.getItem(Ro(o,e,t))}catch{return null}}function jf(o,e,t,r){try{localStorage.setItem(Ro(o,e,r),t)}catch{}}function Uf(o,e,t){try{localStorage.removeItem(Ro(o,e,t))}catch{}}async function po(o,e,t="before-chat"){const r=o.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const i={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(i[u]=d);typeof e.serviceType=="string"&&(i.serviceType=e.serviceType),typeof e.userType=="string"&&(i.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in i?i[p]:""),s=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(s);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=s(g);return d}return u},a=await Kt(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 x=d.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",a)}const b={method:g,headers:f};d.body&&(f["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,b);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Bf(y,w)){const S=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${y} (transient). Retry #${m} in ${S}ms.`),await new Promise(E=>setTimeout(E,S));continue}const v=`Preflight #${u} ${g} ${p} → ${y} ${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(S=>setTimeout(S,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&d.capture&&d.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const S of d.capture.path.split("."))if(v&&typeof v=="object"&&S in v)v=v[S];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let S=v;d.capture.stripPrefix&&S.startsWith(d.capture.stripPrefix)&&(S=S.slice(d.capture.stripPrefix.length)),l[d.capture.as]=S,i[d.capture.as]=S,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${S.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Df(o){const e=o.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await po(e,{sessionToken:o.sessionToken,userId:o.userId,projectId:o.projectId??"",slug:o.slug??"",identity:o.identity,serviceType:o.serviceType,userType:o.userType},"on-method-select")).captured:{}}function Bf(o,e){if(o===503||o===504||o===502)return!0;if(o===401||o===403)return e.trim().length===0;if(o===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Tc(o,e){const t=await fetch(o,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.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 Cc(o,e){return o.replace("{projectId}",e).replace("{uuid}",Nf().replace(/-/g,""))}function Pc(o){const e=o._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=>lc(r)))}async function Oc(o){const e={...o.config??(o.configUrl?await Tc(o.configUrl,o.configHeaders):{}),...o.overrides??{}};Pc(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 i=r?.projectId??"",n=o.identity.userId,s=o.conversationScope||void 0,a=o.forceNewConversation?null:Ic(n,i,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=o.conversationId??a??Cc(l,i);(o.conversationId||!a||o.forceNewConversation)&&i&&jf(n,i,c,s);const u=await o.tokenProvider(),d=o.tokenProvider,p=o.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:o.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,...o.identity.departmentId?{departmentId:o.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:o.identity.senderFullname??o.identity.userName,tokenProvider:d}:void 0,f=o.uploadAdapter??(e.uploadEndpoint?Oo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=o.historyAdapter??(e.historyApiBase?Kl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:o.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:o.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:o.identity.userName,departmentId:o.identity.departmentId,senderFullname:o.identity.senderFullname??o.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:b,onError:o.onError,onMessage:o.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),o.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Ff(o){if(typeof o!="string")return o;const e=document.querySelector(o);if(!e)throw new Error(`mountFromSlug: container "${o}" not found`);return e}async function Mc(o){const e=(o.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(o.slug)}`;let r=null;try{r=await Tc(t,o.configHeaders)}catch(I){if(!o.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${o.slug}" — using fallbackConfig.`,I)}const i={...o.fallbackConfig??{},...r??{},...o.overrides??{}};if(Pc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const C=`template:${I}`;i.components[C]||!O?.scriptUrl||!O?.render||(i.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:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${o.slug} descriptor must include "auth" block`);let s=null,a=o.user.id,l=o.user.name,c="",u=o.user.token,d=null;const p=await Kt(o.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&i.sso?.tokenSource){d=new Ec({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:o.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,o.user.identity&&!o.user.identity.partnerToken&&(o.user.identity.partnerToken=I.token)}else if(!g&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(o.slug)}/sso_exchange`;s=await new xc({descriptor:i.sso,providers:o.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let f="",b="";if(i.preflight&&i.preflight.length){const I=await po(i.preflight,{sessionToken:u,userId:a,projectId:i.tiledesk?.projectId??"",slug:o.slug,identity:o.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&&(b=I.captured.requestId)}const y=new _c(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?Ic(a,I):null,C=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=O??(I?Cc(C,I):"");y.prime(f,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Kt(o.user.token),identity:o.user.identity,slug:o.slug,configBase:e};const _=d&&i.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Kt(o.user.token)}`,S=o.hooks?.upload??(x&&x.mode==="presigned-3step"?Vl({...x,authHeader:v}):x&&x.mode==="direct"?Oo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await Oc({container:Ff(o.container),config:i,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:o.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:S,historyAdapter:o.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:o.conversationScope,onError:o.hooks?.onError,onMessage:o.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Kt(o.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:i,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const O=i.preflight;return!O||!O.length?{}:O.some(j=>j.trigger==="on-method-select")?(await po(O,{sessionToken:u,userId:a,projectId:i.tiledesk?.projectId??"",slug:o.slug,identity:{...o.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=pn;exports.AikaaraChat=mc;exports.AikaaraChatBubble=Ql;exports.AikaaraChatClient=zl;exports.AikaaraChatHeader=Xl;exports.AikaaraChatInput=ic;exports.AikaaraChatWidget=Jl;exports.AikaaraComparePlans=bc;exports.AikaaraErrorBanner=ac;exports.AikaaraLinkModal=gc;exports.AikaaraMessageBubble=nc;exports.AikaaraMessageList=tc;exports.AikaaraModalAction=fc;exports.AikaaraOptionList=dc;exports.AikaaraSchemaForm=vc;exports.AikaaraSmartEditModal=yc;exports.AikaaraStreamingMessage=sc;exports.AikaaraSubmitAction=hc;exports.AikaaraSystemPill=uc;exports.AikaaraTemplateRenderer=cc;exports.AikaaraTextInput=pc;exports.AikaaraTypingIndicator=oc;exports.ApiClient=sa;exports.ChannelSubscription=ia;exports.ConnectionManager=oa;exports.ConversationManager=ca;exports.EventEmitter=mo;exports.MessageStore=aa;exports.SessionAuthAdapter=_c;exports.SsoExchangeAdapter=xc;exports.TiledeskTransport=$l;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=Ec;exports.clearPersistedConversationId=Uf;exports.collectSsoCredentials=kc;exports.createFetchUploadAdapter=Oo;exports.createPresigned3StepUploadAdapter=Vl;exports.createTiledeskHistoryAdapter=Kl;exports.discoverToken=Sc;exports.extractTiledeskFileEnvelope=Wl;exports.inferTiledeskRole=Hl;exports.isTiledeskSelfEcho=ql;exports.mount=Oc;exports.mountFromSlug=Mc;exports.openInPopupWindow=ec;exports.parseTiledeskTemplate=Po;exports.registerComponents=wc;exports.runMethodSelectPreflight=Df;
|
|
1599
|
+
`}}function St(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ge(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function _c(){const i=[["aikaara-chat-widget",Ql],["aikaara-chat-bubble",Xl],["aikaara-chat-header",Zl],["aikaara-message-list",rc],["aikaara-message-bubble",ic],["aikaara-chat-input",oc],["aikaara-typing-indicator",sc],["aikaara-streaming-message",ac],["aikaara-error-banner",lc],["aikaara-template-renderer",uc],["aikaara-system-pill",dc],["aikaara-option-list",hc],["aikaara-submit-action",fc],["aikaara-modal-action",pc],["aikaara-text-input",mc],["aikaara-chat",gc],["aikaara-link-modal",bc],["aikaara-compare-plans",yc],["aikaara-smart-edit-modal",vc],["aikaara-schema-form",wc]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}_c();function br(i,e,t=""){if(!e)return t;const r=e.split(".");let o=i;for(const n of r)if(o&&typeof o=="object"&&n in o)o=o[n];else return t;return typeof o=="string"?o:t}function na(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 Kt(i){return typeof i=="function"?await i():i}class kc{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=na(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 Kt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",o={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",s={method:n,headers:o};n==="POST"&&(o["content-type"]="application/json",s.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,s);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=br(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=br(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=br(l,this.descriptor.fullNamePath??"data.fullName"),b=br(l,this.descriptor.userPath??"data.userId"),y=na(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:f,userId:b,expiresAt:y},this.cache}}async function xc(i){const e={};for(const t of i.spec){const r=await Ef(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 Ef(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return Af(t);case"localStorage":return yr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return yr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return yr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return yr(()=>document.querySelector(`meta[name="${If(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const o=await r();return typeof o=="string"?o:void 0}default: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 o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function yr(i){try{return i()}catch{return}}function If(i){return i.replace(/["\\]/g,"\\$&")}const Tf=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 xc({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 o=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!o)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(o,{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??Tf;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 Cf=3e4,Pf=2e3,Of=100;async function Ec(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",o=Mf(r);if(!o)throw new Xe("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=Lf(r);if(!o)throw new Xe("hash",`#${r}= not present`);return{token:o,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",o=typeof t.key=="string"&&t.key?t.key:"token",n=Df(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Cf;return{token:await Uf({type:r,key:o,origins:n,timeoutMs:s}),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 o=Rf(r);if(!o)throw new Xe("cookie",`cookie "${r}" not set`);return{token:o,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",o=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!o)throw new Xe("storage","storage.key not configured");const s=Nf(r,o,n);if(!s)throw new Xe("storage",`${r}Storage["${o}"] not set`);return{token:s,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Pf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Of,s=await jf(r,o,n);if(!s)throw new Xe("global",`window.${r} not present`);return{token:s,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 Ec(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 Mf(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 Lf(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function Rf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const o=r.indexOf("=");if(o===-1)continue;const n=r.slice(0,o);if(n===i||n===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}}function Nf(i,e,t){if(!(typeof window>"u"))try{const o=(i==="session"?window.sessionStorage:window.localStorage).getItem(e);if(o==null)return;if(!t)return o;let n;try{n=JSON.parse(o)}catch{return o}const s=Ic(n,t);return typeof s=="string"?s:void 0}catch{return}}async function jf(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=Ic(window,i);if(typeof o=="string"&&o.length>0)return o;if(typeof o=="function")try{const n=o();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Uf(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=s=>{if(i.origins.length>0&&!i.origins.includes(s.origin))return;const a=s.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 Df(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Ic(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return;return r}function Bf(){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 Ff="aikaara_chat:requestId";function Lo(i,e,t){const r=`${Ff}:${i}:${e}`;return t?`${r}:${t}`:r}function Tc(i,e,t){try{return localStorage.getItem(Lo(i,e,t))}catch{return null}}function $f(i,e,t,r){try{localStorage.setItem(Lo(i,e,r),t)}catch{}}function qf(i,e,t){try{localStorage.removeItem(Lo(i,e,t))}catch{}}async function po(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 o={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(o[u]=d);typeof e.serviceType=="string"&&(o.serviceType=e.serviceType),typeof e.userType=="string"&&(o.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in o?o[p]:""),s=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(s);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=s(g);return d}return u},a=await Kt(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 x=d.authHeaderTemplate??"Bearer {token}";f.authorization=x.replace("{token}",a)}const b={method:g,headers:f};d.body&&(f["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,_=null;for(;;)try{const x=await fetch(p,b);if(x.ok){_=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Wf(y,w)){const S=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${y} (transient). Retry #${m} in ${S}ms.`),await new Promise(E=>setTimeout(E,S));continue}const v=`Preflight #${u} ${g} ${p} → ${y} ${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(S=>setTimeout(S,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,x);break}throw x}if(_&&d.capture&&d.capture.as)try{const x=await _.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const S of d.capture.path.split("."))if(v&&typeof v=="object"&&S in v)v=v[S];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let S=v;d.capture.stripPrefix&&S.startsWith(d.capture.stripPrefix)&&(S=S.slice(d.capture.stripPrefix.length)),l[d.capture.as]=S,o[d.capture.as]=S,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${S.slice(0,24)}…)`)}}catch(x){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,x)}}return{captured:l}}async function Hf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await po(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 Wf(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 Cc(i,e){const t=await fetch(i,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const o=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${o.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 Pc(i,e){return i.replace("{projectId}",e).replace("{uuid}",Bf().replace(/-/g,""))}function Oc(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=>cc(r)))}async function Mc(i){const e={...i.config??(i.configUrl?await Cc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};Oc(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 o=r?.projectId??"",n=i.identity.userId,s=i.conversationScope||void 0,a=i.forceNewConversation?null:Tc(n,o,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??Pc(l,o);(i.conversationId||!a||i.forceNewConversation)&&o&&$f(n,o,c,s);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?Oo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=i.historyAdapter??(e.historyApiBase?Kl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={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:b,onError:i.onError,onMessage:i.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.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:y,destroy(){w.remove()}}}function zf(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 Lc(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 Cc(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 o={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(Oc(o),o.templates&&Object.keys(o.templates).length>0){o.components={...o.components??{}};for(const[I,P]of Object.entries(o.templates)){const O=`template:${I}`;o.components[O]||!P?.scriptUrl||!P?.render||(o.components[O]={kind:"iife-element",scriptUrl:P.scriptUrl,tag:P.render,...P.props?{props:P.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:o.templates,components:o.components,razorpay:o.razorpay,title:o.title,cloud:o.cloud??n.__aikaara_descriptor__?.cloud,upload:o.upload??n.__aikaara_descriptor__?.upload,themeSource:o.themeSource??n.__aikaara_descriptor__?.themeSource,api:o.api,auth:o.auth},!o.auth)throw new Error(`mountFromSlug: widget_configs/${i.slug} descriptor must include "auth" block`);let s=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const p=await Kt(i.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&o.sso?.tokenSource){d=new Ac({descriptor:{provider:o.sso.provider,flow:o.sso.flow,skipLogin:o.sso.skipLogin,autoRefresh:o.sso.autoRefresh,tokenSource:o.sso.tokenSource,tokenSourceConfig:o.sso.tokenSourceConfig,fallback:o.sso.fallback,map:o.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&&o.sso&&o.sso.collect&&o.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(i.slug)}/sso_exchange`;s=await new Sc({descriptor:o.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let f="",b="";if(o.preflight&&o.preflight.length){const I=await po(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const P=f;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new kc(o.auth,u);if(f){const I=o.tiledesk?.projectId??"",P=I?Tc(a,I):null,O=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",B=P??(I?Pc(O,I):"");y.prime(f,{requestId:B,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Kt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const _=d&&o.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=o.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await y.get()).token:await Kt(i.user.token)}`,S=i.hooks?.upload??(x&&x.mode==="presigned-3step"?Vl({...x,authHeader:v}):x&&x.mode==="direct"?Oo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await Mc({container:zf(i.container),config:o,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:S,historyAdapter:i.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Kt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return _?_():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some(B=>B.trigger==="on-method-select")?(await po(P,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=pn;exports.AikaaraChat=gc;exports.AikaaraChatBubble=Xl;exports.AikaaraChatClient=zl;exports.AikaaraChatHeader=Zl;exports.AikaaraChatInput=oc;exports.AikaaraChatWidget=Ql;exports.AikaaraComparePlans=yc;exports.AikaaraErrorBanner=lc;exports.AikaaraLinkModal=bc;exports.AikaaraMessageBubble=ic;exports.AikaaraMessageList=rc;exports.AikaaraModalAction=pc;exports.AikaaraOptionList=hc;exports.AikaaraSchemaForm=wc;exports.AikaaraSmartEditModal=vc;exports.AikaaraStreamingMessage=ac;exports.AikaaraSubmitAction=fc;exports.AikaaraSystemPill=dc;exports.AikaaraTemplateRenderer=uc;exports.AikaaraTextInput=mc;exports.AikaaraTypingIndicator=sc;exports.ApiClient=sa;exports.ChannelSubscription=ia;exports.ConnectionManager=oa;exports.ConversationManager=ca;exports.EventEmitter=mo;exports.MessageStore=aa;exports.SessionAuthAdapter=kc;exports.SsoExchangeAdapter=Sc;exports.TiledeskTransport=$l;exports.TokenDiscoveryError=Xe;exports.TokenDiscoveryReader=Ac;exports.clearPersistedConversationId=qf;exports.collectSsoCredentials=xc;exports.createFetchUploadAdapter=Oo;exports.createPresigned3StepUploadAdapter=Vl;exports.createTiledeskHistoryAdapter=Kl;exports.discoverToken=Ec;exports.extractTiledeskFileEnvelope=Wl;exports.inferTiledeskRole=Hl;exports.isTiledeskSelfEcho=ql;exports.mount=Mc;exports.mountFromSlug=Lc;exports.openInPopupWindow=tc;exports.parseTiledeskTemplate=Po;exports.registerComponents=_c;exports.runMethodSelectPreflight=Hf;
|