@aikaara/chat-sdk 1.5.18 → 1.5.19
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-CIFBtQKu.cjs → AikaaraLinkButton-8xLs7Y9n.cjs} +1 -1
- package/dist/{AikaaraLinkButton-IeGomyIc.mjs → AikaaraLinkButton-CU-wW3_e.mjs} +1 -1
- package/dist/{MountTenant-mK4EzOxi.mjs → MountTenant-BzTKCfBi.mjs} +5753 -4937
- package/dist/{MountTenant-lU2E6T8p.cjs → MountTenant-C-dsPfDW.cjs} +412 -79
- package/dist/cdn/aikaara-chat.iife.js +447 -114
- 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.d.ts +364 -0
- package/dist/ui.mjs +26 -20
- package/package.json +1 -1
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var AikaaraChat=(function(Me){"use strict";class Bo{identifier;callbacks={};sendFn;constructor(e,t){this.identifier=e,this.sendFn=t}onReceived(e){return this.callbacks.received=e,this}onConnected(e){return this.callbacks.connected=e,this}onDisconnected(e){return this.callbacks.disconnected=e,this}onRejected(e){return this.callbacks.rejected=e,this}perform(e,t={}){this.sendFn({action:e,...t})}_notifyReceived(e){this.callbacks.received?.(e)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class an{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(e){this.url=e}connect(){return new Promise((e,t)=>{this.welcomePromise={resolve:e,reject:t},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=r=>{this.handleMessage(r)},this.ws.onerror=()=>{const r=new Error("WebSocket connection error");this.welcomePromise?.reject(r),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(r=>r._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(e=>e._notifyDisconnected()),this.subscriptions.clear()}subscribe(e){const t=JSON.stringify(e),r=new Bo(t,s=>{this.send({command:"message",identifier:t,data:JSON.stringify(s)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((s,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>s(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class yr{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event handler for "${e}":`,s)}})}removeAllListeners(){this.handlers.clear()}}const Oc=1e3,Mc=10,Lc=400,Rc=600,Fo="#6366f1",Nc=12,jc="system-ui, -apple-system, sans-serif",$o="Type a message...",Uc="bottom-right",Dc="light",Bc={x:20,y:20},ln="aikaara_conversation_id";class qo extends yr{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(e){super(),this.config=e;const t=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new an(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...s&&{source:s}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??Mc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Oc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const s=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new an(s),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const s=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${s}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class Ho{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,s){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=s}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const s=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(s,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(s,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const o=await n.json();if(o&&typeof o=="object"&&"success"in o){if(!o.success)throw new Error(`API error: ${o.message||"Request failed"}`);return o.data}return o}async fetchWithHeaders(e,t,r){const s={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(s["X-Api-Key"]=this.apiKey),this.authToken&&(s.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:s};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class Wo{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const s={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(s),s}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(s=>s.status==="sending"&&s.role===e.role&&s.content===e.content&&s.conversationId===e.conversationId&&Date.now()-new Date(s.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const s=zo(this._messages,e);return s?(Object.assign(s,e,{id:s.id}),{message:s,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(s=>s.externalId===e||s.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){const t=[];for(const r of e){const s=zo(t,r);if(s){const n=br(s),o=br(r);!n&&o&&Object.assign(s,r,{id:s.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function zo(i,e,t=15e3){const r=e.attachments&&e.attachments[0],s=(e.metadata??{}).attributes;if(!(!!r||!!(s&&s.fileMessage)))return null;const o=br(e),a=Vo(e),l=Go(e);if(!o&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=i.length-1;u>=0;u--){const d=i[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const y=(d.content||"").trim().toLowerCase();if(y==="file_uploaded"||y==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const b=br(d);if(o&&b&&o===b)return d;const w=Vo(d);if(a&&w&&a===w)return d;const m=Go(d);if(l&&m&&l===m)return d}return null}function Vo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=Ko(i);if(t)return t}function Go(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(i.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=i.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function br(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(i.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=Ko(i);if(r){const s=/[?&]cloudFileId=([^&]+)/.exec(r);if(s)return decodeURIComponent(s[1])}}function Ko(i){const e=i.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class Yo{_conversationId;persist;constructor(e,t=!0){this.persist=t,this._conversationId=e||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(e){this._conversationId=e,this.persist&&e&&this.saveToStorage(e)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(ln)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(ln)}catch{return null}}saveToStorage(e){try{localStorage.setItem(ln,e)}catch{}}}var cn=Object.defineProperty,Fc=Object.getOwnPropertyDescriptor,$c=Object.getOwnPropertyNames,qc=Object.prototype.hasOwnProperty,Je=(i,e)=>()=>(i&&(e=i(i=0)),e),pe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),$t=(i,e)=>{for(var t in e)cn(i,t,{get:e[t],enumerable:!0})},Hc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $c(e))!qc.call(i,s)&&s!==t&&cn(i,s,{get:()=>e[s],enumerable:!(r=Fc(e,s))||r.enumerable});return i},Ne=i=>Hc(cn({},"__esModule",{value:!0}),i),le=Je(()=>{}),je={};$t(je,{_debugEnd:()=>Wn,_debugProcess:()=>Hn,_events:()=>si,_eventsCount:()=>ai,_exiting:()=>Cn,_fatalExceptions:()=>Fn,_getActiveHandles:()=>rs,_getActiveRequests:()=>ts,_kill:()=>Mn,_linkedBinding:()=>Zo,_maxListeners:()=>oi,_preload_modules:()=>ri,_rawDebug:()=>An,_startProfilerIdleNotifier:()=>zn,_stopProfilerIdleNotifier:()=>Vn,_tickCallback:()=>qn,abort:()=>Jn,addListener:()=>li,allowedNodeEnvironmentFlags:()=>Dn,arch:()=>hn,argv:()=>mn,argv0:()=>ti,assert:()=>ns,binding:()=>wn,browser:()=>En,chdir:()=>Sn,config:()=>Pn,cpuUsage:()=>tr,cwd:()=>_n,debugPort:()=>ei,default:()=>gi,dlopen:()=>es,domain:()=>Tn,emit:()=>fi,emitWarning:()=>vn,env:()=>pn,execArgv:()=>gn,execPath:()=>Zn,exit:()=>jn,features:()=>Bn,hasUncaughtExceptionCaptureCallback:()=>is,hrtime:()=>vr,kill:()=>Nn,listeners:()=>ss,memoryUsage:()=>Rn,moduleLoadList:()=>In,nextTick:()=>Qo,off:()=>ui,on:()=>dt,once:()=>ci,openStdin:()=>Un,pid:()=>Qn,platform:()=>fn,ppid:()=>Xn,prependListener:()=>pi,prependOnceListener:()=>mi,reallyExit:()=>On,release:()=>xn,removeAllListeners:()=>hi,removeListener:()=>di,resourceUsage:()=>Ln,setSourceMapsEnabled:()=>ni,setUncaughtExceptionCaptureCallback:()=>$n,stderr:()=>Kn,stdin:()=>Yn,stdout:()=>Gn,title:()=>dn,umask:()=>kn,uptime:()=>os,version:()=>yn,versions:()=>bn});function un(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Wc(){!Ot||!Mt||(Ot=!1,Mt.length?nt=Mt.concat(nt):er=-1,nt.length&&Jo())}function Jo(){if(!Ot){var i=setTimeout(Wc,0);Ot=!0;for(var e=nt.length;e;){for(Mt=nt,nt=[];++er<e;)Mt&&Mt[er].run();er=-1,e=nt.length}Mt=null,Ot=!1,clearTimeout(i)}}function Qo(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];nt.push(new Xo(i,e)),nt.length===1&&!Ot&&setTimeout(Jo,0)}function Xo(i,e){this.fun=i,this.array=e}function He(){}function Zo(i){un("_linkedBinding")}function es(i){un("dlopen")}function ts(){return[]}function rs(){return[]}function ns(i,e){if(!i)throw new Error(e||"assertion error")}function is(){return!1}function os(){return ht.now()/1e3}function vr(i){var e=Math.floor((Date.now()-ht.now())*.001),t=ht.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=wr)),[r,s]}function dt(){return gi}function ss(i){return[]}var nt,Ot,Mt,er,dn,hn,fn,pn,mn,gn,yn,bn,vn,wn,kn,_n,Sn,xn,En,An,In,Tn,Cn,Pn,On,Mn,tr,Ln,Rn,Nn,jn,Un,Dn,Bn,Fn,$n,qn,Hn,Wn,zn,Vn,Gn,Kn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ht,ii,wr,oi,si,ai,li,ci,ui,di,hi,fi,pi,mi,gi,zc=Je(()=>{le(),ue(),ce(),nt=[],Ot=!1,er=-1,Xo.prototype.run=function(){this.fun.apply(null,this.array)},dn="browser",hn="x64",fn="browser",pn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},mn=["/usr/bin/node"],gn=[],yn="v16.8.0",bn={},vn=function(i,e){console.warn((e?e+": ":"")+i)},wn=function(i){un("binding")},kn=function(i){return 0},_n=function(){return"/"},Sn=function(i){},xn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},En=!0,An=He,In=[],Tn={},Cn=!1,Pn={},On=He,Mn=He,tr=function(){return{}},Ln=tr,Rn=tr,Nn=He,jn=He,Un=He,Dn={},Bn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Fn=He,$n=He,qn=He,Hn=He,Wn=He,zn=He,Vn=He,Gn=void 0,Kn=void 0,Yn=void 0,Jn=He,Qn=2,Xn=1,Zn="/bin/usr/node",ei=9229,ti="node",ri=[],ni=He,ht={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ht.now===void 0&&(ii=Date.now(),ht.timing&&ht.timing.navigationStart&&(ii=ht.timing.navigationStart),ht.now=()=>Date.now()-ii),wr=1e9,vr.bigint=function(i){var e=vr(i);return typeof BigInt>"u"?e[0]*wr+e[1]:BigInt(e[0]*wr)+BigInt(e[1])},oi=10,si={},ai=0,li=dt,ci=dt,ui=dt,di=dt,hi=dt,fi=He,pi=dt,mi=dt,gi={version:yn,versions:bn,arch:hn,platform:fn,browser:En,release:xn,_rawDebug:An,moduleLoadList:In,binding:wn,_linkedBinding:Zo,_events:si,_eventsCount:ai,_maxListeners:oi,on:dt,addListener:li,once:ci,off:ui,removeListener:di,removeAllListeners:hi,emit:fi,prependListener:pi,prependOnceListener:mi,listeners:ss,domain:Tn,_exiting:Cn,config:Pn,dlopen:es,uptime:os,_getActiveRequests:ts,_getActiveHandles:rs,reallyExit:On,_kill:Mn,cpuUsage:tr,resourceUsage:Ln,memoryUsage:Rn,kill:Nn,exit:jn,openStdin:Un,allowedNodeEnvironmentFlags:Dn,assert:ns,features:Bn,_fatalExceptions:Fn,setUncaughtExceptionCaptureCallback:$n,hasUncaughtExceptionCaptureCallback:is,emitWarning:vn,nextTick:Qo,_tickCallback:qn,_debugProcess:Hn,_debugEnd:Wn,_startProfilerIdleNotifier:zn,_stopProfilerIdleNotifier:Vn,stdout:Gn,stdin:Yn,stderr:Kn,abort:Jn,umask:kn,chdir:Sn,cwd:_n,env:pn,title:dn,argv:mn,execArgv:gn,pid:Qn,ppid:Xn,execPath:Zn,debugPort:ei,hrtime:vr,argv0:ti,_preload_modules:ri,setSourceMapsEnabled:ni}}),ce=Je(()=>{zc()});function Vc(){if(yi)return qt;yi=!0,qt.byteLength=a,qt.toByteArray=c,qt.fromByteArray=p;for(var i=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,n=r.length;s<n;++s)i[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function o(g){var f=g.length;if(f%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var y=g.indexOf("=");y===-1&&(y=f);var b=y===f?0:4-y%4;return[y,b]}function a(g){var f=o(g),y=f[0],b=f[1];return(y+b)*3/4-b}function l(g,f,y){return(f+y)*3/4-y}function c(g){var f,y=o(g),b=y[0],w=y[1],m=new t(l(g,b,w)),k=0,S=w>0?b-4:b,v;for(v=0;v<S;v+=4)f=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=f>>16&255,m[k++]=f>>8&255,m[k++]=f&255;return w===2&&(f=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=f&255),w===1&&(f=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=f>>8&255,m[k++]=f&255),m}function u(g){return i[g>>18&63]+i[g>>12&63]+i[g>>6&63]+i[g&63]}function d(g,f,y){for(var b,w=[],m=f;m<y;m+=3)b=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(b));return w.join("")}function p(g){for(var f,y=g.length,b=y%3,w=[],m=16383,k=0,S=y-b;k<S;k+=m)w.push(d(g,k,k+m>S?S:k+m));return b===1?(f=g[y-1],w.push(i[f>>2]+i[f<<4&63]+"==")):b===2&&(f=(g[y-2]<<8)+g[y-1],w.push(i[f>>10]+i[f>>4&63]+i[f<<2&63]+"=")),w.join("")}return qt}function Gc(){return bi?rr:(bi=!0,rr.read=function(i,e,t,r,s){var n,o,a=s*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?s-1:0,p=t?-1:1,g=i[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=p,u-=8);for(o=n&(1<<-u)-1,n>>=-u,u+=r;u>0;o=o*256+i[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return o?NaN:(g?-1:1)*(1/0);o=o+Math.pow(2,r),n=n-c}return(g?-1:1)*o*Math.pow(2,n-r)},rr.write=function(i,e,t,r,s,n){var o,a,l,c=n*8-s-1,u=(1<<c)-1,d=u>>1,p=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,f=r?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),o+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(o++,l/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(e*l-1)*Math.pow(2,s),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,s),o=0));s>=8;i[t+g]=a&255,g+=f,a/=256,s-=8);for(o=o<<s|a,c+=s;c>0;i[t+g]=o&255,g+=f,o/=256,c-=8);i[t+g-f]|=y*128},rr)}function Kc(){if(vi)return St;vi=!0;let i=Vc(),e=Gc(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;St.Buffer=o,St.SlowBuffer=w,St.INSPECT_MAX_BYTES=50;let r=2147483647;St.kMaxLength=r,o.TYPED_ARRAY_SUPPORT=s(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{let h=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(h,_),h.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function n(h){if(h>r)throw new RangeError('The value "'+h+'" is invalid for option "size"');let _=new Uint8Array(h);return Object.setPrototypeOf(_,o.prototype),_}function o(h,_,A){if(typeof h=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(h)}return a(h,_,A)}o.poolSize=8192;function a(h,_,A){if(typeof h=="string")return d(h,_);if(ArrayBuffer.isView(h))return g(h);if(h==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h);if(H(h,ArrayBuffer)||h&&H(h.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(h,SharedArrayBuffer)||h&&H(h.buffer,SharedArrayBuffer)))return f(h,_,A);if(typeof h=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let F=h.valueOf&&h.valueOf();if(F!=null&&F!==h)return o.from(F,_,A);let Z=y(h);if(Z)return Z;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof h[Symbol.toPrimitive]=="function")return o.from(h[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof h)}o.from=function(h,_,A){return a(h,_,A)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function l(h){if(typeof h!="number")throw new TypeError('"size" argument must be of type number');if(h<0)throw new RangeError('The value "'+h+'" is invalid for option "size"')}function c(h,_,A){return l(h),h<=0?n(h):_!==void 0?typeof A=="string"?n(h).fill(_,A):n(h).fill(_):n(h)}o.alloc=function(h,_,A){return c(h,_,A)};function u(h){return l(h),n(h<0?0:b(h)|0)}o.allocUnsafe=function(h){return u(h)},o.allocUnsafeSlow=function(h){return u(h)};function d(h,_){if((typeof _!="string"||_==="")&&(_="utf8"),!o.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(h,_)|0,F=n(A),Z=F.write(h,_);return Z!==A&&(F=F.slice(0,Z)),F}function p(h){let _=h.length<0?0:b(h.length)|0,A=n(_);for(let F=0;F<_;F+=1)A[F]=h[F]&255;return A}function g(h){if(H(h,Uint8Array)){let _=new Uint8Array(h);return f(_.buffer,_.byteOffset,_.byteLength)}return p(h)}function f(h,_,A){if(_<0||h.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(h.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let F;return _===void 0&&A===void 0?F=new Uint8Array(h):A===void 0?F=new Uint8Array(h,_):F=new Uint8Array(h,_,A),Object.setPrototypeOf(F,o.prototype),F}function y(h){if(o.isBuffer(h)){let _=b(h.length)|0,A=n(_);return A.length===0||h.copy(A,0,0,_),A}if(h.length!==void 0)return typeof h.length!="number"||me(h.length)?n(0):p(h);if(h.type==="Buffer"&&Array.isArray(h.data))return p(h.data)}function b(h){if(h>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return h|0}function w(h){return+h!=h&&(h=0),o.alloc(+h)}o.isBuffer=function(h){return h!=null&&h._isBuffer===!0&&h!==o.prototype},o.compare=function(h,_){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),H(_,Uint8Array)&&(_=o.from(_,_.offset,_.byteLength)),!o.isBuffer(h)||!o.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(h===_)return 0;let A=h.length,F=_.length;for(let Z=0,de=Math.min(A,F);Z<de;++Z)if(h[Z]!==_[Z]){A=h[Z],F=_[Z];break}return A<F?-1:F<A?1:0},o.isEncoding=function(h){switch(String(h).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(h,_){if(!Array.isArray(h))throw new TypeError('"list" argument must be an Array of Buffers');if(h.length===0)return o.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<h.length;++A)_+=h[A].length;let F=o.allocUnsafe(_),Z=0;for(A=0;A<h.length;++A){let de=h[A];if(H(de,Uint8Array))Z+de.length>F.length?(o.isBuffer(de)||(de=o.from(de)),de.copy(F,Z)):Uint8Array.prototype.set.call(F,de,Z);else if(o.isBuffer(de))de.copy(F,Z);else throw new TypeError('"list" argument must be an Array of Buffers');Z+=de.length}return F};function m(h,_){if(o.isBuffer(h))return h.length;if(ArrayBuffer.isView(h)||H(h,ArrayBuffer))return h.byteLength;if(typeof h!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof h);let A=h.length,F=arguments.length>2&&arguments[2]===!0;if(!F&&A===0)return 0;let Z=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return q(h).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return fe(h).length;default:if(Z)return F?-1:q(h).length;_=(""+_).toLowerCase(),Z=!0}}o.byteLength=m;function k(h,_,A){let F=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(h||(h="utf8");;)switch(h){case"hex":return W(this,_,A);case"utf8":case"utf-8":return $(this,_,A);case"ascii":return oe(this,_,A);case"latin1":case"binary":return Y(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,_,A);default:if(F)throw new TypeError("Unknown encoding: "+h);h=(h+"").toLowerCase(),F=!0}}o.prototype._isBuffer=!0;function S(h,_,A){let F=h[_];h[_]=h[A],h[A]=F}o.prototype.swap16=function(){let h=this.length;if(h%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<h;_+=2)S(this,_,_+1);return this},o.prototype.swap32=function(){let h=this.length;if(h%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<h;_+=4)S(this,_,_+3),S(this,_+1,_+2);return this},o.prototype.swap64=function(){let h=this.length;if(h%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<h;_+=8)S(this,_,_+7),S(this,_+1,_+6),S(this,_+2,_+5),S(this,_+3,_+4);return this},o.prototype.toString=function(){let h=this.length;return h===0?"":arguments.length===0?$(this,0,h):k.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(h){if(!o.isBuffer(h))throw new TypeError("Argument must be a Buffer");return this===h?!0:o.compare(this,h)===0},o.prototype.inspect=function(){let h="",_=St.INSPECT_MAX_BYTES;return h=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(h+=" ... "),"<Buffer "+h+">"},t&&(o.prototype[t]=o.prototype.inspect),o.prototype.compare=function(h,_,A,F,Z){if(H(h,Uint8Array)&&(h=o.from(h,h.offset,h.byteLength)),!o.isBuffer(h))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof h);if(_===void 0&&(_=0),A===void 0&&(A=h?h.length:0),F===void 0&&(F=0),Z===void 0&&(Z=this.length),_<0||A>h.length||F<0||Z>this.length)throw new RangeError("out of range index");if(F>=Z&&_>=A)return 0;if(F>=Z)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,F>>>=0,Z>>>=0,this===h)return 0;let de=Z-F,_e=A-_,V=Math.min(de,_e),ie=this.slice(F,Z),Ie=h.slice(_,A);for(let Te=0;Te<V;++Te)if(ie[Te]!==Ie[Te]){de=ie[Te],_e=Ie[Te];break}return de<_e?-1:_e<de?1:0};function v(h,_,A,F,Z){if(h.length===0)return-1;if(typeof A=="string"?(F=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 _=="string"&&(_=o.from(_,F)),o.isBuffer(_))return _.length===0?-1:x(h,_,A,F,Z);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?Z?Uint8Array.prototype.indexOf.call(h,_,A):Uint8Array.prototype.lastIndexOf.call(h,_,A):x(h,[_],A,F,Z);throw new TypeError("val must be string, number or Buffer")}function x(h,_,A,F,Z){let de=1,_e=h.length,V=_.length;if(F!==void 0&&(F=String(F).toLowerCase(),F==="ucs2"||F==="ucs-2"||F==="utf16le"||F==="utf-16le")){if(h.length<2||_.length<2)return-1;de=2,_e/=2,V/=2,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<_e;Ie++)if(ie(h,Ie)===ie(_,Te===-1?0:Ie-Te)){if(Te===-1&&(Te=Ie),Ie-Te+1===V)return Te*de}else Te!==-1&&(Ie-=Ie-Te),Te=-1}else for(A+V>_e&&(A=_e-V),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Pe=0;Pe<V;Pe++)if(ie(h,Ie+Pe)!==ie(_,Pe)){Te=!1;break}if(Te)return Ie}return-1}o.prototype.includes=function(h,_,A){return this.indexOf(h,_,A)!==-1},o.prototype.indexOf=function(h,_,A){return v(this,h,_,A,!0)},o.prototype.lastIndexOf=function(h,_,A){return v(this,h,_,A,!1)};function E(h,_,A,F){A=Number(A)||0;let Z=h.length-A;F?(F=Number(F),F>Z&&(F=Z)):F=Z;let de=_.length;F>de/2&&(F=de/2);let _e;for(_e=0;_e<F;++_e){let V=parseInt(_.substr(_e*2,2),16);if(me(V))return _e;h[A+_e]=V}return _e}function I(h,_,A,F){return be(q(_,h.length-A),h,A,F)}function P(h,_,A,F){return be(te(_),h,A,F)}function O(h,_,A,F){return be(fe(_),h,A,F)}function B(h,_,A,F){return be(he(_,h.length-A),h,A,F)}o.prototype.write=function(h,_,A,F){if(_===void 0)F="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")F=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,F===void 0&&(F="utf8")):(F=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Z=this.length-_;if((A===void 0||A>Z)&&(A=Z),h.length>0&&(A<0||_<0)||_>this.length)throw new RangeError("Attempt to write outside buffer bounds");F||(F="utf8");let de=!1;for(;;)switch(F){case"hex":return E(this,h,_,A);case"utf8":case"utf-8":return I(this,h,_,A);case"ascii":case"latin1":case"binary":return P(this,h,_,A);case"base64":return O(this,h,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,h,_,A);default:if(de)throw new TypeError("Unknown encoding: "+F);F=(""+F).toLowerCase(),de=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function T(h,_,A){return _===0&&A===h.length?i.fromByteArray(h):i.fromByteArray(h.slice(_,A))}function $(h,_,A){A=Math.min(h.length,A);let F=[],Z=_;for(;Z<A;){let de=h[Z],_e=null,V=de>239?4:de>223?3:de>191?2:1;if(Z+V<=A){let ie,Ie,Te,Pe;switch(V){case 1:de<128&&(_e=de);break;case 2:ie=h[Z+1],(ie&192)===128&&(Pe=(de&31)<<6|ie&63,Pe>127&&(_e=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)&&(_e=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&&(_e=Pe))}}_e===null?(_e=65533,V=1):_e>65535&&(_e-=65536,F.push(_e>>>10&1023|55296),_e=56320|_e&1023),F.push(_e),Z+=V}return U(F)}let M=4096;function U(h){let _=h.length;if(_<=M)return String.fromCharCode.apply(String,h);let A="",F=0;for(;F<_;)A+=String.fromCharCode.apply(String,h.slice(F,F+=M));return A}function oe(h,_,A){let F="";A=Math.min(h.length,A);for(let Z=_;Z<A;++Z)F+=String.fromCharCode(h[Z]&127);return F}function Y(h,_,A){let F="";A=Math.min(h.length,A);for(let Z=_;Z<A;++Z)F+=String.fromCharCode(h[Z]);return F}function W(h,_,A){let F=h.length;(!_||_<0)&&(_=0),(!A||A<0||A>F)&&(A=F);let Z="";for(let de=_;de<A;++de)Z+=ve[h[de]];return Z}function ee(h,_,A){let F=h.slice(_,A),Z="";for(let de=0;de<F.length-1;de+=2)Z+=String.fromCharCode(F[de]+F[de+1]*256);return Z}o.prototype.slice=function(h,_){let A=this.length;h=~~h,_=_===void 0?A:~~_,h<0?(h+=A,h<0&&(h=0)):h>A&&(h=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<h&&(_=h);let F=this.subarray(h,_);return Object.setPrototypeOf(F,o.prototype),F};function D(h,_,A){if(h%1!==0||h<0)throw new RangeError("offset is not uint");if(h+_>A)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let F=this[h],Z=1,de=0;for(;++de<_&&(Z*=256);)F+=this[h+de]*Z;return F},o.prototype.readUintBE=o.prototype.readUIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let F=this[h+--_],Z=1;for(;_>0&&(Z*=256);)F+=this[h+--_]*Z;return F},o.prototype.readUint8=o.prototype.readUInt8=function(h,_){return h=h>>>0,_||D(h,1,this.length),this[h]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(h,_){return h=h>>>0,_||D(h,2,this.length),this[h]|this[h+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(h,_){return h=h>>>0,_||D(h,2,this.length),this[h]<<8|this[h+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(h,_){return h=h>>>0,_||D(h,4,this.length),(this[h]|this[h+1]<<8|this[h+2]<<16)+this[h+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]*16777216+(this[h+1]<<16|this[h+2]<<8|this[h+3])},o.prototype.readBigUInt64LE=ae(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ye(h,this.length-8);let F=_+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(F)+(BigInt(Z)<<BigInt(32))}),o.prototype.readBigUInt64BE=ae(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ye(h,this.length-8);let F=_*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(F)<<BigInt(32))+BigInt(Z)}),o.prototype.readIntLE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let F=this[h],Z=1,de=0;for(;++de<_&&(Z*=256);)F+=this[h+de]*Z;return Z*=128,F>=Z&&(F-=Math.pow(2,8*_)),F},o.prototype.readIntBE=function(h,_,A){h=h>>>0,_=_>>>0,A||D(h,_,this.length);let F=_,Z=1,de=this[h+--F];for(;F>0&&(Z*=256);)de+=this[h+--F]*Z;return Z*=128,de>=Z&&(de-=Math.pow(2,8*_)),de},o.prototype.readInt8=function(h,_){return h=h>>>0,_||D(h,1,this.length),this[h]&128?(255-this[h]+1)*-1:this[h]},o.prototype.readInt16LE=function(h,_){h=h>>>0,_||D(h,2,this.length);let A=this[h]|this[h+1]<<8;return A&32768?A|4294901760:A},o.prototype.readInt16BE=function(h,_){h=h>>>0,_||D(h,2,this.length);let A=this[h+1]|this[h]<<8;return A&32768?A|4294901760:A},o.prototype.readInt32LE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]|this[h+1]<<8|this[h+2]<<16|this[h+3]<<24},o.prototype.readInt32BE=function(h,_){return h=h>>>0,_||D(h,4,this.length),this[h]<<24|this[h+1]<<16|this[h+2]<<8|this[h+3]},o.prototype.readBigInt64LE=ae(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ye(h,this.length-8);let F=this[h+4]+this[h+5]*2**8+this[h+6]*2**16+(A<<24);return(BigInt(F)<<BigInt(32))+BigInt(_+this[++h]*256+this[++h]*65536+this[++h]*16777216)}),o.prototype.readBigInt64BE=ae(function(h){h=h>>>0,Q(h,"offset");let _=this[h],A=this[h+7];(_===void 0||A===void 0)&&ye(h,this.length-8);let F=(_<<24)+this[++h]*2**16+this[++h]*2**8+this[++h];return(BigInt(F)<<BigInt(32))+BigInt(this[++h]*16777216+this[++h]*65536+this[++h]*256+A)}),o.prototype.readFloatLE=function(h,_){return h=h>>>0,_||D(h,4,this.length),e.read(this,h,!0,23,4)},o.prototype.readFloatBE=function(h,_){return h=h>>>0,_||D(h,4,this.length),e.read(this,h,!1,23,4)},o.prototype.readDoubleLE=function(h,_){return h=h>>>0,_||D(h,8,this.length),e.read(this,h,!0,52,8)},o.prototype.readDoubleBE=function(h,_){return h=h>>>0,_||D(h,8,this.length),e.read(this,h,!1,52,8)};function X(h,_,A,F,Z,de){if(!o.isBuffer(h))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>Z||_<de)throw new RangeError('"value" argument is out of bounds');if(A+F>h.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(h,_,A,F){if(h=+h,_=_>>>0,A=A>>>0,!F){let _e=Math.pow(2,8*A)-1;X(this,h,_,A,_e,0)}let Z=1,de=0;for(this[_]=h&255;++de<A&&(Z*=256);)this[_+de]=h/Z&255;return _+A},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(h,_,A,F){if(h=+h,_=_>>>0,A=A>>>0,!F){let _e=Math.pow(2,8*A)-1;X(this,h,_,A,_e,0)}let Z=A-1,de=1;for(this[_+Z]=h&255;--Z>=0&&(de*=256);)this[_+Z]=h/de&255;return _+A},o.prototype.writeUint8=o.prototype.writeUInt8=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,1,255,0),this[_]=h&255,_+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,2,65535,0),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,2,65535,0),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,4,4294967295,0),this[_+3]=h>>>24,this[_+2]=h>>>16,this[_+1]=h>>>8,this[_]=h&255,_+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,4,4294967295,0),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4};function L(h,_,A,F,Z){K(_,F,Z,h,A,7);let de=Number(_&BigInt(4294967295));h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de,de=de>>8,h[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[A++]=_e,_e=_e>>8,h[A++]=_e,_e=_e>>8,h[A++]=_e,_e=_e>>8,h[A++]=_e,A}function J(h,_,A,F,Z){K(_,F,Z,h,A,7);let de=Number(_&BigInt(4294967295));h[A+7]=de,de=de>>8,h[A+6]=de,de=de>>8,h[A+5]=de,de=de>>8,h[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return h[A+3]=_e,_e=_e>>8,h[A+2]=_e,_e=_e>>8,h[A+1]=_e,_e=_e>>8,h[A]=_e,A+8}o.prototype.writeBigUInt64LE=ae(function(h,_=0){return L(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=ae(function(h,_=0){return J(this,h,_,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(h,_,A,F){if(h=+h,_=_>>>0,!F){let V=Math.pow(2,8*A-1);X(this,h,_,A,V-1,-V)}let Z=0,de=1,_e=0;for(this[_]=h&255;++Z<A&&(de*=256);)h<0&&_e===0&&this[_+Z-1]!==0&&(_e=1),this[_+Z]=(h/de>>0)-_e&255;return _+A},o.prototype.writeIntBE=function(h,_,A,F){if(h=+h,_=_>>>0,!F){let V=Math.pow(2,8*A-1);X(this,h,_,A,V-1,-V)}let Z=A-1,de=1,_e=0;for(this[_+Z]=h&255;--Z>=0&&(de*=256);)h<0&&_e===0&&this[_+Z+1]!==0&&(_e=1),this[_+Z]=(h/de>>0)-_e&255;return _+A},o.prototype.writeInt8=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,1,127,-128),h<0&&(h=255+h+1),this[_]=h&255,_+1},o.prototype.writeInt16LE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,2,32767,-32768),this[_]=h&255,this[_+1]=h>>>8,_+2},o.prototype.writeInt16BE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,2,32767,-32768),this[_]=h>>>8,this[_+1]=h&255,_+2},o.prototype.writeInt32LE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,4,2147483647,-2147483648),this[_]=h&255,this[_+1]=h>>>8,this[_+2]=h>>>16,this[_+3]=h>>>24,_+4},o.prototype.writeInt32BE=function(h,_,A){return h=+h,_=_>>>0,A||X(this,h,_,4,2147483647,-2147483648),h<0&&(h=4294967295+h+1),this[_]=h>>>24,this[_+1]=h>>>16,this[_+2]=h>>>8,this[_+3]=h&255,_+4},o.prototype.writeBigInt64LE=ae(function(h,_=0){return L(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=ae(function(h,_=0){return J(this,h,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ge(h,_,A,F,Z,de){if(A+F>h.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function re(h,_,A,F,Z){return _=+_,A=A>>>0,Z||ge(h,_,A,4),e.write(h,_,A,F,23,4),A+4}o.prototype.writeFloatLE=function(h,_,A){return re(this,h,_,!0,A)},o.prototype.writeFloatBE=function(h,_,A){return re(this,h,_,!1,A)};function we(h,_,A,F,Z){return _=+_,A=A>>>0,Z||ge(h,_,A,8),e.write(h,_,A,F,52,8),A+8}o.prototype.writeDoubleLE=function(h,_,A){return we(this,h,_,!0,A)},o.prototype.writeDoubleBE=function(h,_,A){return we(this,h,_,!1,A)},o.prototype.copy=function(h,_,A,F){if(!o.isBuffer(h))throw new TypeError("argument should be a Buffer");if(A||(A=0),!F&&F!==0&&(F=this.length),_>=h.length&&(_=h.length),_||(_=0),F>0&&F<A&&(F=A),F===A||h.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(F<0)throw new RangeError("sourceEnd out of bounds");F>this.length&&(F=this.length),h.length-_<F-A&&(F=h.length-_+A);let Z=F-A;return this===h&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,F):Uint8Array.prototype.set.call(h,this.subarray(A,F),_),Z},o.prototype.fill=function(h,_,A,F){if(typeof h=="string"){if(typeof _=="string"?(F=_,_=0,A=this.length):typeof A=="string"&&(F=A,A=this.length),F!==void 0&&typeof F!="string")throw new TypeError("encoding must be a string");if(typeof F=="string"&&!o.isEncoding(F))throw new TypeError("Unknown encoding: "+F);if(h.length===1){let de=h.charCodeAt(0);(F==="utf8"&&de<128||F==="latin1")&&(h=de)}}else typeof h=="number"?h=h&255:typeof h=="boolean"&&(h=Number(h));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,h||(h=0);let Z;if(typeof h=="number")for(Z=_;Z<A;++Z)this[Z]=h;else{let de=o.isBuffer(h)?h:o.from(h,F),_e=de.length;if(_e===0)throw new TypeError('The value "'+h+'" is invalid for argument "value"');for(Z=0;Z<A-_;++Z)this[Z+_]=de[Z%_e]}return this};let G={};function j(h,_,A){G[h]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${h}]`,this.stack,delete this.name}get code(){return h}set code(F){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:F,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,_){return`The "${h}" argument must be of type number. Received type ${typeof _}`},TypeError),j("ERR_OUT_OF_RANGE",function(h,_,A){let F=`The value of "${h}" is out of range.`,Z=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?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"),F+=` It must be ${_}. Received ${Z}`,F},RangeError);function ne(h){let _="",A=h.length,F=h[0]==="-"?1:0;for(;A>=F+4;A-=3)_=`_${h.slice(A-3,A)}${_}`;return`${h.slice(0,A)}${_}`}function z(h,_,A){Q(_,"offset"),(h[_]===void 0||h[_+A]===void 0)&&ye(_,h.length-(A+1))}function K(h,_,A,F,Z,de){if(h>A||h<_){let _e=typeof _=="bigint"?"n":"",V;throw _===0||_===BigInt(0)?V=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:V=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new G.ERR_OUT_OF_RANGE("value",V,h)}z(F,Z,de)}function Q(h,_){if(typeof h!="number")throw new G.ERR_INVALID_ARG_TYPE(_,"number",h)}function ye(h,_,A){throw Math.floor(h)!==h?(Q(h,A),new G.ERR_OUT_OF_RANGE("offset","an integer",h)):_<0?new G.ERR_BUFFER_OUT_OF_BOUNDS:new G.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,h)}let se=/[^+/0-9A-Za-z-_]/g;function R(h){if(h=h.split("=")[0],h=h.trim().replace(se,""),h.length<2)return"";for(;h.length%4!==0;)h=h+"=";return h}function q(h,_){_=_||1/0;let A,F=h.length,Z=null,de=[];for(let _e=0;_e<F;++_e){if(A=h.charCodeAt(_e),A>55295&&A<57344){if(!Z){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===F){(_-=3)>-1&&de.push(239,191,189);continue}Z=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),Z=A;continue}A=(Z-55296<<10|A-56320)+65536}else Z&&(_-=3)>-1&&de.push(239,191,189);if(Z=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function te(h){let _=[];for(let A=0;A<h.length;++A)_.push(h.charCodeAt(A)&255);return _}function he(h,_){let A,F,Z,de=[];for(let _e=0;_e<h.length&&!((_-=2)<0);++_e)A=h.charCodeAt(_e),F=A>>8,Z=A%256,de.push(Z),de.push(F);return de}function fe(h){return i.toByteArray(R(h))}function be(h,_,A,F){let Z;for(Z=0;Z<F&&!(Z+A>=_.length||Z>=h.length);++Z)_[Z+A]=h[Z];return Z}function H(h,_){return h instanceof _||h!=null&&h.constructor!=null&&h.constructor.name!=null&&h.constructor.name===_.name}function me(h){return h!==h}let ve=(function(){let h="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let F=A*16;for(let Z=0;Z<16;++Z)_[F+Z]=h[A]+h[Z]}return _})();function ae(h){return typeof BigInt>"u"?Oe:h}function Oe(){throw new Error("BigInt not supported")}return St}var qt,yi,rr,bi,St,vi,Yc=Je(()=>{le(),ue(),ce(),qt={},yi=!1,rr={},bi=!1,St={},vi=!1}),$e={};$t($e,{Buffer:()=>kr,INSPECT_MAX_BYTES:()=>as,default:()=>ft,kMaxLength:()=>ls});var ft,kr,as,ls,qe=Je(()=>{le(),ue(),ce(),Yc(),ft=Kc(),ft.Buffer,ft.SlowBuffer,ft.INSPECT_MAX_BYTES,ft.kMaxLength,kr=ft.Buffer,as=ft.INSPECT_MAX_BYTES,ls=ft.kMaxLength}),ue=Je(()=>{qe()}),Be=pe((i,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let s="";for(let n=0;n<r.length;n++)s+=` ${r[n].stack}
|
|
2
|
-
`;super(s),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,s){return r.includes(s)},ArrayPrototypeIndexOf(r,s){return r.indexOf(s)},ArrayPrototypeJoin(r,s){return r.join(s)},ArrayPrototypeMap(r,s){return r.map(s)},ArrayPrototypePop(r,s){return r.pop(s)},ArrayPrototypePush(r,s){return r.push(s)},ArrayPrototypeSlice(r,s,n){return r.slice(s,n)},Error,FunctionPrototypeCall(r,s,...n){return r.call(s,...n)},FunctionPrototypeSymbolHasInstance(r,s){return Function.prototype[Symbol.hasInstance].call(r,s)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,s){return Object.defineProperties(r,s)},ObjectDefineProperty(r,s,n){return Object.defineProperty(r,s,n)},ObjectGetOwnPropertyDescriptor(r,s){return Object.getOwnPropertyDescriptor(r,s)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,s){return Object.setPrototypeOf(r,s)},Promise,PromisePrototypeCatch(r,s){return r.catch(s)},PromisePrototypeThen(r,s,n){return r.then(s,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,s){return r.test(s)},SafeSet:Set,String,StringPrototypeSlice(r,s,n){return r.slice(s,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,s,n){return r.set(s,n)},Boolean,Uint8Array}}),cs=pe((i,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[s,n]){let o=r.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),Ke=pe((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=cs(),{AggregateError:s}=Be(),n=globalThis.AggregateError||s,o=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function p(m){let k="",S=m.length,v=m[0]==="-"?1:0;for(;S>=v+4;S-=3)k=`_${m.slice(S-3,S)}${k}`;return`${m.slice(0,S)}${k}`}function g(m,k,S){if(typeof k=="function")return d(k.length<=S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${k.length}).`),k(...S);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===S.length,`Code: ${m}; The provided arguments length (${S.length}) does not match the required ones (${v}).`),S.length===0?k:t(k,...S)}function f(m,k,S){S||(S=Error);class v extends S{constructor(...E){super(g(m,k,E))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:S.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${m}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),v.prototype.code=m,v.prototype[o]=!0,u[m]=v}function y(m){let k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function b(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let S=new n([k,m],k.message);return S.code=k.code,S}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};f("ERR_ASSERTION","%s",Error),f("ERR_INVALID_ARG_TYPE",(m,k,S)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let x=[],E=[],I=[];for(let O of k)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?x.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=x.indexOf("object");O!==-1&&(x.splice(x,O,1),E.push("Object"))}if(x.length>0){switch(x.length){case 1:v+=`of type ${x[0]}`;break;case 2:v+=`one of type ${x[0]} or ${x[1]}`;break;default:{let O=x.pop();v+=`one of type ${x.join(", ")}, or ${O}`}}(E.length>0||I.length>0)&&(v+=" or ")}if(E.length>0){switch(E.length){case 1:v+=`an instance of ${E[0]}`;break;case 2:v+=`an instance of ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`an instance of ${E.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(S==null)v+=`. Received ${S}`;else if(typeof S=="function"&&S.name)v+=`. Received function ${S.name}`;else if(typeof S=="object"){var P;if((P=S.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${S.constructor.name}`;else{let O=r(S,{depth:-1});v+=`. Received ${O}`}}else{let O=r(S,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof S} (${O})`}return v},TypeError),f("ERR_INVALID_ARG_VALUE",(m,k,S="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${S}. Received ${v}`},TypeError),f("ERR_INVALID_RETURN_VALUE",(m,k,S)=>{var v;let x=S!=null&&(v=S.constructor)!==null&&v!==void 0&&v.name?`instance of ${S.constructor.name}`:`type ${typeof S}`;return`Expected ${m} to be returned from the "${k}" function but got ${x}.`},TypeError),f("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,S=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),S){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),f("ERR_OUT_OF_RANGE",(m,k,S)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(S)&&Math.abs(S)>2**32)v=p(String(S));else if(typeof S=="bigint"){v=String(S);let x=BigInt(2)**BigInt(32);(S>x||S<-x)&&(v=p(v)),v+="n"}else v=r(S);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),f("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),f("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),f("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),f("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),f("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),f("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),f("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),f("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),f("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),f("ERR_STREAM_WRITE_AFTER_END","write after end",Error),f("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:y(b),hideStackFrames:y,codes:u}}),nr=pe((i,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),xt={};$t(xt,{EventEmitter:()=>us,default:()=>Ht,defaultMaxListeners:()=>ds,init:()=>hs,listenerCount:()=>fs,on:()=>ps,once:()=>ms});function Jc(){if(wi)return ir;wi=!0;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,v,x){return Function.prototype.apply.call(S,v,x)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function r(S){console&&console.warn&&console.warn(S)}var s=Number.isNaN||function(S){return S!==S};function n(){n.init.call(this)}ir=n,ir.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");o=S}}),n.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function l(S){return S._maxListeners===void 0?n.defaultMaxListeners:S._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(S){for(var v=[],x=1;x<arguments.length;x++)v.push(arguments[x]);var E=S==="error",I=this._events;if(I!==void 0)E=E&&I.error===void 0;else if(!E)return!1;if(E){var P;if(v.length>0&&(P=v[0]),P instanceof Error)throw P;var O=new Error("Unhandled error."+(P?" ("+P.message+")":""));throw O.context=P,O}var B=I[S];if(B===void 0)return!1;if(typeof B=="function")e(B,this,v);else for(var T=B.length,$=f(B,T),x=0;x<T;++x)e($[x],this,v);return!0};function c(S,v,x,E){var I,P,O;if(a(x),P=S._events,P===void 0?(P=S._events=Object.create(null),S._eventsCount=0):(P.newListener!==void 0&&(S.emit("newListener",v,x.listener?x.listener:x),P=S._events),O=P[v]),O===void 0)O=P[v]=x,++S._eventsCount;else if(typeof O=="function"?O=P[v]=E?[x,O]:[O,x]:E?O.unshift(x):O.push(x),I=l(S),I>0&&O.length>I&&!O.warned){O.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");B.name="MaxListenersExceededWarning",B.emitter=S,B.type=v,B.count=O.length,r(B)}return S}n.prototype.addListener=function(S,v){return c(this,S,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(S,v){return c(this,S,v,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(S,v,x){var E={fired:!1,wrapFn:void 0,target:S,type:v,listener:x},I=u.bind(E);return I.listener=x,E.wrapFn=I,I}n.prototype.once=function(S,v){return a(v),this.on(S,d(this,S,v)),this},n.prototype.prependOnceListener=function(S,v){return a(v),this.prependListener(S,d(this,S,v)),this},n.prototype.removeListener=function(S,v){var x,E,I,P,O;if(a(v),E=this._events,E===void 0)return this;if(x=E[S],x===void 0)return this;if(x===v||x.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete E[S],E.removeListener&&this.emit("removeListener",S,x.listener||v));else if(typeof x!="function"){for(I=-1,P=x.length-1;P>=0;P--)if(x[P]===v||x[P].listener===v){O=x[P].listener,I=P;break}if(I<0)return this;I===0?x.shift():y(x,I),x.length===1&&(E[S]=x[0]),E.removeListener!==void 0&&this.emit("removeListener",S,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(S){var v,x,E;if(x=this._events,x===void 0)return this;if(x.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):x[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete x[S]),this;if(arguments.length===0){var I=Object.keys(x),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=x[S],typeof v=="function")this.removeListener(S,v);else if(v!==void 0)for(E=v.length-1;E>=0;E--)this.removeListener(S,v[E]);return this};function p(S,v,x){var E=S._events;if(E===void 0)return[];var I=E[v];return I===void 0?[]:typeof I=="function"?x?[I.listener||I]:[I]:x?b(I):f(I,I.length)}n.prototype.listeners=function(S){return p(this,S,!0)},n.prototype.rawListeners=function(S){return p(this,S,!1)},n.listenerCount=function(S,v){return typeof S.listenerCount=="function"?S.listenerCount(v):g.call(S,v)},n.prototype.listenerCount=g;function g(S){var v=this._events;if(v!==void 0){var x=v[S];if(typeof x=="function")return 1;if(x!==void 0)return x.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(S,v){for(var x=new Array(v),E=0;E<v;++E)x[E]=S[E];return x}function y(S,v){for(;v+1<S.length;v++)S[v]=S[v+1];S.pop()}function b(S){for(var v=new Array(S.length),x=0;x<v.length;++x)v[x]=S[x].listener||S[x];return v}function w(S,v){return new Promise(function(x,E){function I(O){S.removeListener(v,P),E(O)}function P(){typeof S.removeListener=="function"&&S.removeListener("error",I),x([].slice.call(arguments))}k(S,v,P,{once:!0}),v!=="error"&&m(S,I,{once:!0})})}function m(S,v,x){typeof S.on=="function"&&k(S,"error",v,x)}function k(S,v,x,E){if(typeof S.on=="function")E.once?S.once(v,x):S.on(v,x);else if(typeof S.addEventListener=="function")S.addEventListener(v,function I(P){E.once&&S.removeEventListener(v,I),x(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}return ir}var ir,wi,Ht,us,ds,hs,fs,ps,ms,Lt=Je(()=>{le(),ue(),ce(),ir={},wi=!1,Ht=Jc(),Ht.once,Ht.once=function(i,e){return new Promise((t,r)=>{function s(...o){n!==void 0&&i.removeListener("error",n),t(o)}let n;e!=="error"&&(n=o=>{i.removeListener(name,s),r(o)},i.once("error",n)),i.once(e,s)})},Ht.on=function(i,e){let t=[],r=[],s=null,n=!1,o={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(s){let u=Promise.reject(s);return s=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){i.removeListener(e,a),i.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){s=c,i.removeListener(e,a),i.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return i.on(e,a),i.on("error",l),o;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):s=c,o.return()}},{EventEmitter:us,defaultMaxListeners:ds,init:hs,listenerCount:fs,on:ps,once:ms}=Ht}),Qe=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),{format:r,inspect:s}=cs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ke(),{kResistStopPropagation:o,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||nr().AbortSignal,u=globalThis.AbortController||nr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(b){return b instanceof p}:function(b){return!1},f=(b,w)=>{if(b!==void 0&&(b===null||typeof b!="object"||!("aborted"in b)))throw new n(w,"AbortSignal",b)},y=(b,w)=>{if(typeof b!="function")throw new n(w,"Function",b)};e.exports={AggregateError:a,kEmptyObject:Object.freeze({}),once(b){let w=!1;return function(...m){w||(w=!0,b.apply(this,m))}},createDeferredPromise:function(){let b,w;return{promise:new Promise((m,k)=>{b=m,w=k}),resolve:b,reject:w}},promisify(b){return new Promise((w,m)=>{b((k,...S)=>k?m(k):w(...S))})},debuglog(){return function(){}},format:r,inspect:s,types:{isAsyncFunction(b){return b instanceof d},isArrayBufferView(b){return ArrayBuffer.isView(b)}},isBlob:g,deprecate(b,w){return b},addAbortListener:(Lt(),Ne(xt)).addAbortListener||function(b,w){if(b===void 0)throw new n("signal","AbortSignal",b);f(b,"signal"),y(w,"listener");let m;return b.aborted?queueMicrotask(()=>w()):(b.addEventListener("abort",w,{__proto__:null,once:!0,[o]:!0}),m=()=>{b.removeEventListener("abort",w)}),{__proto__:null,[l](){var k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(b){if(b.length===1)return b[0];let w=new u,m=()=>w.abort();return b.forEach(k=>{f(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{b.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),or=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:s,ArrayPrototypeMap:n,NumberIsInteger:o,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:f,StringPrototypeTrim:y}=Be(),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:v}}=Ke(),{normalizeEncoding:x}=Qe(),{isAsyncFunction:E,isArrayBufferView:I}=Qe().types,P={};function O(H){return H===(H|0)}function B(H){return H===H>>>0}var T=/^[0-7]+$/,$="must be a 32-bit unsigned integer or an octal string";function M(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(p(T,H)===null)throw new k(me,H,$);H=u(H,8)}return Y(H,me),H}var U=b((H,me,ve=c,ae=l)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);if(H<ve||H>ae)throw new S(me,`>= ${ve} && <= ${ae}`,H)}),oe=b((H,me,ve=-2147483648,ae=2147483647)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);if(H<ve||H>ae)throw new S(me,`>= ${ve} && <= ${ae}`,H)}),Y=b((H,me,ve=!1)=>{if(typeof H!="number")throw new m(me,"number",H);if(!o(H))throw new S(me,"an integer",H);let ae=ve?1:0,Oe=4294967295;if(H<ae||H>Oe)throw new S(me,`>= ${ae} && <= ${Oe}`,H)});function W(H,me){if(typeof H!="string")throw new m(me,"string",H)}function ee(H,me,ve=void 0,ae){if(typeof H!="number")throw new m(me,"number",H);if(ve!=null&&H<ve||ae!=null&&H>ae||(ve!=null||ae!=null)&&a(H))throw new S(me,`${ve!=null?`>= ${ve}`:""}${ve!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,H)}var D=b((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+s(n(ve,Oe=>typeof Oe=="string"?`'${Oe}'`:g(Oe)),", ");throw new k(me,H,ae)}});function X(H,me){if(typeof H!="boolean")throw new m(me,"boolean",H)}function L(H,me,ve){return H==null||!d(H,me)?ve:H[me]}var J=b((H,me,ve=null)=>{let ae=L(ve,"allowArray",!1),Oe=L(ve,"allowFunction",!1);if(!L(ve,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Oe||typeof H!="function"))throw new m(me,"Object",H)}),ge=b((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),re=b((H,me,ve=0)=>{if(!t(H))throw new m(me,"Array",H);if(H.length<ve){let ae=`must be longer than ${ve}`;throw new k(me,H,ae)}});function we(H,me){re(H,me);for(let ve=0;ve<H.length;ve++)W(H[ve],`${me}[${ve}]`)}function G(H,me){re(H,me);for(let ve=0;ve<H.length;ve++)X(H[ve],`${me}[${ve}]`)}function j(H,me){re(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);ye(ae,Oe)}}function ne(H,me="signal"){if(W(H,me),P[H]===void 0)throw P[f(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var z=b((H,me="buffer")=>{if(!I(H))throw new m(me,["Buffer","TypedArray","DataView"],H)});function K(H,me){let ve=x(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new k("encoding",me,`is invalid for data of length ${ae}`)}function Q(H,me="Port",ve=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&y(H).length===0||+H!==+H>>>0||H>65535||H===0&&!ve)throw new w(me,H,ve);return H|0}var ye=b((H,me)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(me,"AbortSignal",H)}),se=b((H,me)=>{if(typeof H!="function")throw new m(me,"Function",H)}),R=b((H,me)=>{if(typeof H!="function"||E(H))throw new m(me,"Function",H)}),q=b((H,me)=>{if(H!==void 0)throw new m(me,"undefined",H)});function te(H,me,ve){if(!r(ve,H))throw new m(me,`('${s(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,me){if(typeof H>"u"||!p(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function be(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let ae=0;ae<me;ae++){let Oe=H[ae];fe(Oe,"hints"),ve+=Oe,ae!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:B,parseFileMode:M,validateArray:re,validateStringArray:we,validateBooleanArray:G,validateAbortSignalArray:j,validateBoolean:X,validateBuffer:z,validateDictionary:ge,validateEncoding:K,validateFunction:se,validateInt32:oe,validateInteger:U,validateNumber:ee,validateObject:J,validateOneOf:D,validatePlainFunction:R,validatePort:Q,validateSignalName:ne,validateString:W,validateUint32:Y,validateUndefined:q,validateUnion:te,validateAbortSignal:ye,validateLinkHeaderValue:be}}),Rt=pe((i,e)=>{le(),ue(),ce();var t=e.exports={},r,s;function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?s=clearTimeout:s=o}catch{s=o}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(s===clearTimeout)return clearTimeout(w);if((s===o||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(w);try{return s(w)}catch{try{return s.call(null,w)}catch{return s.call(this,w)}}}var c=[],u=!1,d,p=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&f())}function f(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++p<m;)d&&d[p].run();p=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new y(w,m)),c.length===1&&!u&&a(f)};function y(w,m){this.fun=w,this.array=m}y.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={};function b(){}t.on=b,t.addListener=b,t.once=b,t.off=b,t.removeListener=b,t.removeAllListeners=b,t.emit=b,t.prependListener=b,t.prependOnceListener=b,t.listeners=function(w){return[]},t.binding=function(w){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(w){throw new Error("process.chdir is not supported")},t.umask=function(){return 0}}),pt=pe((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:s}=Be(),n=s("nodejs.stream.destroyed"),o=s("nodejs.stream.errored"),a=s("nodejs.stream.readable"),l=s("nodejs.stream.writable"),c=s("nodejs.stream.disturbed"),u=s("nodejs.webstream.isClosedPromise"),d=s("nodejs.webstream.controllerErrorFunction");function p(L,J=!1){var ge;return!!(L&&typeof L.pipe=="function"&&typeof L.on=="function"&&(!J||typeof L.pause=="function"&&typeof L.resume=="function")&&(!L._writableState||((ge=L._readableState)===null||ge===void 0?void 0:ge.readable)!==!1)&&(!L._writableState||L._readableState))}function g(L){var J;return!!(L&&typeof L.write=="function"&&typeof L.on=="function"&&(!L._readableState||((J=L._writableState)===null||J===void 0?void 0:J.writable)!==!1))}function f(L){return!!(L&&typeof L.pipe=="function"&&L._readableState&&typeof L.on=="function"&&typeof L.write=="function")}function y(L){return L&&(L._readableState||L._writableState||typeof L.write=="function"&&typeof L.on=="function"||typeof L.pipe=="function"&&typeof L.on=="function")}function b(L){return!!(L&&!y(L)&&typeof L.pipeThrough=="function"&&typeof L.getReader=="function"&&typeof L.cancel=="function")}function w(L){return!!(L&&!y(L)&&typeof L.getWriter=="function"&&typeof L.abort=="function")}function m(L){return!!(L&&!y(L)&&typeof L.readable=="object"&&typeof L.writable=="object")}function k(L){return b(L)||w(L)||m(L)}function S(L,J){return L==null?!1:J===!0?typeof L[t]=="function":J===!1?typeof L[r]=="function":typeof L[t]=="function"||typeof L[r]=="function"}function v(L){if(!y(L))return null;let J=L._writableState,ge=L._readableState,re=J||ge;return!!(L.destroyed||L[n]||re!=null&&re.destroyed)}function x(L){if(!g(L))return null;if(L.writableEnded===!0)return!0;let J=L._writableState;return J!=null&&J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function E(L,J){if(!g(L))return null;if(L.writableFinished===!0)return!0;let ge=L._writableState;return ge!=null&&ge.errored?!1:typeof ge?.finished!="boolean"?null:!!(ge.finished||J===!1&&ge.ended===!0&&ge.length===0)}function I(L){if(!p(L))return null;if(L.readableEnded===!0)return!0;let J=L._readableState;return!J||J.errored?!1:typeof J?.ended!="boolean"?null:J.ended}function P(L,J){if(!p(L))return null;let ge=L._readableState;return ge!=null&&ge.errored?!1:typeof ge?.endEmitted!="boolean"?null:!!(ge.endEmitted||J===!1&&ge.ended===!0&&ge.length===0)}function O(L){return L&&L[a]!=null?L[a]:typeof L?.readable!="boolean"?null:v(L)?!1:p(L)&&L.readable&&!P(L)}function B(L){return L&&L[l]!=null?L[l]:typeof L?.writable!="boolean"?null:v(L)?!1:g(L)&&L.writable&&!x(L)}function T(L,J){return y(L)?v(L)?!0:!(J?.readable!==!1&&O(L)||J?.writable!==!1&&B(L)):null}function $(L){var J,ge;return y(L)?L.writableErrored?L.writableErrored:(J=(ge=L._writableState)===null||ge===void 0?void 0:ge.errored)!==null&&J!==void 0?J:null:null}function M(L){var J,ge;return y(L)?L.readableErrored?L.readableErrored:(J=(ge=L._readableState)===null||ge===void 0?void 0:ge.errored)!==null&&J!==void 0?J:null:null}function U(L){if(!y(L))return null;if(typeof L.closed=="boolean")return L.closed;let J=L._writableState,ge=L._readableState;return typeof J?.closed=="boolean"||typeof ge?.closed=="boolean"?J?.closed||ge?.closed:typeof L._closed=="boolean"&&oe(L)?L._closed:null}function oe(L){return typeof L._closed=="boolean"&&typeof L._defaultKeepAlive=="boolean"&&typeof L._removedConnection=="boolean"&&typeof L._removedContLen=="boolean"}function Y(L){return typeof L._sent100=="boolean"&&oe(L)}function W(L){var J;return typeof L._consuming=="boolean"&&typeof L._dumped=="boolean"&&((J=L.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function ee(L){if(!y(L))return null;let J=L._writableState,ge=L._readableState,re=J||ge;return!re&&Y(L)||!!(re&&re.autoDestroy&&re.emitClose&&re.closed===!1)}function D(L){var J;return!!(L&&((J=L[c])!==null&&J!==void 0?J:L.readableDidRead||L.readableAborted))}function X(L){var J,ge,re,we,G,j,ne,z,K,Q;return!!(L&&((J=(ge=(re=(we=(G=(j=L[o])!==null&&j!==void 0?j:L.readableErrored)!==null&&G!==void 0?G:L.writableErrored)!==null&&we!==void 0?we:(ne=L._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&re!==void 0?re:(z=L._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&ge!==void 0?ge:(K=L._readableState)===null||K===void 0?void 0:K.errored)!==null&&J!==void 0?J:!((Q=L._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:D,kIsDisturbed:c,isErrored:X,kIsErrored:o,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:f,isFinished:T,isIterable:S,isReadableNodeStream:p,isReadableStream:b,isReadableEnded:I,isReadableFinished:P,isReadableErrored:M,isNodeStream:y,isWebStream:k,isWritable:B,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:x,isWritableFinished:E,isWritableErrored:$,isServerRequest:W,isServerResponse:Y,willEmitClose:ee,isTransformStream:m}}),Et=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{AbortError:r,codes:s}=Ke(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:o}=s,{kEmptyObject:a,once:l}=Qe(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=or(),{Promise:g,PromisePrototypeThen:f,SymbolDispose:y}=Be(),{isClosed:b,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:S,isReadableErrored:v,isWritable:x,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:B,willEmitClose:T,kIsClosedPromise:$}=pt(),M;function U(D){return D.setHeader&&typeof D.abort=="function"}var oe=()=>{};function Y(D,X,L){var J,ge;if(arguments.length===2?(L=X,X=a):X==null?X=a:d(X,"options"),u(L,"callback"),c(X.signal,"options.signal"),L=l(L),k(D)||I(D))return W(D,X,L);if(!B(D))throw new n("stream",["ReadableStream","WritableStream","Stream"],D);let re=(J=X.readable)!==null&&J!==void 0?J:m(D),we=(ge=X.writable)!==null&&ge!==void 0?ge:E(D),G=D._writableState,j=D._readableState,ne=()=>{D.writable||Q()},z=T(D)&&m(D)===re&&E(D)===we,K=P(D,!1),Q=()=>{K=!0,D.destroyed&&(z=!1),!(z&&(!D.readable||re))&&(!re||ye)&&L.call(D)},ye=S(D,!1),se=()=>{ye=!0,D.destroyed&&(z=!1),!(z&&(!D.writable||we))&&(!we||K)&&L.call(D)},R=H=>{L.call(D,H)},q=b(D),te=()=>{q=!0;let H=O(D)||v(D);if(H&&typeof H!="boolean")return L.call(D,H);if(re&&!ye&&m(D,!0)&&!S(D,!1))return L.call(D,new o);if(we&&!K&&!P(D,!1))return L.call(D,new o);L.call(D)},he=()=>{q=!0;let H=O(D)||v(D);if(H&&typeof H!="boolean")return L.call(D,H);L.call(D)},fe=()=>{D.req.on("finish",Q)};U(D)?(D.on("complete",Q),z||D.on("abort",te),D.req?fe():D.on("request",fe)):we&&!G&&(D.on("end",ne),D.on("close",ne)),!z&&typeof D.aborted=="boolean"&&D.on("aborted",te),D.on("end",se),D.on("finish",Q),X.error!==!1&&D.on("error",R),D.on("close",te),q?t.nextTick(te):G!=null&&G.errorEmitted||j!=null&&j.errorEmitted?z||t.nextTick(he):(!re&&(!z||w(D))&&(K||x(D)===!1)||!we&&(!z||x(D))&&(ye||w(D)===!1)||j&&D.req&&D.aborted)&&t.nextTick(he);let be=()=>{L=oe,D.removeListener("aborted",te),D.removeListener("complete",Q),D.removeListener("abort",te),D.removeListener("request",fe),D.req&&D.req.removeListener("finish",Q),D.removeListener("end",ne),D.removeListener("close",ne),D.removeListener("finish",Q),D.removeListener("end",se),D.removeListener("error",R),D.removeListener("close",te)};if(X.signal&&!q){let H=()=>{let me=L;be(),me.call(D,new r(void 0,{cause:X.signal.reason}))};if(X.signal.aborted)t.nextTick(H);else{M=M||Qe().addAbortListener;let me=M(X.signal,H),ve=L;L=l((...ae)=>{me[y](),ve.apply(D,ae)})}}return be}function W(D,X,L){let J=!1,ge=oe;if(X.signal)if(ge=()=>{J=!0,L.call(D,new r(void 0,{cause:X.signal.reason}))},X.signal.aborted)t.nextTick(ge);else{M=M||Qe().addAbortListener;let we=M(X.signal,ge),G=L;L=l((...j)=>{we[y](),G.apply(D,j)})}let re=(...we)=>{J||t.nextTick(()=>L.apply(D,we))};return f(D[$].promise,re,re),oe}function ee(D,X){var L;let J=!1;return X===null&&(X=a),(L=X)!==null&&L!==void 0&&L.cleanup&&(p(X.cleanup,"cleanup"),J=X.cleanup),new g((ge,re)=>{let we=Y(D,X,G=>{J&&we(),G?re(G):ge()})})}e.exports=Y,e.exports.finished=ee}),Wt=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:s},AbortError:n}=Ke(),{Symbol:o}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=pt(),d=o("kDestroy"),p=o("kConstruct");function g(T,$,M){T&&(T.stack,$&&!$.errored&&($.errored=T),M&&!M.errored&&(M.errored=T))}function f(T,$){let M=this._readableState,U=this._writableState,oe=U||M;return U!=null&&U.destroyed||M!=null&&M.destroyed?(typeof $=="function"&&$(),this):(g(T,U,M),U&&(U.destroyed=!0),M&&(M.destroyed=!0),oe.constructed?y(this,T,$):this.once(d,function(Y){y(this,r(Y,T),$)}),this)}function y(T,$,M){let U=!1;function oe(Y){if(U)return;U=!0;let W=T._readableState,ee=T._writableState;g(Y,ee,W),ee&&(ee.closed=!0),W&&(W.closed=!0),typeof M=="function"&&M(Y),Y?t.nextTick(b,T,Y):t.nextTick(w,T)}try{T._destroy($||null,oe)}catch(Y){oe(Y)}}function b(T,$){m(T,$),w(T)}function w(T){let $=T._readableState,M=T._writableState;M&&(M.closeEmitted=!0),$&&($.closeEmitted=!0),(M!=null&&M.emitClose||$!=null&&$.emitClose)&&T.emit("close")}function m(T,$){let M=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||M!=null&&M.errorEmitted||(U&&(U.errorEmitted=!0),M&&(M.errorEmitted=!0),T.emit("error",$))}function k(){let T=this._readableState,$=this._writableState;T&&(T.constructed=!0,T.closed=!1,T.closeEmitted=!1,T.destroyed=!1,T.errored=null,T.errorEmitted=!1,T.reading=!1,T.ended=T.readable===!1,T.endEmitted=T.readable===!1),$&&($.constructed=!0,$.destroyed=!1,$.closed=!1,$.closeEmitted=!1,$.errored=null,$.errorEmitted=!1,$.finalCalled=!1,$.prefinished=!1,$.ended=$.writable===!1,$.ending=$.writable===!1,$.finished=$.writable===!1)}function S(T,$,M){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=$),M?t.nextTick(m,T,$):m(T,$))}function v(T,$){if(typeof T._construct!="function")return;let M=T._readableState,U=T._writableState;M&&(M.constructed=!1),U&&(U.constructed=!1),T.once(p,$),!(T.listenerCount(p)>1)&&t.nextTick(x,T)}function x(T){let $=!1;function M(U){if($){S(T,U??new s);return}$=!0;let oe=T._readableState,Y=T._writableState,W=Y||oe;oe&&(oe.constructed=!0),Y&&(Y.constructed=!0),W.destroyed?T.emit(d,U):U?S(T,U,!0):t.nextTick(E,T)}try{T._construct(U=>{t.nextTick(M,U)})}catch(U){t.nextTick(M,U)}}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,$){T.emit("error",$),t.nextTick(P,T)}function B(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(O,T,$):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:B,destroy:f,undestroy:k,errorOrDestroy:S}}),ki=pe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:s}=(Lt(),Ne(xt));function n(a){s.call(this,a)}r(n.prototype,s.prototype),r(n,s),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",f));let p=!1;function g(){p||(p=!0,a.end())}function f(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function y(w){b(),s.listenerCount(this,"error")===0&&this.emit("error",w)}o(c,"error",y),o(a,"error",y);function b(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",f),c.removeListener("error",y),a.removeListener("error",y),c.removeListener("end",b),c.removeListener("close",b),a.removeListener("close",b)}return c.on("end",b),c.on("close",b),a.on("close",b),a.emit("pipe",c),a};function o(a,l,c){if(typeof a.prependListener=="function")return a.prependListener(l,c);!a._events||!a._events[l]?a.on(l,c):t(a._events[l])?a._events[l].unshift(c):a._events[l]=[c,a._events[l]]}e.exports={Stream:n,prependListener:o}}),_r=pe((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:s}=Ke(),{isNodeStream:n,isWebStream:o,kControllerErrorFunction:a}=pt(),l=Et(),{ERR_INVALID_ARG_TYPE:c}=s,u,d=(p,g)=>{if(typeof p!="object"||!("aborted"in p))throw new c(g,"AbortSignal",p)};e.exports.addAbortSignal=function(p,g){if(d(p,"signal"),!n(g)&&!o(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(p,g)},e.exports.addAbortSignalNoValidate=function(p,g){if(typeof p!="object"||!("aborted"in p))return g;let f=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[a](new r(void 0,{cause:p.reason}))};if(p.aborted)f();else{u=u||Qe().addAbortListener;let y=u(p,f);l(g,y[t])}return g}}),Qc=pe((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:s,Uint8Array:n}=Be(),{Buffer:o}=(qe(),Ne($e)),{inspect:a}=Qe();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return o.alloc(0);let c=o.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)s(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=o.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)s(c,g,u-l),l-=g.length;else{l===g.length?(s(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(s(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Sr=pe((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:s}=or(),{ERR_INVALID_ARG_VALUE:n}=Ke().codes,o=16*1024,a=16;function l(p,g,f){return p.highWaterMark!=null?p.highWaterMark:g?p[f]:null}function c(p){return p?a:o}function u(p,g){s(g,"value",0),p?a=g:o=g}function d(p,g,f,y){let b=l(g,y,f);if(b!=null){if(!r(b)||b<0){let w=y?`options.${f}`:"options.highWaterMark";throw new n(w,b)}return t(b)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),Xc=pe((i,e)=>{le(),ue(),ce();var t=(qe(),Ne($e)),r=t.Buffer;function s(o,a){for(var l in o)a[l]=o[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(s(t,i),i.Buffer=n);function n(o,a,l){return r(o,a,l)}n.prototype=Object.create(r.prototype),s(r,n),n.from=function(o,a,l){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,a,l)},n.alloc=function(o,a,l){if(typeof o!="number")throw new TypeError("Argument must be a number");var c=r(o);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},n.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(o)}}),Zc=pe(i=>{le(),ue(),ce();var e=Xc().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function s(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=s(m);var k;switch(this.encoding){case"utf16le":this.text=p,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=f,this.end=y,k=3;break;default:this.write=b,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,S;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";S=this.lastNeed,this.lastNeed=0}else S=0;return S<m.length?k?k+this.text(m,S):this.text(m,S):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function o(m){return m<=127?0:m>>5===6?2:m>>4===14?3:m>>3===30?4:m>>6===2?-1:-2}function a(m,k,S){var v=k.length-1;if(v<S)return 0;var x=o(k[v]);return x>=0?(x>0&&(m.lastNeed=x-1),x):--v<S||x===-2?0:(x=o(k[v]),x>=0?(x>0&&(m.lastNeed=x-2),x):--v<S||x===-2?0:(x=o(k[v]),x>=0?(x>0&&(x===2?x=0:m.lastNeed=x-3),x):0))}function l(m,k,S){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,S=l(this,m);if(S!==void 0)return S;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var S=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=S;var v=m.length-(S-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function p(m,k){if((m.length-k)%2===0){var S=m.toString("utf16le",k);if(S){var v=S.charCodeAt(S.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],S.slice(0,-1)}return S}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var S=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,S)}return k}function f(m,k){var S=(m.length-k)%3;return S===0?m.toString("base64",k):(this.lastNeed=3-S,this.lastTotal=3,S===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-S))}function y(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function b(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),gs=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{PromisePrototypeThen:r,SymbolAsyncIterator:s,SymbolIterator:n}=Be(),{Buffer:o}=(qe(),Ne($e)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ke().codes;function c(u,d,p){let g;if(typeof d=="string"||d instanceof o)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let f;if(d&&d[s])f=!0,g=d[s]();else if(d&&d[n])f=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let y=new u({objectMode:!0,highWaterMark:1,...p}),b=!1;y._read=function(){b||(b=!0,m())},y._destroy=function(k,S){r(w(k),()=>t.nextTick(S,k),v=>t.nextTick(S,v||k))};async function w(k){let S=k!=null,v=typeof g.throw=="function";if(S&&v){let{value:x,done:E}=await g.throw(k);if(await x,E)return}if(typeof g.return=="function"){let{value:x}=await g.return();await x}}async function m(){for(;;){try{let{value:k,done:S}=f?await g.next():g.next();if(S)y.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw b=!1,new l;if(y.push(v))continue;b=!1}}catch(k){y.destroy(k)}break}}return y}e.exports=c}),xr=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:s,NumberIsNaN:n,NumberParseInt:o,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:f}=Be();e.exports=ae,ae.ReadableState=ve;var{EventEmitter:y}=(Lt(),Ne(xt)),{Stream:b,prependListener:w}=ki(),{Buffer:m}=(qe(),Ne($e)),{addAbortSignal:k}=_r(),S=Et(),v=Qe().debuglog("stream",C=>{v=C}),x=Qc(),E=Wt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=Sr(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:B,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:$,ERR_STREAM_PUSH_AFTER_EOF:M,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:oe}=Ke(),{validateObject:Y}=or(),W=f("kPaused"),{StringDecoder:ee}=Zc(),D=gs();c(ae.prototype,b.prototype),c(ae,b);var X=()=>{},{errorOrDestroy:L}=E,J=1,ge=2,re=4,we=8,G=16,j=32,ne=64,z=128,K=256,Q=512,ye=1024,se=2048,R=4096,q=8192,te=16384,he=32768,fe=65536,be=1<<17,H=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(ge),endEmitted:me(re),reading:me(we),constructed:me(G),sync:me(j),needReadable:me(ne),emittedReadable:me(z),readableListening:me(K),resumeScheduled:me(Q),errorEmitted:me(ye),emitClose:me(se),autoDestroy:me(R),destroyed:me(q),closed:me(te),closeEmitted:me(he),multiAwaitDrain:me(fe),readingMore:me(be),dataEmitted:me(H)});function ve(C,N,ke){typeof ke!="boolean"&&(ke=N instanceof mt()),this.state=se|R|G|j,C&&C.objectMode&&(this.state|=J),ke&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new x,this.length=0,this.pipes=[],this.flowing=null,this[W]=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 ee(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&&k(C.signal,this)),b.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(C,N){N(C)},ae.prototype[y.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,ke)=>S(this,xe=>xe&&xe!==C?ke(xe):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,ke,xe){v("readableAddChunk",N);let Ae=C._readableState,Fe;if((Ae.state&J)===0&&(typeof N=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(xe&&Ae.encoding?N=m.from(N,ke).toString(Ae.encoding):(N=m.from(N,ke),ke=""))):N instanceof m?ke="":b._isUint8Array(N)?(N=b._uint8ArrayToBuffer(N),ke=""):N!=null&&(Fe=new B("chunk",["string","Buffer","Uint8Array"],N))),Fe)L(C,Fe);else if(N===null)Ae.state&=~we,Z(C,Ae);else if((Ae.state&J)!==0||N&&N.length>0)if(xe)if((Ae.state&re)!==0)L(C,new U);else{if(Ae.destroyed||Ae.errored)return!1;h(C,Ae,N,!0)}else if(Ae.ended)L(C,new M);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~we,Ae.decoder&&!ke?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?h(C,Ae,N,!1):V(C,Ae)):h(C,Ae,N,!1)}else xe||(Ae.state&=~we,V(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function h(C,N,ke,xe){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",ke)):(N.length+=N.objectMode?1:ke.length,xe?N.buffer.unshift(ke):N.buffer.push(ke),(N.state&ne)!==0&&de(C)),V(C,N)}ae.prototype.isPaused=function(){let C=this._readableState;return C[W]===!0||C.flowing===!1},ae.prototype.setEncoding=function(C){let N=new ee(C);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,xe="";for(let Ae of ke)xe+=N.write(Ae);return ke.clear(),xe!==""&&ke.push(xe),this._readableState.length=xe.length,this};var _=1073741824;function A(C){if(C>_)throw new $("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function F(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:s(C)||(C=o(C,10));let N=this._readableState,ke=C;if(C>N.highWaterMark&&(N.highWaterMark=A(C)),C!==0&&(N.state&=~z),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?lt(this):de(this),null;if(C=F(C,N),C===0&&N.ended)return N.length===0&<(this),null;let xe=(N.state&ne)!==0;if(v("need readable",xe),(N.length===0||N.length-C<N.highWaterMark)&&(xe=!0,v("length less than watermark",xe)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)xe=!1,v("reading, ended or constructing",xe);else if(xe){v("do read"),N.state|=we|j,N.length===0&&(N.state|=ne);try{this._read(N.highWaterMark)}catch(Fe){L(this,Fe)}N.state&=~j,N.reading||(C=F(ke,N))}let Ae;return C>0?Ae=Xt(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),ke!==C&&N.ended&<(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 ke=N.decoder.end();ke&&ke.length&&(N.buffer.push(ke),N.length+=N.objectMode?1:ke.length)}N.ended=!0,N.sync?de(C):(N.needReadable=!1,N.emittedReadable=!0,_e(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(_e,C))}function _e(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,st(C)}function V(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 ke=N.length;if(v("maybeReadMore read 0"),C.read(0),ke===N.length)break}N.readingMore=!1}ae.prototype._read=function(C){throw new T("_read()")},ae.prototype.pipe=function(C,N){let ke=this,xe=this._readableState;xe.pipes.length===1&&(xe.multiAwaitDrain||(xe.multiAwaitDrain=!0,xe.awaitDrainWriters=new d(xe.awaitDrainWriters?[xe.awaitDrainWriters]:[]))),xe.pipes.push(C),v("pipe count=%d opts=%j",xe.pipes.length,N);let Ae=(!N||N.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ye:Ft;xe.endEmitted?t.nextTick(Ae):ke.once("end",Ae),C.on("unpipe",Fe);function Fe(ut,_t){v("onunpipe"),ut===ke&&_t&&_t.hasUnpiped===!1&&(_t.hasUnpiped=!0,pr())}function Ye(){v("onend"),C.end()}let rt,fr=!1;function pr(){v("cleanup"),C.removeListener("close",ct),C.removeListener("finish",Pt),rt&&C.removeListener("drain",rt),C.removeListener("error",Bt),C.removeListener("unpipe",Fe),ke.removeListener("end",Ye),ke.removeListener("end",Ft),ke.removeListener("data",sn),fr=!0,rt&&xe.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&rt()}function mr(){fr||(xe.pipes.length===1&&xe.pipes[0]===C?(v("false write response, pause",0),xe.awaitDrainWriters=C,xe.multiAwaitDrain=!1):xe.pipes.length>1&&xe.pipes.includes(C)&&(v("false write response, pause",xe.awaitDrainWriters.size),xe.awaitDrainWriters.add(C)),ke.pause()),rt||(rt=Ie(ke,C),C.on("drain",rt))}ke.on("data",sn);function sn(ut){v("ondata");let _t=C.write(ut);v("dest.write",_t),_t===!1&&mr()}function Bt(ut){if(v("onerror",ut),Ft(),C.removeListener("error",Bt),C.listenerCount("error")===0){let _t=C._writableState||C._readableState;_t&&!_t.errorEmitted?L(C,ut):C.emit("error",ut)}}w(C,"error",Bt);function ct(){C.removeListener("finish",Pt),Ft()}C.once("close",ct);function Pt(){v("onfinish"),C.removeListener("close",ct),Ft()}C.once("finish",Pt);function Ft(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?mr():xe.flowing||(v("pipe resume"),ke.resume()),C};function Ie(C,N){return function(){let ke=C._readableState;ke.awaitDrainWriters===N?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(N)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}ae.prototype.unpipe=function(C){let N=this._readableState,ke={hasUnpiped:!1};if(N.pipes.length===0)return this;if(!C){let Ae=N.pipes;N.pipes=[],this.pause();for(let Fe=0;Fe<Ae.length;Fe++)Ae[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let xe=r(N.pipes,C);return xe===-1?this:(N.pipes.splice(xe,1),N.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},ae.prototype.on=function(C,N){let ke=b.prototype.on.call(this,C,N),xe=this._readableState;return C==="data"?(xe.readableListening=this.listenerCount("readable")>0,xe.flowing!==!1&&this.resume()):C==="readable"&&!xe.endEmitted&&!xe.readableListening&&(xe.readableListening=xe.needReadable=!0,xe.flowing=!1,xe.emittedReadable=!1,v("on readable",xe.length,xe.reading),xe.length?de(this):xe.reading||t.nextTick(Pe,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,N){let ke=b.prototype.removeListener.call(this,C,N);return C==="readable"&&t.nextTick(Te,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(C){let N=b.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[W]===!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,Le(this,C)),C[W]=!1,this};function Le(C,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(ot,C,N))}function ot(C,N){v("resume",N.reading),N.reading||C.read(0),N.resumeScheduled=!1,C.emit("resume"),st(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[W]=!0,this};function st(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",xe=>{!this.push(xe)&&C.pause&&(N=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",xe=>{L(this,xe)}),C.on("close",()=>{this.destroy()}),C.on("destroy",()=>{this.destroy()}),this._read=()=>{N&&C.resume&&(N=!1,C.resume())};let ke=l(C);for(let xe=1;xe<ke.length;xe++){let Ae=ke[xe];this[Ae]===void 0&&typeof C[Ae]=="function"&&(this[Ae]=C[Ae].bind(C))}return this},ae.prototype[g]=function(){return Ge(this)},ae.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ge(this,C)};function Ge(C,N){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let ke=at(C,N);return ke.stream=C,ke}async function*at(C,N){let ke=X;function xe(Ye){this===C?(ke(),ke=X):ke=Ye}C.on("readable",xe);let Ae,Fe=S(C,{writable:!1},Ye=>{Ae=Ye?O(Ae,Ye):null,ke(),ke=X});try{for(;;){let Ye=C.destroyed?null:C.read();if(Ye!==null)yield Ye;else{if(Ae)throw Ae;if(Ae===null)return;await new u(xe)}}}catch(Ye){throw Ae=O(Ae,Ye),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",xe),Fe())}}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[W]!==!1},set(C){this[W]=!!C}}}),ae._fromList=Xt;function Xt(C,N){if(N.length===0)return null;let ke;return N.objectMode?ke=N.buffer.shift():!C||C>=N.length?(N.decoder?ke=N.buffer.join(""):N.buffer.length===1?ke=N.buffer.first():ke=N.buffer.concat(N.length),N.buffer.clear()):ke=N.buffer.consume(C,N.decoder),ke}function lt(C){let N=C._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(Ze,N,C))}function Ze(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(on,N);else if(C.autoDestroy){let ke=N._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&N.destroy()}}}function on(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,N){return D(ae,C,N)};var Zt;function hr(){return Zt===void 0&&(Zt={}),Zt}ae.fromWeb=function(C,N){return hr().newStreamReadableFromReadableStream(C,N)},ae.toWeb=function(C,N){return hr().newReadableStreamFromStreamReadable(C,N)},ae.wrap=function(C,N){var ke,xe;return new ae({objectMode:(ke=(xe=C.readableObjectMode)!==null&&xe!==void 0?xe:C.objectMode)!==null&&ke!==void 0?ke:!0,...N,destroy(Ae,Fe){E.destroyer(C,Ae),Fe(Ae)}}).wrap(C)}}),_i=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayPrototypeSlice:r,Error:s,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:o,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=U;var{EventEmitter:p}=(Lt(),Ne(xt)),g=ki().Stream,{Buffer:f}=(qe(),Ne($e)),y=Wt(),{addAbortSignal:b}=_r(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Sr(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:x,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:B}=Ke().codes,{errorOrDestroy:T}=y;l(Y.prototype,g.prototype),l(Y,g);function $(){}var M=u("kOnFinished");function U(R,q,te){typeof te!="boolean"&&(te=q instanceof mt()),this.objectMode=!!(R&&R.objectMode),te&&(this.objectMode=this.objectMode||!!(R&&R.writableObjectMode)),this.highWaterMark=R?w(this,R,"writableHighWaterMark",te):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=L.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[M]=[]}function oe(R){R.buffered=[],R.bufferedIndex=0,R.allBuffers=!0,R.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},o(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Y(R){let q=this instanceof mt();if(!q&&!n(Y,this))return new Y(R);this._writableState=new U(R,this,q),R&&(typeof R.write=="function"&&(this._write=R.write),typeof R.writev=="function"&&(this._writev=R.writev),typeof R.destroy=="function"&&(this._destroy=R.destroy),typeof R.final=="function"&&(this._final=R.final),typeof R.construct=="function"&&(this._construct=R.construct),R.signal&&b(R.signal,this)),g.call(this,R),y.construct(this,()=>{let te=this._writableState;te.writing||we(this,te),z(this,te)})}o(Y,d,{__proto__:null,value:function(R){return n(this,R)?!0:this!==Y?!1:R&&R._writableState instanceof U}}),Y.prototype.pipe=function(){T(this,new x)};function W(R,q,te,he){let fe=R._writableState;if(typeof te=="function")he=te,te=fe.defaultEncoding;else{if(!te)te=fe.defaultEncoding;else if(te!=="buffer"&&!f.isEncoding(te))throw new B(te);typeof he!="function"&&(he=$)}if(q===null)throw new P;if(!fe.objectMode)if(typeof q=="string")fe.decodeStrings!==!1&&(q=f.from(q,te),te="buffer");else if(q instanceof f)te="buffer";else if(g._isUint8Array(q))q=g._uint8ArrayToBuffer(q),te="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],q);let be;return fe.ending?be=new O:fe.destroyed&&(be=new E("write")),be?(t.nextTick(he,be),T(R,be,!0),be):(fe.pendingcb++,ee(R,fe,q,te,he))}Y.prototype.write=function(R,q,te){return W(this,R,q,te)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let R=this._writableState;R.corked&&(R.corked--,R.writing||we(this,R))},Y.prototype.setDefaultEncoding=function(R){if(typeof R=="string"&&(R=c(R)),!f.isEncoding(R))throw new B(R);return this._writableState.defaultEncoding=R,this};function ee(R,q,te,he,fe){let be=q.objectMode?1:te.length;q.length+=be;let H=q.length<q.highWaterMark;return H||(q.needDrain=!0),q.writing||q.corked||q.errored||!q.constructed?(q.buffered.push({chunk:te,encoding:he,callback:fe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&fe!==$&&(q.allNoop=!1)):(q.writelen=be,q.writecb=fe,q.writing=!0,q.sync=!0,R._write(te,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function D(R,q,te,he,fe,be,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new E("write")):te?R._writev(fe,q.onwrite):R._write(fe,be,q.onwrite),q.sync=!1}function X(R,q,te,he){--q.pendingcb,he(te),re(q),T(R,te)}function L(R,q){let te=R._writableState,he=te.sync,fe=te.writecb;if(typeof fe!="function"){T(R,new v);return}te.writing=!1,te.writecb=null,te.length-=te.writelen,te.writelen=0,q?(q.stack,te.errored||(te.errored=q),R._readableState&&!R._readableState.errored&&(R._readableState.errored=q),he?t.nextTick(X,R,te,q,fe):X(R,te,q,fe)):(te.buffered.length>te.bufferedIndex&&we(R,te),he?te.afterWriteTickInfo!==null&&te.afterWriteTickInfo.cb===fe?te.afterWriteTickInfo.count++:(te.afterWriteTickInfo={count:1,cb:fe,stream:R,state:te},t.nextTick(J,te.afterWriteTickInfo)):ge(R,te,1,fe))}function J({stream:R,state:q,count:te,cb:he}){return q.afterWriteTickInfo=null,ge(R,q,te,he)}function ge(R,q,te,he){for(!q.ending&&!R.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,R.emit("drain"));te-- >0;)q.pendingcb--,he();q.destroyed&&re(q),z(R,q)}function re(R){if(R.writing)return;for(let fe=R.bufferedIndex;fe<R.buffered.length;++fe){var q;let{chunk:be,callback:H}=R.buffered[fe],me=R.objectMode?1:be.length;R.length-=me,H((q=R.errored)!==null&&q!==void 0?q:new E("write"))}let te=R[M].splice(0);for(let fe=0;fe<te.length;fe++){var he;te[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:te,bufferedIndex:he,objectMode:fe}=q,be=te.length-he;if(!be)return;let H=he;if(q.bufferProcessing=!0,be>1&&R._writev){q.pendingcb-=be-1;let me=q.allNoop?$:ae=>{for(let Oe=H;Oe<te.length;++Oe)te[Oe].callback(ae)},ve=q.allNoop&&H===0?te:r(te,H);ve.allBuffers=q.allBuffers,D(R,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=te[H];te[H++]=null;let Oe=fe?1:me.length;D(R,q,!1,Oe,me,ve,ae)}while(H<te.length&&!q.writing);H===te.length?oe(q):H>256?(te.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}Y.prototype._write=function(R,q,te){if(this._writev)this._writev([{chunk:R,encoding:q}],te);else throw new S("_write()")},Y.prototype._writev=null,Y.prototype.end=function(R,q,te){let he=this._writableState;typeof R=="function"?(te=R,R=null,q=null):typeof q=="function"&&(te=q,q=null);let fe;if(R!=null){let be=W(this,R,q);be instanceof s&&(fe=be)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,z(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new E("end"))),typeof te=="function"&&(fe||he.finished?t.nextTick(te,fe):he[M].push(te)),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 te=!1;function he(fe){if(te){T(R,fe??v());return}if(te=!0,q.pendingcb--,fe){let be=q[M].splice(0);for(let H=0;H<be.length;H++)be[H](fe);T(R,fe,q.sync)}else G(q)&&(q.prefinished=!0,R.emit("prefinish"),q.pendingcb++,t.nextTick(K,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 z(R,q,te){G(q)&&(ne(R,q),q.pendingcb===0&&(te?(q.pendingcb++,t.nextTick((he,fe)=>{G(fe)?K(he,fe):fe.pendingcb--},R,q)):G(q)&&(q.pendingcb++,K(R,q))))}function K(R,q){q.pendingcb--,q.finished=!0;let te=q[M].splice(0);for(let he=0;he<te.length;he++)te[he]();if(R.emit("finish"),q.autoDestroy){let he=R._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&R.destroy()}}a(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(R){this._writableState&&(this._writableState.destroyed=R)}},writable:{__proto__:null,get(){let R=this._writableState;return!!R&&R.writable!==!1&&!R.destroyed&&!R.errored&&!R.ending&&!R.ended},set(R){this._writableState&&(this._writableState.writable=!!R)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let R=this._writableState;return R?!R.destroyed&&!R.ending&&R.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var Q=y.destroy;Y.prototype.destroy=function(R,q){let te=this._writableState;return!te.destroyed&&(te.bufferedIndex<te.buffered.length||te[M].length)&&t.nextTick(re,te),Q.call(this,R,q),this},Y.prototype._undestroy=y.undestroy,Y.prototype._destroy=function(R,q){q(R)},Y.prototype[p.captureRejectionSymbol]=function(R){this.destroy(R)};var ye;function se(){return ye===void 0&&(ye={}),ye}Y.fromWeb=function(R,q){return se().newStreamWritableFromWritableStream(R,q)},Y.toWeb=function(R){return se().newWritableStreamFromStreamWritable(R)}}),eu=pe((i,e)=>{le(),ue(),ce();var t=Rt(),r=(qe(),Ne($e)),{isReadable:s,isWritable:n,isIterable:o,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=pt(),g=Et(),{AbortError:f,codes:{ERR_INVALID_ARG_TYPE:y,ERR_INVALID_RETURN_VALUE:b}}=Ke(),{destroyer:w}=Wt(),m=mt(),k=xr(),S=_i(),{createDeferredPromise:v}=Qe(),x=gs(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(M){return M instanceof E}:function(M){return!1},P=globalThis.AbortController||nr().AbortController,{FunctionPrototypeCall:O}=Be(),B=class extends m{constructor(M){super(M),M?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),M?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function M(U,oe){if(u(U))return U;if(l(U))return $({readable:U});if(c(U))return $({writable:U});if(a(U))return $({writable:!1,readable:!1});if(d(U))return $({readable:k.fromWeb(U)});if(p(U))return $({writable:S.fromWeb(U)});if(typeof U=="function"){let{value:W,write:ee,final:D,destroy:X}=T(U);if(o(W))return x(B,W,{objectMode:!0,write:ee,final:D,destroy:X});let L=W?.then;if(typeof L=="function"){let J,ge=O(L,W,re=>{if(re!=null)throw new b("nully","body",re)},re=>{w(J,re)});return J=new B({objectMode:!0,readable:!1,write:ee,final(re){D(async()=>{try{await ge,t.nextTick(re,null)}catch(we){t.nextTick(re,we)}})},destroy:X})}throw new b("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(U))return M(U.arrayBuffer());if(o(U))return x(B,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&p(U?.writable))return B.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let W=U!=null&&U.readable?l(U?.readable)?U?.readable:M(U.readable):void 0,ee=U!=null&&U.writable?c(U?.writable)?U?.writable:M(U.writable):void 0;return $({readable:W,writable:ee})}let Y=U?.then;if(typeof Y=="function"){let W;return O(Y,U,ee=>{ee!=null&&W.push(ee),W.push(null)},ee=>{w(W,ee)}),W=new B({objectMode:!0,writable:!1,read(){}})}throw new y(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T(M){let{promise:U,resolve:oe}=v(),Y=new P,W=Y.signal;return{value:M((async function*(){for(;;){let ee=U;U=null;let{chunk:D,done:X,cb:L}=await ee;if(t.nextTick(L),X)return;if(W.aborted)throw new f(void 0,{cause:W.reason});({promise:U,resolve:oe}=v()),yield D}})(),{signal:W}),write(ee,D,X){let L=oe;oe=null,L({chunk:ee,done:!1,cb:X})},final(ee){let D=oe;oe=null,D({done:!0,cb:ee})},destroy(ee,D){Y.abort(),D(ee)}}}function $(M){let U=M.readable&&typeof M.readable.read!="function"?k.wrap(M.readable):M.readable,oe=M.writable,Y=!!s(U),W=!!n(oe),ee,D,X,L,J;function ge(re){let we=L;L=null,we?we(re):re&&J.destroy(re)}return J=new B({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:Y,writable:W}),W&&(g(oe,re=>{W=!1,re&&w(U,re),ge(re)}),J._write=function(re,we,G){oe.write(re,we)?G():ee=G},J._final=function(re){oe.end(),D=re},oe.on("drain",function(){if(ee){let re=ee;ee=null,re()}}),oe.on("finish",function(){if(D){let re=D;D=null,re()}})),Y&&(g(U,re=>{Y=!1,re&&w(U,re),ge(re)}),U.on("readable",function(){if(X){let re=X;X=null,re()}}),U.on("end",function(){J.push(null)}),J._read=function(){for(;;){let re=U.read();if(re===null){X=J._read;return}if(!J.push(re))return}}),J._destroy=function(re,we){!re&&L!==null&&(re=new f),X=null,ee=null,D=null,L===null?we(re):(L=we,w(oe,re),w(U,re))},J}}),mt=pe((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:s,ObjectSetPrototypeOf:n}=Be();e.exports=l;var o=xr(),a=_i();n(l.prototype,o.prototype),n(l,o);{let p=s(a.prototype);for(let g=0;g<p.length;g++){let f=p[g];l.prototype[f]||(l.prototype[f]=a.prototype[f])}}function l(p){if(!(this instanceof l))return new l(p);o.call(this,p),a.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=eu()),d(p,"body")}}),ys=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:s}=Ke().codes,n=mt(),{getHighWaterMark:o}=Sr();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?o(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,g)=>{if(p){d?d(p):this.destroy(p);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,p,g){throw new s("_transform()")},l.prototype._write=function(d,p,g){let f=this._readableState,y=this._writableState,b=f.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),y.ended||b===f.length||f.length<f.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),bs=pe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=s;var r=ys();t(s.prototype,r.prototype),t(s,r);function s(n){if(!(this instanceof s))return new s(n);r.call(this,n)}s.prototype._transform=function(n,o,a){a(null,n)}}),Si=pe((i,e)=>{le(),ue(),ce();var t=Rt(),{ArrayIsArray:r,Promise:s,SymbolAsyncIterator:n,SymbolDispose:o}=Be(),a=Et(),{once:l}=Qe(),c=Wt(),u=mt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:f,ERR_STREAM_DESTROYED:y,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:w}=Ke(),{validateFunction:m,validateAbortSignal:k}=or(),{isIterable:S,isReadable:v,isReadableNodeStream:x,isNodeStream:E,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:B}=pt(),T=globalThis.AbortController||nr().AbortController,$,M,U;function oe(re,we,G){let j=!1;re.on("close",()=>{j=!0});let ne=a(re,{readable:we,writable:G},z=>{j=!z});return{destroy:z=>{j||(j=!0,c.destroyer(re,z||new y("pipe")))},cleanup:ne}}function Y(re){return m(re[re.length-1],"streams[stream.length - 1]"),re.pop()}function W(re){if(S(re))return re;if(x(re))return ee(re);throw new p("val",["Readable","Iterable","AsyncIterable"],re)}async function*ee(re){M||(M=xr()),yield*M.prototype[n].call(re)}async function D(re,we,G,{end:j}){let ne,z=null,K=se=>{if(se&&(ne=se),z){let R=z;z=null,R()}},Q=()=>new s((se,R)=>{ne?R(ne):z=()=>{ne?R(ne):se()}});we.on("drain",K);let ye=a(we,{readable:!1},K);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{ye(),we.off("drain",K)}}async function X(re,we,G,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let z of re)await ne.ready,ne.write(z).catch(()=>{});await ne.ready,j&&await ne.close(),G()}catch(z){try{await ne.abort(z),G(z)}catch(K){G(K)}}}function L(...re){return J(re,l(Y(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,z=G?.signal,K=[];k(z,"options.signal");function Q(){fe(new w)}U=U||Qe().addAbortListener;let ye;z&&(ye=U(z,Q));let se,R,q=[],te=0;function he(ve){fe(ve,--te===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=ye)===null||Oe===void 0||Oe[o](),j.abort(),ae&&(se||K.forEach(h=>h()),t.nextTick(we,se,R))}}let be;for(let ve=0;ve<re.length;ve++){let ae=re[ve],Oe=ve<re.length-1,h=ve>0,_=Oe||G?.end!==!1,A=ve===re.length-1;if(E(ae)){let F=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(Z)};if(_){let{destroy:Z,cleanup:de}=oe(ae,Oe,h);q.push(Z),v(ae)&&A&&K.push(de)}ae.on("error",F),v(ae)&&A&&K.push(()=>{ae.removeListener("error",F)})}if(ve===0)if(typeof ae=="function"){if(be=ae({signal:ne}),!S(be))throw new g("Iterable, AsyncIterable or Stream","source",be)}else S(ae)||x(ae)||I(ae)?be=ae:be=u.from(ae);else if(typeof ae=="function"){if(I(be)){var H;be=W((H=be)===null||H===void 0?void 0:H.readable)}else be=W(be);if(be=ae(be,{signal:ne}),Oe){if(!S(be,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,be)}else{var me;$||($=bs());let F=new $({objectMode:!0}),Z=(me=be)===null||me===void 0?void 0:me.then;if(typeof Z=="function")te++,Z.call(be,V=>{R=V,V!=null&&F.write(V),_&&F.end(),t.nextTick(he)},V=>{F.destroy(V),t.nextTick(he,V)});else if(S(be,!0))te++,D(be,F,he,{end:_});else if(O(be)||I(be)){let V=be.readable||be;te++,D(V,F,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",be);be=F;let{destroy:de,cleanup:_e}=oe(be,!1,!0);q.push(de),A&&K.push(_e)}}else if(E(ae)){if(x(be)){te+=2;let F=ge(be,ae,he,{end:_});v(ae)&&A&&K.push(F)}else if(I(be)||O(be)){let F=be.readable||be;te++,D(F,ae,he,{end:_})}else if(S(be))te++,D(be,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else if(P(ae)){if(x(be))te++,X(W(be),ae,he,{end:_});else if(O(be)||S(be))te++,X(be,ae,he,{end:_});else if(I(be))te++,X(be.readable,ae,he,{end:_});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],be);be=ae}else be=u.from(ae)}return(ne!=null&&ne.aborted||z!=null&&z.aborted)&&t.nextTick(Q),be}function ge(re,we,G,{end:j}){let ne=!1;if(we.on("close",()=>{ne||G(new b)}),re.pipe(we,{end:!1}),j){let z=function(){ne=!0,we.end()};B(re)?t.nextTick(z):re.once("end",z)}else G();return a(re,{readable:!0,writable:!1},z=>{let K=re._readableState;z&&z.code==="ERR_STREAM_PREMATURE_CLOSE"&&K&&K.ended&&!K.errored&&!K.errorEmitted?re.once("end",G).once("error",G):G(z)}),a(we,{readable:!1,writable:!0},G)}e.exports={pipelineImpl:J,pipeline:L}}),vs=pe((i,e)=>{le(),ue(),ce();var{pipeline:t}=Si(),r=mt(),{destroyer:s}=Wt(),{isNodeStream:n,isReadable:o,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=pt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:f}}=Ke(),y=Et();e.exports=function(...b){if(b.length===0)throw new f("streams");if(b.length===1)return r.from(b[0]);let w=[...b];if(typeof b[0]=="function"&&(b[0]=r.from(b[0])),typeof b[b.length-1]=="function"){let T=b.length-1;b[T]=r.from(b[T])}for(let T=0;T<b.length;++T)if(!(!n(b[T])&&!l(b[T]))){if(T<b.length-1&&!(o(b[T])||d(b[T])||c(b[T])))throw new g(`streams[${T}]`,w[T],"must be readable");if(T>0&&!(a(b[T])||u(b[T])||c(b[T])))throw new g(`streams[${T}]`,w[T],"must be writable")}let m,k,S,v,x;function E(T){let $=v;v=null,$?$(T):T?x.destroy(T):!B&&!O&&x.destroy()}let I=b[0],P=t(b,E),O=!!(a(I)||u(I)||c(I)),B=!!(o(P)||d(P)||c(P));if(x=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:B}),O){if(n(I))x._write=function($,M,U){I.write($,M)?U():m=U},x._final=function($){I.end(),k=$},I.on("drain",function(){if(m){let $=m;m=null,$()}});else if(l(I)){let $=(c(I)?I.writable:I).getWriter();x._write=async function(M,U,oe){try{await $.ready,$.write(M).catch(()=>{}),oe()}catch(Y){oe(Y)}},x._final=async function(M){try{await $.ready,$.close().catch(()=>{}),k=M}catch(U){M(U)}}}let T=c(P)?P.readable:P;y(T,()=>{if(k){let $=k;k=null,$()}})}if(B){if(n(P))P.on("readable",function(){if(S){let T=S;S=null,T()}}),P.on("end",function(){x.push(null)}),x._read=function(){for(;;){let T=P.read();if(T===null){S=x._read;return}if(!x.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();x._read=async function(){for(;;)try{let{value:$,done:M}=await T.read();if(!x.push($))return;if(M){x.push(null);return}}catch{return}}}}return x._destroy=function(T,$){!T&&v!==null&&(T=new p),S=null,m=null,k=null,v===null?$(T):(v=$,n(P)&&s(P,T))},x}}),tu=pe((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||nr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:s,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:o},AbortError:a}=Ke(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=or(),d=Be().Symbol("kWeak"),p=Be().Symbol("kResistStopPropagation"),{finished:g}=Et(),f=vs(),{addAbortSignalNoValidate:y}=_r(),{isWritable:b,isNodeStream:w}=pt(),{deprecate:m}=Qe(),{ArrayPrototypePush:k,Boolean:S,MathFloor:v,Number:x,NumberIsNaN:E,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:B,Symbol:T}=Be(),$=T("kEmpty"),M=T("kEof");function U(z,K){if(K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),w(z)&&!b(z))throw new r("stream",z,"must be writable");let Q=f(this,z);return K!=null&&K.signal&&y(K.signal,Q),Q}function oe(z,K){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal");let Q=1;K?.concurrency!=null&&(Q=v(K.concurrency));let ye=Q-1;return K?.highWaterMark!=null&&(ye=v(K.highWaterMark)),c(Q,"options.concurrency",1),c(ye,"options.highWaterMark",0),ye+=Q,(async function*(){let se=Qe().AbortSignalAny([K?.signal].filter(S)),R=this,q=[],te={signal:se},he,fe,be=!1,H=0;function me(){be=!0,ve()}function ve(){H-=1,ae()}function ae(){fe&&!be&&H<Q&&q.length<ye&&(fe(),fe=null)}async function Oe(){try{for await(let h of R){if(be)return;if(se.aborted)throw new a;try{if(h=z(h,te),h===$)continue;h=O(h)}catch(_){h=P(_)}H+=1,B(h,ve,me),q.push(h),he&&(he(),he=null),!be&&(q.length>=ye||H>=Q)&&await new I(_=>{fe=_})}q.push(M)}catch(h){let _=P(h);B(_,ve,me),q.push(_)}finally{be=!0,he&&(he(),he=null)}}Oe();try{for(;;){for(;q.length>0;){let h=await q[0];if(h===M)return;if(se.aborted)throw new a;h!==$&&(yield h),q.shift(),ae()}await new I(h=>{he=h})}}finally{be=!0,fe&&(fe(),fe=null)}}).call(this)}function Y(z=void 0){return z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal"),(async function*(){let K=0;for await(let ye of this){var Q;if(z!=null&&(Q=z.signal)!==null&&Q!==void 0&&Q.aborted)throw new a({cause:z.signal.reason});yield[K++,ye]}}).call(this)}async function W(z,K=void 0){for await(let Q of L.call(this,z,K))return!0;return!1}async function ee(z,K=void 0){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);return!await W.call(this,async(...Q)=>!await z(...Q),K)}async function D(z,K){for await(let Q of L.call(this,z,K))return Q}async function X(z,K){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function Q(ye,se){return await z(ye,se),$}for await(let ye of oe.call(this,Q,K));}function L(z,K){if(typeof z!="function")throw new s("fn",["Function","AsyncFunction"],z);async function Q(ye,se){return await z(ye,se)?ye:$}return oe.call(this,Q,K)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function ge(z,K,Q){var ye;if(typeof z!="function")throw new s("reducer",["Function","AsyncFunction"],z);Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal");let se=arguments.length>1;if(Q!=null&&(ye=Q.signal)!==null&&ye!==void 0&&ye.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 te=!1;try{for await(let fe of this){var he;if(te=!0,Q!=null&&(he=Q.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?K=await z(K,fe,{signal:q}):(K=fe,se=!0)}if(!te&&!se)throw new J}finally{R.abort()}return K}async function re(z){z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal");let K=[];for await(let ye of this){var Q;if(z!=null&&(Q=z.signal)!==null&&Q!==void 0&&Q.aborted)throw new a(void 0,{cause:z.signal.reason});k(K,ye)}return K}function we(z,K){let Q=oe.call(this,z,K);return(async function*(){for await(let ye of Q)yield*ye}).call(this)}function G(z){if(z=x(z),E(z))return 0;if(z<0)throw new o("number",">= 0",z);return z}function j(z,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),z=G(z),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new a;for await(let se of this){var ye;if(K!=null&&(ye=K.signal)!==null&&ye!==void 0&&ye.aborted)throw new a;z--<=0&&(yield se)}}).call(this)}function ne(z,K=void 0){return K!=null&&u(K,"options"),K?.signal!=null&&l(K.signal,"options.signal"),z=G(z),(async function*(){var Q;if(K!=null&&(Q=K.signal)!==null&&Q!==void 0&&Q.aborted)throw new a;for await(let se of this){var ye;if(K!=null&&(ye=K.signal)!==null&&ye!==void 0&&ye.aborted)throw new a;if(z-- >0&&(yield se),z<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:L,flatMap:we,map:oe,take:ne,compose:U},e.exports.promiseReturningOperators={every:ee,forEach:X,reduce:ge,toArray:re,some:W,find:D}}),ws=pe((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:s,isNodeStream:n,isWebStream:o}=pt(),{pipelineImpl:a}=Si(),{finished:l}=Et();ks();function c(...u){return new r((d,p)=>{let g,f,y=u[u.length-1];if(y&&typeof y=="object"&&!n(y)&&!s(y)&&!o(y)){let b=t(u);g=b.signal,f=b.end}a(u,(b,w)=>{b?p(b):d(w)},{signal:g,end:f})})}e.exports={finished:l,pipeline:c}}),ks=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),{ObjectDefineProperty:r,ObjectKeys:s,ReflectApply:n}=Be(),{promisify:{custom:o}}=Qe(),{streamReturningOperators:a,promiseReturningOperators:l}=tu(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ke(),u=vs(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=Sr(),{pipeline:g}=Si(),{destroyer:f}=Wt(),y=Et(),b=ws(),w=pt(),m=e.exports=ki().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=xr();for(let S of s(a)){let v=function(...E){if(new.target)throw c();return m.Readable.from(n(x,this,E))},x=a[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let S of s(l)){let v=function(...E){if(new.target)throw c();return n(x,this,E)},x=l[S];r(v,"name",{__proto__:null,value:x.name}),r(v,"length",{__proto__:null,value:x.length}),r(m.Readable.prototype,S,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=_i(),m.Duplex=mt(),m.Transform=ys(),m.PassThrough=bs(),m.pipeline=g;var{addAbortSignal:k}=_r();m.addAbortSignal=k,m.finished=y,m.destroy=f,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return b}}),r(g,o,{__proto__:null,enumerable:!0,get(){return b.pipeline}}),r(y,o,{__proto__:null,enumerable:!0,get(){return b.finished}}),m.Stream=m,m._isUint8Array=function(S){return S instanceof Uint8Array},m._uint8ArrayToBuffer=function(S){return t.from(S.buffer,S.byteOffset,S.byteLength)}}),Nt=pe((i,e)=>{le(),ue(),ce();var t=ks(),r=ws(),s=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=s,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),ru=pe((i,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var s=function(){};s.prototype=r.prototype,t.prototype=new s,t.prototype.constructor=t}}}),nu=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),r=Symbol.for("BufferList");function s(n){if(!(this instanceof s))return new s(n);s._init.call(this,n)}s._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},s.prototype._new=function(n){return new s(n)},s.prototype._offset=function(n){if(n===0)return[0,0];let o=0;for(let a=0;a<this._bufs.length;a++){let l=o+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-o];o=l}},s.prototype._reverseOffset=function(n){let o=n[0],a=n[1];for(let l=0;l<o;l++)a+=this._bufs[l].length;return a},s.prototype.getBuffers=function(){return this._bufs},s.prototype.get=function(n){if(n>this.length||n<0)return;let o=this._offset(n);return this._bufs[o[0]][o[1]]},s.prototype.slice=function(n,o){return typeof n=="number"&&n<0&&(n+=this.length),typeof o=="number"&&o<0&&(o+=this.length),this.copy(null,0,n,o)},s.prototype.copy=function(n,o,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,p=d,g=c&&o||0,f=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let y=0;y<this._bufs.length;y++)this._bufs[y].copy(n,g),g+=this._bufs[y].length;return n}if(p<=this._bufs[u[0]].length-f)return c?this._bufs[u[0]].copy(n,o,f,f+p):this._bufs[u[0]].slice(f,f+p);c||(n=t.allocUnsafe(d));for(let y=u[0];y<this._bufs.length;y++){let b=this._bufs[y].length-f;if(p>b)this._bufs[y].copy(n,g,f),g+=b;else{this._bufs[y].copy(n,g,f,f+p),g+=b;break}p-=b,f&&(f=0)}return n.length>g?n.slice(0,g):n},s.prototype.shallowSlice=function(n,o){if(n=n||0,o=typeof o!="number"?this.length:o,n<0&&(n+=this.length),o<0&&(o+=this.length),n===o)return this._new();let a=this._offset(n),l=this._offset(o),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},s.prototype.toString=function(n,o,a){return this.slice(o,a).toString(n)},s.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},s.prototype.duplicate=function(){let n=this._new();for(let o=0;o<this._bufs.length;o++)n.append(this._bufs[o]);return n},s.prototype.append=function(n){return this._attach(n,s.prototype._appendBuffer)},s.prototype.prepend=function(n){return this._attach(n,s.prototype._prependBuffer,!0)},s.prototype._attach=function(n,o,a){if(n==null)return this;if(n.buffer)o.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],o,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],o,a)}else typeof n=="number"&&(n=n.toString()),o.call(this,t.from(n));return this},s.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},s.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},s.prototype.indexOf=function(n,o,a){if(a===void 0&&typeof o=="string"&&(a=o,o=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),o=Number(o||0),isNaN(o)&&(o=0),o<0&&(o=this.length+o),o<0&&(o=0),n.length===0)return o>this.length?this.length:o;let l=this._offset(o),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},s.prototype._match=function(n,o){if(this.length-n<o.length)return!1;for(let a=0;a<o.length;a++)if(this.get(n+a)!==o[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let o in n)(function(a){n[a]===null?s.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:s.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(o)})(),s.prototype._isBufferList=function(n){return n instanceof s||s.isBufferList(n)},s.isBufferList=function(n){return n!=null&&n[r]},e.exports=s}),iu=pe((i,e)=>{le(),ue(),ce();var t=Nt().Duplex,r=ru(),s=nu();function n(o){if(!(this instanceof n))return new n(o);if(typeof o=="function"){this._callback=o;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),o=null}s._init.call(this,o),t.call(this)}r(n,t),Object.assign(n.prototype,s.prototype),n.prototype._new=function(o){return new n(o)},n.prototype._write=function(o,a,l){this._appendBuffer(o),typeof l=="function"&&l()},n.prototype._read=function(o){if(!this.length)return this.push(null);o=Math.min(o,this.length),this.push(this.slice(0,o)),this.consume(o)},n.prototype.end=function(o){t.prototype.end.call(this,o),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(o,a){this._bufs.length=0,this.length=0,a(o)},n.prototype._isBufferList=function(o){return o instanceof n||o instanceof s||n.isBufferList(o)},n.isBufferList=s.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=s}),ou=pe((i,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),_s=pe((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(qe(),Ne($e));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let o=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+o.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let o=t.types[n];t.codes[o]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let o=t.properties[n];t.propertiesCodes[o]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function s(n){return[0,1,2].map(o=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|o<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=s("publish"),t.SUBSCRIBE_HEADER=s("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=s("unsubscribe"),t.ACKS={unsuback:s("unsuback"),puback:s("puback"),pubcomp:s("pubcomp"),pubrel:s("pubrel"),pubrec:s("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),su=pe((i,e)=>{le(),ue(),ce();var t=1e3,r=t*60,s=r*60,n=s*24,o=n*7,a=n*365.25;e.exports=function(p,g){g=g||{};var f=typeof p;if(f==="string"&&p.length>0)return l(p);if(f==="number"&&isFinite(p))return g.long?u(p):c(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function l(p){if(p=String(p),!(p.length>100)){var g=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(g){var f=parseFloat(g[1]),y=(g[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return f*a;case"weeks":case"week":case"w":return f*o;case"days":case"day":case"d":return f*n;case"hours":case"hour":case"hrs":case"hr":case"h":return f*s;case"minutes":case"minute":case"mins":case"min":case"m":return f*r;case"seconds":case"second":case"secs":case"sec":case"s":return f*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return f;default:return}}}}function c(p){var g=Math.abs(p);return g>=n?Math.round(p/n)+"d":g>=s?Math.round(p/s)+"h":g>=r?Math.round(p/r)+"m":g>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var g=Math.abs(p);return g>=n?d(p,g,n,"day"):g>=s?d(p,g,s,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,f,y){var b=g>=f*1.5;return Math.round(p/f)+" "+y+(b?"s":"")}}),au=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=su(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function s(g){let f=0;for(let y=0;y<g.length;y++)f=(f<<5)-f+g.charCodeAt(y),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=s;function n(g){let f,y=null,b,w;function m(...k){if(!m.enabled)return;let S=m,v=Number(new Date),x=v-(f||v);S.diff=x,S.prev=f,S.curr=v,f=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";E++;let O=n.formatters[P];if(typeof O=="function"){let B=k[E];I=O.call(S,B),k.splice(E,1),E--}return I}),n.formatArgs.call(S,k),(S.log||n.log).apply(S,k)}return m.namespace=g,m.useColors=n.useColors(),m.color=n.selectColor(g),m.extend=o,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>y!==null?y:(b!==n.namespaces&&(b=n.namespaces,w=n.enabled(g)),w),set:k=>{y=k}}),typeof n.init=="function"&&n.init(m),m}function o(g,f){let y=n(this.namespace+(typeof f>"u"?":":f)+g);return y.log=this.log,y}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let f=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let y of f)y[0]==="-"?n.skips.push(y.slice(1)):n.names.push(y)}function l(g,f){let y=0,b=0,w=-1,m=0;for(;y<g.length;)if(b<f.length&&(f[b]===g[y]||f[b]==="*"))f[b]==="*"?(w=b,m=y,b++):(y++,b++);else if(w!==-1)b=w+1,m++,y=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function c(){let g=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),g}function u(g){for(let f of n.skips)if(l(g,f))return!1;for(let f of n.names)if(l(g,f))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function p(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}e.exports=t}),gt=pe((i,e)=>{le(),ue(),ce(),i.formatArgs=r,i.save=s,i.load=n,i.useColors=t,i.storage=o(),i.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),i.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}i.log=console.debug||console.log||(()=>{});function s(l){try{l?i.storage.setItem("debug",l):i.storage.removeItem("debug")}catch{}}function n(){let l;try{l=i.storage.getItem("debug")||i.storage.getItem("DEBUG")}catch{}return!l&&typeof je<"u"&&"env"in je&&(l=je.env.DEBUG),l}function o(){try{return localStorage}catch{}}e.exports=au()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),lu=pe((i,e)=>{le(),ue(),ce();var t=iu(),{EventEmitter:r}=(Lt(),Ne(xt)),s=ou(),n=_s(),o=gt()("mqtt-packet:parser"),a=class Uo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Uo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Uo().parser(c)}_resetState(){o("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),o("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,o("parse: state complete. _stateCounter is now: %d",this._stateCounter),o("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return o("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=c&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,o("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),o("_parseLength %d",c.value),!!c}_parsePayload(){o("_parsePayload: payload %O",this._list);let c=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}c=!0}return o("_parsePayload complete result: %s",c),c}_parseConnect(){o("_parseConnect");let c,u,d,p,g={},f=this.packet,y=this._parseString();if(y===null)return this._emitError(new Error("Cannot parse protocolId"));if(y!=="MQTT"&&y!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(f.protocolId=y,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(f.protocolVersion=this._list.readUInt8(this._pos),f.protocolVersion>=128&&(f.bridgeMode=!0,f.protocolVersion=f.protocolVersion-128),f.protocolVersion!==3&&f.protocolVersion!==4&&f.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));g.username=this._list.readUInt8(this._pos)&n.USERNAME_MASK,g.password=this._list.readUInt8(this._pos)&n.PASSWORD_MASK,g.will=this._list.readUInt8(this._pos)&n.WILL_FLAG_MASK;let b=!!(this._list.readUInt8(this._pos)&n.WILL_RETAIN_MASK),w=(this._list.readUInt8(this._pos)&n.WILL_QOS_MASK)>>n.WILL_QOS_SHIFT;if(g.will)f.will={},f.will.retain=b,f.will.qos=w;else{if(b)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(w)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(f.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,f.keepalive=this._parseNum(),f.keepalive===-1)return this._emitError(new Error("Packet too short"));if(f.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(f.clientId=m,o("_parseConnect: packet.clientId: %s",f.clientId),g.will){if(f.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(f.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(f.will.topic=c,o("_parseConnect: packet.will.topic: %s",f.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));f.will.payload=u,o("_parseConnect: packet.will.paylaod: %s",f.will.payload)}if(g.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));f.username=p,o("_parseConnect: packet.username: %s",f.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));f.password=d}return this.settings=f,o("_parseConnect: complete"),f}_parseConnack(){o("_parseConnack");let c=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}o("_parseConnack: complete")}_parsePublish(){o("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),o("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){o("_parseSubscribe");let c=this.packet,u,d,p,g,f,y,b;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(y=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,f=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));b={topic:u,qos:p},this.settings.protocolVersion===5?(b.nl=y,b.rap=f,b.rh=g):this.settings.bridgeMode&&(b.rh=0,b.rap=!0,b.nl=!0),o("_parseSubscribe: push subscription `%s` to subscription",b),c.subscriptions.push(b)}}}_parseSuback(){o("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){o("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));o("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){o("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){o("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}o("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(o("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return o("_parseDisconnect result: true"),!0}_parseAuth(){o("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),o("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(o("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,o("_parseString: result: %s",p),p}_parseStringPair(){return o("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=c,o("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,o("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,o("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){o("_parseVarByteNum");let u=4,d=0,p=1,g=0,f=!1,y,b=this._pos?this._pos:0;for(;d<u&&b+d<this._list.length;){if(y=this._list.readUInt8(b+d++),g+=p*(y&n.VARBYTEINT_MASK),p*=128,(y&n.VARBYTEINT_FIN_MASK)===0){f=!0;break}if(this._list.length<=d)break}return!f&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),b&&(this._pos+=d),f?c?f={bytes:d,value:g}:f=g:f=!1,o("_parseVarByteNum: result: %o",f),f}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),o("_parseByte: result: %o",c),c}_parseByType(c){switch(o("_parseByType: type: %s",c),c){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){o("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[p];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let f=this._parseByType(n.propertiesTypes[g]);if(d[g][f.name])if(Array.isArray(d[g][f.name]))d[g][f.name].push(f.value);else{let y=d[g][f.name];d[g][f.name]=[y],d[g][f.name].push(f.value)}else d[g][f.name]=f.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return o("_newPacket"),this.packet&&(this._list.consume(this.packet.length),o("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),o("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(c){o("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),cu=pe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Ne($e)),r=65536,s={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function o(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)s[u]=o(u)}function l(u){let d=0,p=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?g.subarray(0,p):g.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:s,generateCache:a,generateNumber:o,genBufVariableByteInt:l,generate4ByteBuffer:c}}),uu=pe((i,e)=>{le(),ue(),ce(),typeof je>"u"||!je.version||je.version.indexOf("v0.")===0||je.version.indexOf("v1.")===0&&je.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=je;function t(r,s,n,o){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return je.nextTick(r);case 2:return je.nextTick(function(){r.call(null,s)});case 3:return je.nextTick(function(){r.call(null,s,n)});case 4:return je.nextTick(function(){r.call(null,s,n,o)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return je.nextTick(function(){r.apply(null,l)})}}}),Ss=pe((i,e)=>{le(),ue(),ce();var t=_s(),{Buffer:r}=(qe(),Ne($e)),s=r.allocUnsafe(0),n=r.from([0]),o=cu(),a=uu().nextTick,l=gt()("mqtt-packet:writeToStream"),c=o.cache,u=o.generateNumber,d=o.generateCache,p=o.genBufVariableByteInt,g=o.generate4ByteBuffer,f=Y,y=!0;function b(G,j,ne){switch(l("generate called"),j.cork&&(j.cork(),a(w,j)),y&&(y=!1,d()),l("generate: packet.cmd: %s",G.cmd),G.cmd){case"connect":return m(G,j);case"connack":return k(G,j,ne);case"publish":return S(G,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(G,j,ne);case"subscribe":return x(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(b,"cacheNumbers",{get(){return f===Y},set(G){G?((!c||Object.keys(c).length===0)&&(y=!0),f=Y):(y=!1,f=W)}});function w(G){G.uncork()}function m(G,j,ne){let z=G||{},K=z.protocolId||"MQTT",Q=z.protocolVersion||4,ye=z.will,se=z.clean,R=z.keepalive||0,q=z.clientId||"",te=z.username,he=z.password,fe=z.properties;se===void 0&&(se=!0);let be=0;if(typeof K!="string"&&!r.isBuffer(K))return j.destroy(new Error("Invalid protocolId")),!1;if(be+=K.length+2,Q!==3&&Q!==4&&Q!==5)return j.destroy(new Error("Invalid protocol version")),!1;if(be+=1,(typeof q=="string"||r.isBuffer(q))&&(q||Q>=4)&&(q||se))be+=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;be+=2,be+=1;let H,me;if(Q===5){if(H=X(j,fe),!H)return!1;be+=H.length}if(ye){if(typeof ye!="object")return j.destroy(new Error("Invalid will")),!1;if(!ye.topic||typeof ye.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(be+=r.byteLength(ye.topic)+2,be+=2,ye.payload)if(ye.payload.length>=0)typeof ye.payload=="string"?be+=r.byteLength(ye.payload):be+=ye.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=X(j,ye.properties),!me)return!1;be+=me.length}}let ve=!1;if(te!=null)if(we(te))ve=!0,be+=r.byteLength(te)+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))be+=re(he)+2;else return j.destroy(new Error("Invalid password")),!1}j.write(t.CONNECT_HEADER),M(j,be),D(j,K),z.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|=te!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=ye&&ye.retain?t.WILL_RETAIN_MASK:0,ae|=ye&&ye.qos?ye.qos<<t.WILL_QOS_SHIFT:0,ae|=ye?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,j.write(r.from([ae])),f(j,R),Q===5&&H.write(),D(j,q),ye&&(Q===5&&me.write(),U(j,ye.topic),D(j,ye.payload)),te!=null&&D(j,te),he!=null&&D(j,he),!0}function k(G,j,ne){let z=ne?ne.protocolVersion:4,K=G||{},Q=z===5?K.reasonCode:K.returnCode,ye=K.properties,se=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let R=null;if(z===5){if(R=X(j,ye),!R)return!1;se+=R.length}return j.write(t.CONNACK_HEADER),M(j,se),j.write(K.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),R?.write(),!0}function S(G,j,ne){l("publish: packet: %o",G);let z=ne?ne.protocolVersion:4,K=G||{},Q=K.qos||0,ye=K.retain?t.RETAIN_MASK:0,se=K.topic,R=K.payload||s,q=K.messageId,te=K.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(z===5){if(fe=X(j,te),!fe)return!1;he+=fe.length}return j.write(t.PUBLISH_HEADER[Q][K.dup?1:0][ye?1:0]),M(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 z=ne?ne.protocolVersion:4,K=G||{},Q=K.cmd||"puback",ye=K.messageId,se=K.dup&&Q==="pubrel"?t.DUP_MASK:0,R=0,q=K.reasonCode,te=K.properties,he=z===5?3:2;if(Q==="pubrel"&&(R=1),typeof ye!="number")return j.destroy(new Error("Invalid messageId")),!1;let fe=null;if(z===5&&typeof te=="object"){if(fe=L(j,te,ne,he),!fe)return!1;he+=fe.length}return j.write(t.ACKS[Q][R][se][0]),he===3&&(he+=q!==0?1:-1),M(j,he),f(j,ye),z===5&&he!==2&&j.write(r.from([q])),fe!==null?fe.write():he===4&&j.write(r.from([0])),!0}function x(G,j,ne){l("subscribe: packet: ");let z=ne?ne.protocolVersion:4,K=G||{},Q=K.dup?t.DUP_MASK:0,ye=K.messageId,se=K.subscriptions,R=K.properties,q=0;if(typeof ye!="number")return j.destroy(new Error("Invalid messageId")),!1;q+=2;let te=null;if(z===5){if(te=X(j,R),!te)return!1;q+=te.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let be=se[fe].topic,H=se[fe].qos;if(typeof be!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(z===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(be)+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]),M(j,q),f(j,ye),te!==null&&te.write();let he=!0;for(let fe of se){let be=fe.topic,H=fe.qos,me=+fe.nl,ve=+fe.rap,ae=fe.rh,Oe;U(j,be),Oe=t.SUBSCRIBE_OPTIONS_QOS[H],z===5&&(Oe|=me?t.SUBSCRIBE_OPTIONS_NL:0,Oe|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Oe|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=j.write(r.from([Oe]))}return he}function E(G,j,ne){let z=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ye=K.granted,se=K.properties,R=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(R+=2,typeof ye=="object"&&ye.length)for(let te=0;te<ye.length;te+=1){if(typeof ye[te]!="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(z===5){if(q=L(j,se,ne,R),!q)return!1;R+=q.length}return j.write(t.SUBACK_HEADER),M(j,R),f(j,Q),q!==null&&q.write(),j.write(r.from(ye))}function I(G,j,ne){let z=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ye=K.dup?t.DUP_MASK:0,se=K.unsubscriptions,R=K.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 te=null;if(z===5){if(te=X(j,R),!te)return!1;q+=te.length}j.write(t.UNSUBSCRIBE_HEADER[1][ye?1:0][0]),M(j,q),f(j,Q),te!==null&&te.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(j,se[fe]);return he}function P(G,j,ne){let z=ne?ne.protocolVersion:4,K=G||{},Q=K.messageId,ye=K.dup?t.DUP_MASK:0,se=K.granted,R=K.properties,q=K.cmd,te=0,he=2;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(z===5)if(typeof se=="object"&&se.length)for(let be=0;be<se.length;be+=1){if(typeof se[be]!="number")return j.destroy(new Error("Invalid qos vector")),!1;he+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(z===5){if(fe=L(j,R,ne,he),!fe)return!1;he+=fe.length}return j.write(t.ACKS[q][te][ye][0]),M(j,he),f(j,Q),fe!==null&&fe.write(),z===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 z=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ye=K.properties,se=z===5?1:0,R=null;if(z===5){if(R=L(j,ye,ne,se),!R)return!1;se+=R.length}return j.write(r.from([t.codes.disconnect<<4])),M(j,se),z===5&&j.write(r.from([Q])),R!==null&&R.write(),!0}function T(G,j,ne){let z=ne?ne.protocolVersion:4,K=G||{},Q=K.reasonCode,ye=K.properties,se=z===5?1:0;z!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let R=L(j,ye,ne,se);return R?(se+=R.length,j.write(r.from([t.codes.auth<<4])),M(j,se),j.write(r.from([Q])),R!==null&&R.write(),!0):!1}var $={};function M(G,j){if(j>t.VARBYTEINT_MAX)return G.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=$[j];return ne||(ne=p(j),j<16384&&($[j]=ne)),l("writeVarByteInt: writing to stream: %o",ne),G.write(ne)}function U(G,j){let ne=r.byteLength(j);return f(G,ne),l("writeString: %s",j),G.write(j,"utf8")}function oe(G,j,ne){U(G,j),U(G,ne)}function Y(G,j){return l("writeNumberCached: number: %d",j),l("writeNumberCached: %o",c[j]),G.write(c[j])}function W(G,j){let ne=u(j);return l("writeNumberGenerated: %o",ne),G.write(ne)}function ee(G,j){let ne=g(j);return l("write4ByteNumber: %o",ne),G.write(ne)}function D(G,j){typeof j=="string"?U(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(){ge(G,{},0)}};let ne=0;function z(K,Q){let ye=t.propertiesTypes[K],se=0;switch(ye){case"byte":{if(typeof Q!="boolean")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=2;break}case"binary":{if(Q&&Q===null)return G.destroy(new Error(`Invalid ${K}: ${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 ${K}: ${Q}`)),!1;se+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=1+r.byteLength(p(Q));break}case"string":{if(typeof Q!="string")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return G.destroy(new Error(`Invalid ${K}: ${Q}`)),!1;se+=Object.getOwnPropertyNames(Q).reduce((R,q)=>{let te=Q[q];return Array.isArray(te)?R+=te.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 ${K}: ${Q}`)),!1}return se}if(j)for(let K in j){let Q=0,ye=0,se=j[K];if(se!==void 0){if(Array.isArray(se))for(let R=0;R<se.length;R++){if(ye=z(K,se[R]),!ye)return!1;Q+=ye}else{if(ye=z(K,se),!ye)return!1;Q=ye}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(p(ne))+ne,write(){ge(G,j,ne)}}}function L(G,j,ne,z){let K=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,ye=X(G,j);if(Q)for(;z+ye.length>Q;){let se=K.shift();if(se&&j[se])delete j[se],ye=X(G,j);else return!1}return ye}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]])),D(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]])),ee(G,ne);break}case"var":{G.write(r.from([t.properties[j]])),M(G,ne);break}case"string":{G.write(r.from([t.properties[j]])),U(G,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(z=>{let K=ne[z];Array.isArray(K)?K.forEach(Q=>{G.write(r.from([t.properties[j]])),oe(G,z.toString(),Q.toString())}):(G.write(r.from([t.properties[j]])),oe(G,z.toString(),K.toString()))});break}default:return G.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function ge(G,j,ne){M(G,ne);for(let z in j)if(Object.prototype.hasOwnProperty.call(j,z)&&j[z]!=null){let K=j[z];if(Array.isArray(K))for(let Q=0;Q<K.length;Q++)J(G,z,K[Q]);else J(G,z,K)}}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=b}),du=pe((i,e)=>{le(),ue(),ce();var t=Ss(),{EventEmitter:r}=(Lt(),Ne(xt)),{Buffer:s}=(qe(),Ne($e));function n(a,l){let c=new o;return t(a,c,l),c.concat()}var o=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=s.byteLength(c[d]),a+=l[d];let p=s.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),hu=pe(i=>{le(),ue(),ce(),i.parser=lu().parser,i.generate=du(),i.writeToStream=Ss()}),fu=pe((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof kr?kr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return s(n);let o=new Map;if(o.set(Date,d=>new Date(d)),o.set(Map,(d,p)=>new Map(l(Array.from(d),p))),o.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)o.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,p){let g=Object.keys(d),f=new Array(g.length);for(let y=0;y<g.length;y++){let b=g[y],w=d[b];typeof w!="object"||w===null?f[b]=w:w.constructor!==Object&&(a=o.get(w.constructor))?f[b]=a(w,p):ArrayBuffer.isView(w)?f[b]=t(w):f[b]=p(w)}return f}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,c);let p={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[g]=a(f,c):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=c(f)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=o.get(d.constructor)))return a(d,u);let p={};for(let g in d){let f=d[g];typeof f!="object"||f===null?p[g]=f:f.constructor!==Object&&(a=o.get(f.constructor))?p[g]=a(f,u):ArrayBuffer.isView(f)?p[g]=t(f):p[g]=u(f)}return p}}function s(n){let o=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,f)=>new Map(u(Array.from(g),f))),l.set(Set,(g,f)=>new Set(u(Array.from(g),f))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?p:d;function u(g,f){let y=Object.keys(g),b=new Array(y.length);for(let w=0;w<y.length;w++){let m=y[w],k=g[m];if(typeof k!="object"||k===null)b[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))b[m]=c(k,f);else if(ArrayBuffer.isView(k))b[m]=t(k);else{let S=o.indexOf(k);S!==-1?b[m]=a[S]:b[m]=f(k)}}return b}function d(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,d);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,d);let f={};o.push(g),a.push(f);for(let y in g){if(Object.hasOwnProperty.call(g,y)===!1)continue;let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=l.get(b.constructor)))f[y]=c(b,d);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=a[w]:f[y]=d(b)}}return o.pop(),a.pop(),f}function p(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,p);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,p);let f={};o.push(g),a.push(f);for(let y in g){let b=g[y];if(typeof b!="object"||b===null)f[y]=b;else if(b.constructor!==Object&&(c=l.get(b.constructor)))f[y]=c(b,p);else if(ArrayBuffer.isView(b))f[y]=t(b);else{let w=o.indexOf(b);w!==-1?f[y]=a[w]:f[y]=p(b)}}return o.pop(),a.pop(),f}}}),pu=pe((i,e)=>{le(),ue(),ce(),e.exports=fu()()}),xs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.validateTopic=e,i.validateTopics=t;function e(r){let s=r.split("/");for(let n=0;n<s.length;n++)if(s[n]!=="+"){if(s[n]==="#")return n===s.length-1;if(s[n].indexOf("+")!==-1||s[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let s=0;s<r.length;s++)if(!e(r[s]))return r[s];return null}}),Es=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Nt(),t={objectMode:!0},r={clean:!0},s=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,o){return this._inflights.set(n.messageId,n),o&&o(),this}createStream(){let n=new e.Readable(t),o=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{o.push(c)}),n._read=()=>{!a&&l<o.length?n.push(o[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,o){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),o(null,a)):o&&o(new Error("missing packet")),this}get(n,o){let a=this._inflights.get(n.messageId);return a?o(null,a):o&&o(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};i.default=s}),mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,s,n)=>{r.log("handlePublish: packet %o",s),n=typeof n<"u"?n:r.noop;let o=s.topic.toString(),a=s.payload,{qos:l}=s,{messageId:c}=s,{options:u}=r;if(r.options.protocolVersion===5){let d;if(s.properties&&(d=s.properties.topicAlias),typeof d<"u")if(o.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)o=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",o,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(o,d))r.log("handlePublish :: registered topic: %s - alias: %d",o,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(s,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(o,a,s,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",o,a,s),r.handleMessage(s,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",o,a,s),r.handleMessage(s,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};i.default=t}),gu=pe((i,e)=>{e.exports={version:"5.15.0"}}),zt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.MQTTJS_VERSION=i.nextTick=i.ErrorWithSubackPacket=i.ErrorWithReasonCode=void 0,i.applyMixin=r;var e=class kc extends Error{code;constructor(n,o){super(n),this.code=o,Object.setPrototypeOf(this,kc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class _c extends Error{packet;constructor(n,o){super(n),this.packet=o,Object.setPrototypeOf(this,_c.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};i.ErrorWithSubackPacket=t;function r(s,n,o=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(o||c!=="constructor")&&Object.defineProperty(s.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}i.nextTick=typeof je?.nextTick=="function"?je.nextTick:s=>{setTimeout(s,0)},i.MQTTJS_VERSION=gu().version}),Er=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=zt();i.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,s)=>{let{messageId:n}=s,o=s.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=s.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${i.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,s)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=s.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[p]}`),c.code=p;let g=r.messageIdToTopic[n];g&&g.forEach(f=>{delete r._resubscribeTopics[f]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,s);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,s);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};i.default=t}),yu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=zt(),t=Er(),r=(s,n)=>{let{options:o}=s,a=o.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);s.emit("error",c);return}s.handleAuth(n,(c,u)=>{if(c){s.emit("error",c);return}if(l===24)s.reconnecting=!1,s._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);s.emit("error",d)}})};i.default=r}),bu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof je=="object"&&je?je:{},s=(g,f,y,b)=>{typeof r.emitWarning=="function"?r.emitWarning(g,f,y,b):console.error(`[${y}] ${f}: ${g}`)},n=globalThis.AbortController,o=globalThis.AbortSignal;if(typeof n>"u"){o=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(y,b){this._onabort.push(b)}},n=class{constructor(){f()}signal=new o;abort(y){if(!this.signal.aborted){this.signal.reason=y,this.signal.aborted=!0;for(let b of this.signal._onabort)b(y);this.signal.onabort?.(y)}}};let g=r.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",f=()=>{g&&(g=!1,s("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",f))}}var a=g=>!t.has(g),l=g=>g&&g===Math.floor(g)&&g>0&&isFinite(g),c=g=>l(g)?g<=Math.pow(2,8)?Uint8Array:g<=Math.pow(2,16)?Uint16Array:g<=Math.pow(2,32)?Uint32Array:g<=Number.MAX_SAFE_INTEGER?u:null:null,u=class extends Array{constructor(g){super(g),this.fill(0)}},d=class gr{heap;length;static#l=!1;static create(f){let y=c(f);if(!y)return[];gr.#l=!0;let b=new gr(f,y);return gr.#l=!1,b}constructor(f,y){if(!gr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new y(f),this.length=0}push(f){this.heap[this.length++]=f}pop(){return this.heap[--this.length]}},p=class Sc{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#y;#n;#r;#e;#c;#h;#a;#o;#b;#s;#v;#w;#f;#k;#A;#u;static unsafeExposeInternals(f){return{starts:f.#w,ttls:f.#f,sizes:f.#v,keyMap:f.#n,keyList:f.#r,valList:f.#e,next:f.#c,prev:f.#h,get head(){return f.#a},get tail(){return f.#o},free:f.#b,isBackgroundFetch:y=>f.#t(y),backgroundFetch:(y,b,w,m)=>f.#R(y,b,w,m),moveToTail:y=>f.#C(y),indexes:y=>f.#_(y),rindexes:y=>f.#S(y),isStale:y=>f.#p(y)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#y}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(f){let{max:y=0,ttl:b,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:S,allowStale:v,dispose:x,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:B=0,sizeCalculation:T,fetchMethod:$,memoMethod:M,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:W,ignoreFetchAbort:ee}=f;if(y!==0&&!l(y))throw new TypeError("max option must be a nonnegative integer");let D=y?c(y):Array;if(!D)throw new Error("invalid max value: "+y);if(this.#l=y,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(M!==void 0&&typeof M!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=M,$!==void 0&&typeof $!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=$,this.#A=!!$,this.#n=new Map,this.#r=new Array(y).fill(void 0),this.#e=new Array(y).fill(void 0),this.#c=new D(y),this.#h=new D(y),this.#a=0,this.#o=0,this.#b=d.create(y),this.#i=0,this.#y=0,typeof x=="function"&&(this.#m=x),typeof E=="function"?(this.#g=E,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!ee,this.maxEntrySize!==0){if(this.#d!==0&&!l(this.#d))throw new TypeError("maxSize must be a positive integer if specified");if(!l(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!S,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=b||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#l===0&&this.ttl===0&&this.#d===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#l&&!this.#d){let X="LRU_CACHE_UNBOUNDED";a(X)&&(t.add(X),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",X,Sc))}}getRemainingTTL(f){return this.#n.has(f)?1/0:0}#N(){let f=new u(this.#l),y=new u(this.#l);this.#f=f,this.#w=y,this.#j=(m,k,S=e.now())=>{if(y[m]=k!==0?S:0,f[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#x(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{y[m]=f[m]!==0?e.now():0},this.#E=(m,k)=>{if(f[k]){let S=f[k],v=y[k];if(!S||!v)return;m.ttl=S,m.start=v,m.now=b||w();let x=m.now-v;m.remainingTTL=S-x}};let b=0,w=()=>{let m=e.now();if(this.ttlResolution>0){b=m;let k=setTimeout(()=>b=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let S=f[k],v=y[k];if(!S||!v)return 1/0;let x=(b||w())-v;return S-x},this.#p=m=>{let k=y[m],S=f[m];return!!S&&!!k&&(b||w())-k>S}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#$(){let f=new u(this.#l);this.#y=0,this.#v=f,this.#T=y=>{this.#y-=f[y],f[y]=0},this.#U=(y,b,w,m)=>{if(this.#t(b))return 0;if(!l(w))if(m){if(typeof m!="function")throw new TypeError("sizeCalculation must be a function");if(w=m(b,y),!l(w))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return w},this.#M=(y,b,w)=>{if(f[y]=b,this.#d){let m=this.#d-f[y];for(;this.#y>m;)this.#L(!0)}this.#y+=f[y],w&&(w.entrySize=b,w.totalCalculatedSize=this.#y)}}#T=f=>{};#M=(f,y,b)=>{};#U=(f,y,b,w)=>{if(b||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:f=this.allowStale}={}){if(this.#i)for(let y=this.#o;!(!this.#D(y)||((f||!this.#p(y))&&(yield y),y===this.#a));)y=this.#h[y]}*#S({allowStale:f=this.allowStale}={}){if(this.#i)for(let y=this.#a;!(!this.#D(y)||((f||!this.#p(y))&&(yield y),y===this.#o));)y=this.#c[y]}#D(f){return f!==void 0&&this.#n.get(this.#r[f])===f}*entries(){for(let f of this.#_())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*rentries(){for(let f of this.#S())this.#e[f]!==void 0&&this.#r[f]!==void 0&&!this.#t(this.#e[f])&&(yield[this.#r[f],this.#e[f]])}*keys(){for(let f of this.#_()){let y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*rkeys(){for(let f of this.#S()){let y=this.#r[f];y!==void 0&&!this.#t(this.#e[f])&&(yield y)}}*values(){for(let f of this.#_())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}*rvalues(){for(let f of this.#S())this.#e[f]!==void 0&&!this.#t(this.#e[f])&&(yield this.#e[f])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(f,y={}){for(let b of this.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&f(m,this.#r[b],this))return this.get(this.#r[b],y)}}forEach(f,y=this){for(let b of this.#_()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}rforEach(f,y=this){for(let b of this.#S()){let w=this.#e[b],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&f.call(y,m,this.#r[b],this)}}purgeStale(){let f=!1;for(let y of this.#S({allowStale:!0}))this.#p(y)&&(this.#x(this.#r[y],"expire"),f=!0);return f}info(f){let y=this.#n.get(f);if(y===void 0)return;let b=this.#e[y],w=this.#t(b)?b.__staleWhileFetching:b;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[y],S=this.#w[y];if(k&&S){let v=k-(e.now()-S);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[y]),m}dump(){let f=[];for(let y of this.#_({allowStale:!0})){let b=this.#r[y],w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m===void 0||b===void 0)continue;let k={value:m};if(this.#f&&this.#w){k.ttl=this.#f[y];let S=e.now()-this.#w[y];k.start=Math.floor(Date.now()-S)}this.#v&&(k.size=this.#v[y]),f.unshift([b,k])}return f}load(f){this.clear();for(let[y,b]of f){if(b.start){let w=Date.now()-b.start;b.start=e.now()-w}this.set(y,b.value,b)}}set(f,y,b={}){if(y===void 0)return this.delete(f),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:S=this.sizeCalculation,status:v}=b,{noUpdateTTL:x=this.noUpdateTTL}=b,E=this.#U(f,y,b.size||0,S);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#x(f,"set"),this;let I=this.#i===0?void 0:this.#n.get(f);if(I===void 0)I=this.#i===0?this.#o:this.#b.length!==0?this.#b.pop():this.#i===this.#l?this.#L(!1):this.#i,this.#r[I]=f,this.#e[I]=y,this.#n.set(f,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#M(I,E,v),v&&(v.set="add"),x=!1;else{this.#C(I);let P=this.#e[I];if(y!==P){if(this.#A&&this.#t(P)){P.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:O}=P;O!==void 0&&!k&&(this.#k&&this.#m?.(O,f,"set"),this.#u&&this.#s?.push([O,f,"set"]))}else k||(this.#k&&this.#m?.(P,f,"set"),this.#u&&this.#s?.push([P,f,"set"]));if(this.#T(I),this.#M(I,E,v),this.#e[I]=y,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&&(x||this.#j(I,w,m),v&&this.#E(v,I)),!k&&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,y;for(;y=f?.shift();)this.#g?.(...y)}}}#L(f){let y=this.#a,b=this.#r[y],w=this.#e[y];return this.#A&&this.#t(w)?w.__abortController.abort(new Error("evicted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(w,b,"evict"),this.#u&&this.#s?.push([w,b,"evict"])),this.#T(y),f&&(this.#r[y]=void 0,this.#e[y]=void 0,this.#b.push(y)),this.#i===1?(this.#a=this.#o=0,this.#b.length=0):this.#a=this.#c[y],this.#n.delete(b),this.#i--,y}has(f,y={}){let{updateAgeOnHas:b=this.updateAgeOnHas,status:w}=y,m=this.#n.get(f);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#p(m))w&&(w.has="stale",this.#E(w,m));else return b&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(f,y={}){let{allowStale:b=this.allowStale}=y,w=this.#n.get(f);if(w===void 0||!b&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#R(f,y,b,w){let m=y===void 0?void 0:this.#e[y];if(this.#t(m))return m;let k=new n,{signal:S}=b;S?.addEventListener("abort",()=>k.abort(S.reason),{signal:k.signal});let v={signal:k.signal,options:b,context:w},x=(T,$=!1)=>{let{aborted:M}=k.signal,U=b.ignoreFetchAbort&&T!==void 0;if(b.status&&(M&&!$?(b.status.fetchAborted=!0,b.status.fetchError=k.signal.reason,U&&(b.status.fetchAbortIgnored=!0)):b.status.fetchResolved=!0),M&&!U&&!$)return I(k.signal.reason);let oe=O;return this.#e[y]===O&&(T===void 0?oe.__staleWhileFetching?this.#e[y]=oe.__staleWhileFetching:this.#x(f,"fetch"):(b.status&&(b.status.fetchUpdated=!0),this.set(f,T,v.options))),T},E=T=>(b.status&&(b.status.fetchRejected=!0,b.status.fetchError=T),I(T)),I=T=>{let{aborted:$}=k.signal,M=$&&b.allowStaleOnFetchAbort,U=M||b.allowStaleOnFetchRejection,oe=U||b.noDeleteOnFetchRejection,Y=O;if(this.#e[y]===O&&(!oe||Y.__staleWhileFetching===void 0?this.#x(f,"fetch"):M||(this.#e[y]=Y.__staleWhileFetching)),U)return b.status&&Y.__staleWhileFetching!==void 0&&(b.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},P=(T,$)=>{let M=this.#P?.(f,m,v);M&&M instanceof Promise&&M.then(U=>T(U===void 0?void 0:U),$),k.signal.addEventListener("abort",()=>{(!b.ignoreFetchAbort||b.allowStaleOnFetchAbort)&&(T(void 0),b.allowStaleOnFetchAbort&&(T=U=>x(U,!0)))})};b.status&&(b.status.fetchDispatched=!0);let O=new Promise(P).then(x,E),B=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return y===void 0?(this.set(f,B,{...v.options,status:void 0}),y=this.#n.get(f)):this.#e[y]=B,B}#t(f){if(!this.#A)return!1;let y=f;return!!y&&y instanceof Promise&&y.hasOwnProperty("__staleWhileFetching")&&y.__abortController instanceof n}async fetch(f,y={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:S=this.noDisposeOnSet,size:v=0,sizeCalculation:x=this.sizeCalculation,noUpdateTTL:E=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:T,forceRefresh:$=!1,status:M,signal:U}=y;if(!this.#A)return M&&(M.fetch="get"),this.get(f,{allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:M});let oe={allowStale:b,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:S,size:v,sizeCalculation:x,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:B,ignoreFetchAbort:O,status:M,signal:U},Y=this.#n.get(f);if(Y===void 0){M&&(M.fetch="miss");let W=this.#R(f,Y,oe,T);return W.__returned=W}else{let W=this.#e[Y];if(this.#t(W)){let L=b&&W.__staleWhileFetching!==void 0;return M&&(M.fetch="inflight",L&&(M.returnedStale=!0)),L?W.__staleWhileFetching:W.__returned=W}let ee=this.#p(Y);if(!$&&!ee)return M&&(M.fetch="hit"),this.#C(Y),w&&this.#I(Y),M&&this.#E(M,Y),W;let D=this.#R(f,Y,oe,T),X=D.__staleWhileFetching!==void 0&&b;return M&&(M.fetch=ee?"stale":"refresh",X&&ee&&(M.returnedStale=!0)),X?D.__staleWhileFetching:D.__returned=D}}async forceFetch(f,y={}){let b=await this.fetch(f,y);if(b===void 0)throw new Error("fetch() returned undefined");return b}memo(f,y={}){let b=this.#O;if(!b)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=y,S=this.get(f,k);if(!m&&S!==void 0)return S;let v=b(f,S,{options:k,context:w});return this.set(f,v,k),v}get(f,y={}){let{allowStale:b=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=y,S=this.#n.get(f);if(S!==void 0){let v=this.#e[S],x=this.#t(v);return k&&this.#E(k,S),this.#p(S)?(k&&(k.get="stale"),x?(k&&b&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),b?v.__staleWhileFetching:void 0):(m||this.#x(f,"expire"),k&&b&&(k.returnedStale=!0),b?v:void 0)):(k&&(k.get="hit"),x?v.__staleWhileFetching:(this.#C(S),w&&this.#I(S),v))}else k&&(k.get="miss")}#B(f,y){this.#h[y]=f,this.#c[f]=y}#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.#x(f,"delete")}#x(f,y){let b=!1;if(this.#i!==0){let w=this.#n.get(f);if(w!==void 0)if(b=!0,this.#i===1)this.#F(y);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,f,y),this.#u&&this.#s?.push([m,f,y])),this.#n.delete(f),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let S=this.#c[w];this.#h[S]=this.#h[w]}this.#i--,this.#b.push(w)}}if(this.#u&&this.#s?.length){let w=this.#s,m;for(;m=w?.shift();)this.#g?.(...m)}return b}clear(){return this.#F("delete")}#F(f){for(let y of this.#S({allowStale:!0})){let b=this.#e[y];if(this.#t(b))b.__abortController.abort(new Error("deleted"));else{let w=this.#r[y];this.#k&&this.#m?.(b,w,f),this.#u&&this.#s?.push([b,w,f])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#w&&(this.#f.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#b.length=0,this.#y=0,this.#i=0,this.#u&&this.#s){let y=this.#s,b;for(;b=y?.shift();)this.#g?.(...b)}}};i.LRUCache=p}),yt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.ContainerIterator=i.Container=i.Base=void 0;var e=class{constructor(s=0){this.iteratorType=s}equals(s){return this.o===s.o}};i.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};i.Base=t;var r=class extends t{};i.Container=r}),vu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Base{constructor(s=[]){super(),this.S=[];let n=this;s.forEach(function(o){n.push(o)})}clear(){this.i=0,this.S=[]}push(s){return this.S.push(s),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;i.default=r}),wu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Base{constructor(s=[]){super(),this.j=0,this.q=[];let n=this;s.forEach(function(o){n.push(o)})}clear(){this.q=[],this.i=this.j=0}push(s){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let o=this.i;for(let a=0;a<o;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=s}else this.q[this.j+this.i]=s;return++this.i}pop(){if(this.i===0)return;let s=this.q[this.j++];return this.i-=1,s}front(){if(this.i!==0)return this.q[this.j]}},r=t;i.default=r}),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(s=[],n=function(a,l){return a>l?-1:a<l?1:0},o=!0){if(super(),this.v=n,Array.isArray(s))this.C=o?[...s]:s;else{this.C=[];let l=this;s.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(s){let n=this.C[s];for(;s>0;){let o=s-1>>1,a=this.C[o];if(this.v(a,n)<=0)break;this.C[s]=a,s=o}this.C[s]=n}k(s,n){let o=this.C[s];for(;s<n;){let a=s<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,o)>=0)break;this.C[s]=c,s=a}this.C[s]=o}clear(){this.i=0,this.C.length=0}push(s){this.C.push(s),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let s=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),s}top(){return this.C[0]}find(s){return this.C.indexOf(s)>=0}remove(s){let n=this.C.indexOf(s);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(s){let n=this.C.indexOf(s);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;i.default=r}),xi=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=class extends e.Container{},r=t;i.default=r}),bt=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),As=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=yt(),t=bt(),r=class extends e.ContainerIterator{constructor(s,n){super(n),this.o=s,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(s){this.container.setElementByPos(this.o,s)}};i.RandomIterator=r}),_u=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=As();function r(a){return a&&a.t?a:{default:a}}var s=class xc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new xc(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new s(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},o=n;i.default=o}),Su=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(xi()),t=yt(),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Ec 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 Ec(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=o;i.default=a}),xu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(xi()),t=As();function r(a){return a&&a.t?a:{default:a}}var s=class Ac extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Ac(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(p){d.pushBack(p)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new s(0,this)}end(){return new s(this.i,this)}rBegin(){return new s(this.i-1,this,1)}rEnd(){return new s(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new s(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},o=n;i.default=o}),Eu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.TreeNodeEnableIndex=i.TreeNode=void 0;var e=class{constructor(r,s){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=s}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let s=r.tt;for(;s.U===r;)r=s,s=r.tt;r=s}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let s=r.tt;for(;s.W===r;)r=s,s=r.tt;return r.W!==s?s:r}}te(){let r=this.tt,s=this.W,n=s.U;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.U=this,this.tt=s,this.W=n,n&&(n.tt=this),s}se(){let r=this.tt,s=this.U,n=s.W;return r.tt===this?r.tt=s:r.U===this?r.U=s:r.W=s,s.tt=r,s.W=this,this.tt=s,this.U=n,n&&(n.tt=this),s}};i.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};i.TreeNodeEnableIndex=t}),Is=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Eu(),t=yt(),r=bt(),s=class extends t.Container{constructor(o=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=o,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(d);if(g){let{parentNode:f,grandParent:y,curNode:b}=g;f.ie(),y.ie(),b.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)o=o.W;else if(c>0)l=o,o=o.U;else return o}return l}Z(o,a){let l=this.h;for(;o;)this.v(o.u,a)<=0?o=o.W:(l=o,o=o.U);return l}$(o,a){let l=this.h;for(;o;){let c=this.v(o.u,a);if(c<0)l=o,o=o.W;else if(c>0)o=o.U;else return o}return l}rr(o,a){let l=this.h;for(;o;)this.v(o.u,a)<0?(l=o,o=o.W):o=o.U;return l}ue(o){for(;;){let a=o.tt;if(a===this.h)return;if(o.ee===1){o.ee=0;return}if(o===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,o=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,o=a)}}}fe(o){if(this.i===1)return this.clear(),this.h;let a=o;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[o.u,a.u]=[a.u,o.u],[o.l,a.l]=[a.l,o.l],o=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(o,a){return o===void 0?!1:this.oe(o.U,a)||a(o)?!0:this.oe(o.W,a)}he(o){for(;;){let a=o.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.W){if(o.ee=0,o.U&&(o.U.tt=a),o.W&&(o.W.tt=l),a.W=o.U,l.U=o.W,o.U=a,o.W=l,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,o=l;continue}else if(o===a.U){if(o.ee=0,o.U&&(o.U.tt=l),o.W&&(o.W.tt=a),l.W=o.U,a.U=o.W,o.U=l,o.W=a,l===this.Y)this.Y=o,this.h.tt=o;else{let u=l.tt;u.U===l?u.U=o:u.W=o}return o.tt=l.tt,a.tt=o,l.tt=o,l.ee=1,{parentNode:a,grandParent:l,curNode:o}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(o,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(o,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,o);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(o,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,o);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(o,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let f=l.o;if(f!==this.h){let y=this.v(f.u,o);if(y===0){f.l=a;return}else if(y>0){let b=f.L(),w=this.v(b.u,o);if(w===0){b.l=a;return}else w<0&&(c=new this.re(o,a),b.W===void 0?(b.W=c,c.tt=b):(f.U=c,c.tt=f))}}}if(c===void 0)for(c=this.Y;;){let f=this.v(c.u,o);if(f>0){if(c.U===void 0){c.U=new this.re(o,a),c.U.tt=c,c=c.U;break}c=c.U}else if(f<0){if(c.W===void 0){c.W=new this.re(o,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(o,a){for(;o;){let l=this.v(o.u,a);if(l<0)o=o.W;else if(l>0)o=o.U;else return o}return o||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(o,a){let l=o.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return o===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(o){if(this.i===0)return!1;let a=this.I(this.Y,o);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(o){let a=o.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return o.iteratorType===0?l&&o.next():(!l||a.U===void 0)&&o.next(),this.V(a),o}forEach(o){let a=0;for(let l of this)o(l,a++,this)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===o){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let o=function(a){return a?Math.max(o(a.U),o(a.W))+1:0};return o(this.Y)}},n=s;i.default=n}),Ts=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=yt(),t=bt(),r=class extends e.ContainerIterator{constructor(n,o,a){super(a),this.o=n,this.h=o,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,o=this.h.tt;if(n===this.h)return o?o.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==o;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},s=r;i.default=s}),Au=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(Is()),t=s(Ts()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Ic 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 Ic(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),Iu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=s(Is()),t=s(Ts()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Tc 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 Tc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=o;i.default=a}),Cs=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),Ps=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=yt(),t=s(Cs()),r=bt();function s(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};i.HashContainerIterator=n;var o=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};i.HashContainer=o}),Tu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ps(),t=bt(),r=class Cc 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 Cc(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(o=[]){super();let a=this;o.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(o,a){return this.M(o,void 0,a)}getElementByPos(o){if(o<0||o>this.i-1)throw new RangeError;let a=this.p;for(;o--;)a=a.B;return a.u}find(o,a){let l=this.I(o,a);return new r(l,this.h,this)}forEach(o){let a=0,l=this.p;for(;l!==this.h;)o(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let o=this.p;for(;o!==this.h;)yield o.u,o=o.B}).bind(this)()}},n=s;i.default=n}),Cu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ps(),t=s(Cs()),r=bt();function s(l){return l&&l.t?l:{default:l}}var n=class Pc 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 Pc(this.o,this.h,this.container,this.iteratorType)}},o=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=o;i.default=a}),Pu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),Object.defineProperty(i,"Deque",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(i,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(i,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(i,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(i,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(i,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(i,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(i,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(i,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(i,"Vector",{enumerable:!0,get:function(){return s.default}});var e=d(vu()),t=d(wu()),r=d(ku()),s=d(_u()),n=d(Su()),o=d(xu()),a=d(Au()),l=d(Iu()),c=d(Tu()),u=d(Cu());function d(p){return p&&p.t?p:{default:p}}}),Ou=pe((i,e)=>{le(),ue(),ce();var t=Pu().OrderedSet,r=gt()("number-allocator:trace"),s=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 o(a,l){if(!(this instanceof o))return new o(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}o.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},o.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},o.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},o.prototype.free=function(a){if(a<this.min||a>this.max){s("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},o.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},o.prototype.intervalCount=function(){return this.ss.size()},o.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=o}),Os=pe((i,e)=>{le(),ue(),ce();var t=Ou();e.exports.NumberAllocator=t}),Mu=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=bu(),t=Os(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(s){s>0&&(this.aliasToTopic=new e.LRUCache({max:s}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,s),this.max=s,this.length=0)}put(s,n){if(n===0||n>this.max)return!1;let o=this.aliasToTopic.get(n);return o&&delete this.topicToAlias[o],this.aliasToTopic.set(n,s),this.topicToAlias[s]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(s){return this.aliasToTopic.get(s)}getAliasByTopic(s){let n=this.topicToAlias[s];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};i.default=r}),Lu=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(i,"__esModule",{value:!0});var t=Er(),r=e(Mu()),s=zt(),n=(o,a)=>{o.log("_handleConnack");let{options:l}=o,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(o.connackTimer),delete o.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){o.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(o.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)o.reconnecting=!1,o._onConnect(a);else if(c>0){let u=new s.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);o.emit("error",u),o.options.reconnectOnConnackError&&o._cleanUp(!0)}};i.default=n}),Ru=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(t,r,s)=>{t.log("handling pubrel packet");let n=typeof s<"u"?s:t.noop,{messageId:o}=r,a={cmd:"pubcomp",messageId:o};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};i.default=e}),Nu=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(mu()),r=e(yu()),s=e(Lu()),n=e(Er()),o=e(Ru()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,o.default)(l,c,u);break;case"connack":(0,s.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};i.default=a}),Ms=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};i.default=e}),ju=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}),Uu=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(i,"__esModule",{value:!0}),i.TypedEventEmitter=void 0;var t=e((Lt(),Ne(xt))),r=zt(),s=class{};i.TypedEventEmitter=s,(0,r.applyMixin)(s,t.default)}),Ar=pe((i,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Du=pe((i,e)=>{le(),ue(),ce();var t=Ar().default;function r(s,n){if(t(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(s)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Bu=pe((i,e)=>{le(),ue(),ce();var t=Ar().default,r=Du();function s(n){var o=r(n,"string");return t(o)=="symbol"?o:o+""}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Fu=pe((i,e)=>{le(),ue(),ce();var t=Bu();function r(s,n,o){return(n=t(n))in s?Object.defineProperty(s,n,{value:o,enumerable:!0,configurable:!0,writable:!0}):s[n]=o,s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),$u=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}),qu=pe((i,e)=>{le(),ue(),ce();function t(r,s){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var o,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,s===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(o=l.call(n)).done)&&(u.push(o.value),u.length!==s);d=!0);}catch(g){p=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Hu=pe((i,e)=>{le(),ue(),ce();function t(r,s){(s==null||s>r.length)&&(s=r.length);for(var n=0,o=Array(s);n<s;n++)o[n]=r[n];return o}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Wu=pe((i,e)=>{le(),ue(),ce();var t=Hu();function r(s,n){if(s){if(typeof s=="string")return t(s,n);var o={}.toString.call(s).slice(8,-1);return o==="Object"&&s.constructor&&(o=s.constructor.name),o==="Map"||o==="Set"?Array.from(s):o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(s,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),zu=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}),Vu=pe((i,e)=>{le(),ue(),ce();var t=$u(),r=qu(),s=Wu(),n=zu();function o(a,l){return t(a)||r(a,l)||s(a,l)||n()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),Ls=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(i,function(t){var r=function(g){return function(f){var y=g(f);return f.add(y),y}},s=function(g){return function(f,y){return g.set(f,y),y}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,a=o*2,l=function(g,f){return function(y){var b=f.get(y),w=b===void 0?y.size:b<a?b+1:0;if(!y.has(w))return g(y,w);if(y.size<o){for(;y.has(w);)w=Math.floor(Math.random()*a);return g(y,w)}if(y.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;y.has(w);)w=Math.floor(Math.random()*n);return g(y,w)}},c=new WeakMap,u=s(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),Gu=pe((i,e)=>{le(),ue(),ce();function t(s,n,o,a,l,c,u){try{var d=s[c](u),p=d.value}catch(g){return void o(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(s){return function(){var n=this,o=arguments;return new Promise(function(a,l){var c=s.apply(n,o);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Rs=pe((i,e)=>{le(),ue(),ce();function t(r,s){this.v=r,this.k=s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ns=pe((i,e)=>{le(),ue(),ce();function t(r,s,n,o){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(g,f){t(l,g,function(y){return this._invoke(g,f,y)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,s,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),js=pe((i,e)=>{le(),ue(),ce();var t=Ns();function r(){var s,n,o=typeof Symbol=="function"?Symbol:{},a=o.iterator||"@@iterator",l=o.toStringTag||"@@toStringTag";function c(w,m,k,S){var v=m&&m.prototype instanceof d?m:d,x=Object.create(v.prototype);return t(x,"_invoke",(function(E,I,P){var O,B,T,$=0,M=P||[],U=!1,oe={p:0,n:0,v:s,a:Y,f:Y.bind(s,4),d:function(W,ee){return O=W,B=0,T=s,oe.n=ee,u}};function Y(W,ee){for(B=W,T=ee,n=0;!U&&$&&!D&&n<M.length;n++){var D,X=M[n],L=oe.p,J=X[2];W>3?(D=J===ee)&&(T=X[(B=X[4])?5:(B=3,3)],X[4]=X[5]=s):X[0]<=L&&((D=W<2&&L<X[1])?(B=0,oe.v=ee,oe.n=X[1]):L<J&&(D=W<3||X[0]>ee||ee>J)&&(X[4]=W,X[5]=ee,oe.n=J,B=0))}if(D||W>1)return u;throw U=!0,ee}return function(W,ee,D){if($>1)throw TypeError("Generator is already running");for(U&&ee===1&&Y(ee,D),B=ee,T=D;(n=B<2?s:T)||!U;){O||(B?B<3?(B>1&&(oe.n=-1),Y(B,T)):oe.n=T:oe.v=T);try{if($=2,O){if(B||(W="next"),n=O[W]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,B<2&&(B=0)}else B===1&&(n=O.return)&&n.call(O),B<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),B=1);O=s}else if((n=(U=oe.n<0)?T:E.call(I,oe))!==u)break}catch(X){O=s,B=1,T=X}finally{$=1}}return{value:n,done:U}}})(w,k,S),!0),x}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),y=g.prototype=d.prototype=Object.create(f);function b(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(y),w}return p.prototype=g,t(y,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(y),t(y,l,"Generator"),t(y,a,function(){return this}),t(y,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:b}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Us=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=Ns();function s(n,o){function a(c,u,d,p){try{var g=n[c](u),f=g.value;return f instanceof t?o.resolve(f.v).then(function(y){a("next",y,d,p)},function(y){a("throw",y,d,p)}):o.resolve(f).then(function(y){g.value=y,d(g)},function(y){return a("throw",y,d,p)})}catch(y){p(y)}}var l;this.next||(r(s.prototype),r(s.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new o(function(g,f){a(c,d,g,f)})}return l=l?l.then(p,p):p()},!0)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Ds=pe((i,e)=>{le(),ue(),ce();var t=js(),r=Us();function s(n,o,a,l,c){return new r(t().w(n,o,a,l),c||Promise)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),Ku=pe((i,e)=>{le(),ue(),ce();var t=Ds();function r(s,n,o,a,l){var c=t(s,n,o,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Yu=pe((i,e)=>{le(),ue(),ce();function t(r){var s=Object(r),n=[];for(var o in s)n.unshift(o);return function a(){for(;n.length;)if((o=n.pop())in s)return a.value=o,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Ju=pe((i,e)=>{le(),ue(),ce();var t=Ar().default;function r(s){if(s!=null){var n=s[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],o=0;if(n)return n.call(s);if(typeof s.next=="function")return s;if(!isNaN(s.length))return{next:function(){return s&&o>=s.length&&(s=void 0),{value:s&&s[o++],done:!s}}}}throw new TypeError(t(s)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Qu=pe((i,e)=>{le(),ue(),ce();var t=Rs(),r=js(),s=Ku(),n=Ds(),o=Us(),a=Yu(),l=Ju();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(b){var w=typeof b=="function"&&b.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var f={throw:1,return:2,break:3,continue:3};function y(b){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(S,v){return m(k.a,f[S],v)},delegateYield:function(S,v,x){return w.resultName=v,m(k.d,l(S),x)},finish:function(S){return m(k.f,S)}},m=function(S,v,x){k.p=w.prev,k.n=w.next;try{return S(v,x)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return b.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(b,w,m,k){return u.w(y(b),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(b,w){return new t(b,w)},AsyncIterator:o,async:function(b,w,m,k,S){return(g(w)?n:s)(y(b),w,m,k,S)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),Xu=pe((i,e)=>{le(),ue(),ce();var t=Qu()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),Zu=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Fu(),Vu(),Ls(),Gu(),Xu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(i,function(t,r,s,n,o,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),S.push.apply(S,v)}return S}function d(m){for(var k=1;k<arguments.length;k++){var S=arguments[k]!=null?arguments[k]:{};k%2?u(Object(S),!0).forEach(function(v){r(m,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(S)):u(Object(S)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(S,v))})}return m}var p=function(m){return d(d({},m),{},{connect:function(k){var S=k.call;return o(a.mark(function v(){var x,E,I,P;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return x=new MessageChannel,E=x.port1,I=x.port2,O.next=1,S("connect",{port:E},[E]);case 1:return P=O.sent,c.set(I,P),O.abrupt("return",I);case 2:case"end":return O.stop()}},v)}))},disconnect:function(k){var S=k.call;return(function(){var v=o(a.mark(function x(E){var I;return a.wrap(function(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,S("disconnect",{portId:I});case 2:case"end":return P.stop()}},x)}));return function(x){return v.apply(this,arguments)}})()},isSupported:function(k){var S=k.call;return function(){return S("isSupported")}}})};function g(m,k){var S=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(x){return Object.getOwnPropertyDescriptor(m,x).enumerable})),S.push.apply(S,v)}return S}function f(m){for(var k=1;k<arguments.length;k++){var S=arguments[k]!=null?arguments[k]:{};k%2?g(Object(S),!0).forEach(function(v){r(m,v,S[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(S)):g(Object(S)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(S,v))})}return m}var y=new WeakMap,b=function(m){if(y.has(m))return y.get(m);var k=new Map;return y.set(m,k),k},w=function(m){var k=p(m);return function(S){var v=b(S);S.addEventListener("message",function(M){var U=M.data,oe=U.id;if(oe!==null&&v.has(oe)){var Y=v.get(oe),W=Y.reject,ee=Y.resolve;v.delete(oe),U.error===void 0?ee(U.result):W(new Error(U.error.message))}}),l(S)&&S.start();for(var x=function(M){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Y,W){var ee=n.generateUniqueNumber(v);v.set(ee,{reject:W,resolve:Y}),U===null?S.postMessage({id:ee,method:M},oe):S.postMessage({id:ee,method:M,params:U},oe)})},E=function(M,U){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];S.postMessage({id:null,method:M,params:U},oe)},I={},P=0,O=Object.entries(k);P<O.length;P++){var B=s(O[P],2),T=B[0],$=B[1];I=f(f({},I),{},r({},T,$({call:x,notify:E})))}return f({},I)}};t.createBroker=w})}),ed=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Ar(),Zu(),Ls()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(i,function(t,r,s,n){var o=new Map([[0,null]]),a=new Map([[0,null]]),l=s.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(o.get(p))==="symbol"&&(o.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){o.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(o);o.set(m,w);var k=function(){return d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"interval"}).then(function(){var S=o.get(m);if(S===void 0)throw new Error("The timer is in an undefined state.");S===w&&(p.apply(void 0,y),o.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,f=arguments.length,y=new Array(f>2?f-2:0),b=2;b<f;b++)y[b-2]=arguments[b];var w=Symbol(),m=n.generateUniqueNumber(a);return a.set(m,w),d("set",{delay:g,now:performance.timeOrigin+performance.now(),timerId:m,timerType:"timeout"}).then(function(){var k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),p.apply(void 0,y))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),td=pe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,ed()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(i,function(t,r){var s=function(d,p){var g=null;return function(){if(g!==null)return g;var f=new Blob([p],{type:"application/javascript; charset=utf-8"}),y=URL.createObjectURL(f);return g=d(y),setTimeout(function(){return URL.revokeObjectURL(y)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,o=s(r.load,n),a=function(d){return o().clearInterval(d)},l=function(d){return o().clearTimeout(d)},c=function(){var d;return(d=o()).setInterval.apply(d,arguments)},u=function(){var d;return(d=o()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),Ir=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.isReactNativeBrowser=i.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&je?.versions?!Object.prototype.hasOwnProperty.call(je.versions,"electron"):typeof window.document<"u":!1,t=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),r=()=>typeof navigator<"u"&&navigator.product==="ReactNative",s=e()||t()||r();i.isWebWorker=t(),i.isReactNativeBrowser=r(),i.default=s}),rd=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,g)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=i&&i.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=i&&i.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(p[p.length]=g);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),g=0;g<p.length;g++)p[g]!=="default"&&e(d,u,p[g]);return t(d,u),d}})();Object.defineProperty(i,"__esModule",{value:!0});var s=td(),n=r(Ir()),o={set:s.setInterval,clear:s.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return o;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?o:a}};i.default=l}),Bs=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(i,"__esModule",{value:!0});var t=e(rd()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(s,n){this.client=s,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(s.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(s){if(s*=1e3,isNaN(s)||s<=0||s>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${s}`);this._keepalive=s,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${s}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let s=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+s,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};i.default=r}),Ei=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(v,x,E,I){I===void 0&&(I=E);var P=Object.getOwnPropertyDescriptor(x,E);(!P||("get"in P?!x.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return x[E]}}),Object.defineProperty(v,I,P)}:function(v,x,E,I){I===void 0&&(I=E),v[I]=x[E]}),t=i&&i.__setModuleDefault||(Object.create?function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}:function(v,x){v.default=x}),r=i&&i.__importStar||(function(){var v=function(x){return v=Object.getOwnPropertyNames||function(E){var I=[];for(var P in E)Object.prototype.hasOwnProperty.call(E,P)&&(I[I.length]=P);return I},v(x)};return function(x){if(x&&x.__esModule)return x;var E={};if(x!=null)for(var I=v(x),P=0;P<I.length;P++)I[P]!=="default"&&e(E,x,I[P]);return t(E,x),E}})(),s=i&&i.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(i,"__esModule",{value:!0});var n=s(hu()),o=Nt(),a=s(pu()),l=s(gt()),c=r(xs()),u=s(Es()),d=s(Nu()),p=s(Ms()),g=s(ju()),f=zt(),y=Uu(),b=s(Bs()),w=r(Ir()),m=globalThis.setImmediate||((...v)=>{let x=v.shift();(0,f.nextTick)(()=>{x(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},S=class Do extends y.TypedEventEmitter{static VERSION=f.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(x,E){super(),this.options=E||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Do.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:Do.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=E.protocolVersion===5&&E.customHandleAcks?E.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=x,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=E.outgoingStore||new u.default,this.incomingStore=E.incomingStore||new u.default,this.queueQoSZero=E.queueQoSZero===void 0?!0:E.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,E.properties&&E.properties.topicAliasMaximum>0&&(E.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(E.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,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,$=>{O.cb&&O.cb($),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(x,E){E()}handleMessage(x,E){E()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let x=new o.Writable,E=n.default.parser(this.options),I=null,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",M=>{this.log("parser :: on packet push to packets array."),P.push(M)});let O=()=>{this.log("work :: getting next packet in queue");let M=P.shift();if(M)this.log("work :: packet pulled from queue"),(0,d.default)(this,M,B);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},B=()=>{if(P.length)(0,f.nextTick)(O);else{let M=I;I=null,M()}};x._write=(M,U,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(M),O()};let T=M=>{this.log("streamErrorHandler :: error",M.message),M.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",M)):this.noop(M)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(x),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let $={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&($.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&($.properties||($.properties={}),this.topicAliasRecv&&($.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket($),E.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let M={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(M)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(x,E,I,P){this.log("publish :: message `%s` to topic `%s`",E,x);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:$,properties:M,cbStorePut:U}=I;if(this._checkDisconnecting(P))return this;let oe=()=>{let Y=0;if((B===1||B===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:x,payload:E,qos:B,retain:T,messageId:Y,dup:$};switch(O.protocolVersion===5&&(W.properties=M),this.log("publish :: qos",B),B){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:P||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,P,U);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!oe())&&this._storeProcessingQueue.push({invoke:oe,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(x,E,I){return new Promise((P,O)=>{this.publish(x,E,I,(B,T)=>{B?O(B):P(T)})})}subscribe(x,E,I){let P=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let O=!1,B=[];typeof x=="string"?(x=[x],B=x):Array.isArray(x)?B=x:typeof x=="object"&&(O=x.resubscribe,delete x.resubscribe,B=Object.keys(x));let T=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 $={qos:0};P===5&&($.nl=!1,$.rap=!1,$.rh=0),E={...$,...E};let{properties:M}=E,U=[],oe=(ee,D)=>{if(D=D||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,ee)||this._resubscribeTopics[ee].qos<D.qos||O){let X={topic:ee,qos:D.qos};P===5&&(X.nl=D.nl,X.rap=D.rap,X.rh=D.rh,X.properties=M),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",X.topic,X.qos),U.push(X)}};if(Array.isArray(x)?x.forEach(ee=>{this.log("subscribe: array topic %s",ee),oe(ee)}):Object.keys(x).forEach(ee=>{this.log("subscribe: object topic %s, %o",ee,x[ee]),oe(ee,x[ee])}),!U.length)return I(null,[]),this;let Y=(ee,D)=>{let X={cmd:"subscribe",subscriptions:ee,messageId:D};if(M&&(X.properties=M),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];ee.forEach(ge=>{if(this.options.reconnectPeriod>0){let re={qos:ge.qos};P===5&&(re.nl=ge.nl||!1,re.rap=ge.rap||!1,re.rh=ge.rh||0,re.properties=ge.properties),this._resubscribeTopics[ge.topic]=re,J.push(ge.topic)}}),this.messageIdToTopic[X.messageId]=J}let L=new Promise((J,ge)=>{this.outgoing[X.messageId]={volatile:!0,cb(re,we){if(!re){let{granted:G}=we;for(let j=0;j<G.length;j+=1)ee[j].qos=G[j]}re?ge(new f.ErrorWithSubackPacket(re.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(X),L},W=()=>{let ee=this.options.subscribeBatchSize??U.length,D=[];for(let X=0;X<U.length;X+=ee){let L=U.slice(X,X+ee),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;D.push(Y(L,J))}return Promise.all(D).then(X=>{I(null,U,X.at(-1))}).catch(X=>{I(X,U,X.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:I}),this}subscribeAsync(x,E){return new Promise((I,P)=>{this.subscribe(x,E,(O,B)=>{O?P(O):I(B)})})}unsubscribe(x,E,I){typeof x=="string"&&(x=[x]),typeof E=="function"&&(I=E),I=I||this.noop;let P=c.validateTopics(x);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 x=="string"?T.unsubscriptions=[x]:Array.isArray(x)&&(T.unsubscriptions=x),this.options.resubscribe&&T.unsubscriptions.forEach($=>{delete this._resubscribeTopics[$]}),typeof E=="object"&&E.properties&&(T.properties=E.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(x,E){return new Promise((I,P)=>{this.unsubscribe(x,E,(O,B)=>{O?P(O):I(B)})})}end(x,E,I){this.log("end :: (%s)",this.options.clientId),(x==null||typeof x!="boolean")&&(I=I||E,E=x,x=!1),typeof E!="object"&&(I=I||E,E=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let 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 $=B||T;this.log("end :: closeStores: invoking callback with args"),I($)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},O=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,x),this._cleanUp(x,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,f.nextTick)(P)},E)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!x&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(x,E){return new Promise((I,P)=>{this.end(x,E,O=>{O?P(O):I()})})}removeOutgoingMessage(x){if(this.outgoing[x]){let{cb:E}=this.outgoing[x];this._removeOutgoingAndStoreMessage(x,()=>{E(new Error("Message removed"))})}return this}reconnect(x){this.log("client reconnect");let E=()=>{x?(this.options.incomingStore=x.incomingStore,this.options.outgoingStore=x.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=E:E(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(x=>{this.outgoing[x].volatile&&typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(x=>{typeof this.outgoing[x].cb=="function"&&(this.outgoing[x].cb(new Error("Connection closed")),delete this.outgoing[x])}))}_removeTopicAliasAndRecoverTopicName(x){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",E,I),I.length===0){if(typeof E>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(E),typeof I>"u")return new Error("Unregistered Topic Alias");x.topic=I}E&&delete x.properties.topicAlias}_checkDisconnecting(x){return this.disconnecting&&(x&&x!==this.noop?x(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(x,E,I={}){if(E&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",E)),this.log("_cleanUp :: forced? %s",x),x)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let 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(x,E,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",x.cmd);let P=x,O;if(P.cmd==="publish"&&(P=(0,a.default)(x),O=this._removeTopicAliasAndRecoverTopicName(P),O))return E&&E(O);this.outgoingStore.put(P,B=>{if(B)return E&&E(B);I(),this._writePacket(x,E)})}_applyTopicAlias(x){if(this.options.protocolVersion===5&&x.cmd==="publish"){let E;x.properties&&(E=x.properties.topicAlias);let I=x.topic.toString();if(this.topicAliasSend)if(E){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,E),!this.topicAliasSend.put(I,E)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(E=this.topicAliasSend.getAliasByTopic(I),E?(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,E)):(E=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,E),x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,E))):this.options.autoUseTopicAlias&&(E=this.topicAliasSend.getAliasByTopic(I),E&&(x.topic="",x.properties={...x.properties,topicAlias:E},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,E))));else if(E)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,E),new Error("Sending Topic Alias out of range")}}_noop(x){this.log("noop ::",x)}_writePacket(x,E){this.log("_writePacket :: packet: %O",x),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",x),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(x,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&E&&E!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",E)):E&&(this.log("_writePacket :: invoking cb"),E())}_sendPacket(x,E,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,E=E||this.noop;let O=this._applyTopicAlias(x);if(O){E(O);return}if(!this.connected){if(x.cmd==="auth"){this._writePacket(x,E);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(x,E,I);return}if(P){this._writePacket(x,E);return}switch(x.cmd){case"publish":break;case"pubrel":this._storeAndSend(x,E,I);return;default:this._writePacket(x,E);return}switch(x.qos){case 2:case 1:this._storeAndSend(x,E,I);break;default:this._writePacket(x,E);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(x,E,I){this.log("_storePacket :: packet: %o",x),this.log("_storePacket :: cb? %s",!!E),I=I||this.noop;let P=x;if(P.cmd==="publish"){P=(0,a.default)(x);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 b.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(x=!1){this.keepaliveManager&&this.options.keepalive&&(x||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let x=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&x.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let E=0;E<x.length;E++){let I={};I[x[E]]=this._resubscribeTopics[x[E]],I.resubscribe=!0,this.subscribe(I,{properties:I[x[E]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(x){if(this.disconnected){this.emit("connect",x);return}this.connackPacket=x,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let E=()=>{let I=this.outgoingStore.createStream(),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),$;if(!T){I.once("readable",B);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){B();return}!this.disconnecting&&!this.reconnectTimer?($=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(M,U){$&&$(M,U),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 $ in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[$]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",x)):E()}),B()};E()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let x=this._storeProcessingQueue[0];if(x&&x.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let x of this._storeProcessingQueue)x.cbStorePut&&x.cbStorePut(new Error("Connection closed")),x.callback&&x.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(x,E){delete this.outgoing[x],this.outgoingStore.del({messageId:x},(I,P)=>{E(I,P),this.messageIdProvider.deallocate(x),this._invokeStoreProcessingQueue()})}};i.default=S}),nd=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Os(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};i.default=t});function id(){if(Ai)return Tr;Ai=!0;let i=2147483647,e=36,t=1,r=26,s=38,n=700,o=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,f=Math.floor,y=String.fromCharCode;function b(O){throw new RangeError(p[O])}function w(O,B){let T=[],$=O.length;for(;$--;)T[$]=B(O[$]);return T}function m(O,B){let T=O.split("@"),$="";T.length>1&&($=T[0]+"@",O=T[1]),O=O.replace(d,".");let M=O.split("."),U=w(M,B).join(".");return $+U}function k(O){let B=[],T=0,$=O.length;for(;T<$;){let M=O.charCodeAt(T++);if(M>=55296&&M<=56319&&T<$){let U=O.charCodeAt(T++);(U&64512)==56320?B.push(((M&1023)<<10)+(U&1023)+65536):(B.push(M),T--)}else B.push(M)}return B}let S=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},x=function(O,B){return O+22+75*(O<26)-((B!=0)<<5)},E=function(O,B,T){let $=0;for(O=T?f(O/n):O>>1,O+=f(O/B);O>g*r>>1;$+=e)O=f(O/g);return f($+(g+1)*O/(O+s))},I=function(O){let B=[],T=O.length,$=0,M=a,U=o,oe=O.lastIndexOf(l);oe<0&&(oe=0);for(let Y=0;Y<oe;++Y)O.charCodeAt(Y)>=128&&b("not-basic"),B.push(O.charCodeAt(Y));for(let Y=oe>0?oe+1:0;Y<T;){let W=$;for(let D=1,X=e;;X+=e){Y>=T&&b("invalid-input");let L=v(O.charCodeAt(Y++));L>=e&&b("invalid-input"),L>f((i-$)/D)&&b("overflow"),$+=L*D;let J=X<=U?t:X>=U+r?r:X-U;if(L<J)break;let ge=e-J;D>f(i/ge)&&b("overflow"),D*=ge}let ee=B.length+1;U=E($-W,ee,W==0),f($/ee)>i-M&&b("overflow"),M+=f($/ee),$%=ee,B.splice($++,0,M)}return String.fromCodePoint(...B)},P=function(O){let B=[];O=k(O);let T=O.length,$=a,M=0,U=o;for(let W of O)W<128&&B.push(y(W));let oe=B.length,Y=oe;for(oe&&B.push(l);Y<T;){let W=i;for(let D of O)D>=$&&D<W&&(W=D);let ee=Y+1;W-$>f((i-M)/ee)&&b("overflow"),M+=(W-$)*ee,$=W;for(let D of O)if(D<$&&++M>i&&b("overflow"),D===$){let X=M;for(let L=e;;L+=e){let J=L<=U?t:L>=U+r?r:L-U;if(X<J)break;let ge=X-J,re=e-J;B.push(y(x(J+ge%re,0))),X=f(ge/re)}B.push(y(x(X,0))),U=E(M,ee,Y===oe),M=0,++Y}++M,++$}return B.join("")};return Tr={version:"2.3.1",ucs2:{decode:k,encode:S},decode:I,encode:P,toASCII:function(O){return m(O,function(B){return u.test(B)?"xn--"+P(B):B})},toUnicode:function(O){return m(O,function(B){return c.test(B)?I(B.slice(4).toLowerCase()):B})}},Tr}var Tr,Ai,At,od=Je(()=>{le(),ue(),ce(),Tr={},Ai=!1,At=id(),At.decode,At.encode,At.toASCII,At.toUnicode,At.ucs2,At.version});function sd(){return Pi||(Pi=!0,Ci=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var i={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;i[e]=r;for(e in i)return!1;if(typeof Object.keys=="function"&&Object.keys(i).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(i).length!==0)return!1;var s=Object.getOwnPropertySymbols(i);if(s.length!==1||s[0]!==e||!Object.prototype.propertyIsEnumerable.call(i,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(i,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Ci}function ad(){return Mi||(Mi=!0,Oi=Error),Oi}function ld(){return Ri||(Ri=!0,Li=EvalError),Li}function cd(){return ji||(ji=!0,Ni=RangeError),Ni}function ud(){return Di||(Di=!0,Ui=ReferenceError),Ui}function Fs(){return Fi||(Fi=!0,Bi=SyntaxError),Bi}function sr(){return qi||(qi=!0,$i=TypeError),$i}function dd(){return Wi||(Wi=!0,Hi=URIError),Hi}function hd(){if(zi)return Cr;zi=!0;var i=typeof Symbol<"u"&&Symbol,e=sd();return Cr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Cr}function fd(){if(Vi)return Pr;Vi=!0;var i={__proto__:null,foo:{}},e=Object;return Pr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Pr}function pd(){if(Gi)return Or;Gi=!0;var i="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",s=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},o=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Or=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(i+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var b=l.apply(this,s(c,arguments));return Object(b)===b?b:this}return l.apply(a,s(c,arguments))},p=t(0,l.length-c.length),g=[],f=0;f<p;f++)g[f]="$"+f;if(u=Function("binder","return function ("+o(g,",")+"){ return binder.apply(this,arguments); }")(d),l.prototype){var y=function(){};y.prototype=l.prototype,u.prototype=new y,y.prototype=null}return u},Or}function Ii(){if(Ki)return Mr;Ki=!0;var i=pd();return Mr=Function.prototype.bind||i,Mr}function md(){if(Yi)return Lr;Yi=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Ii();return Lr=t.call(i,e),Lr}function Vt(){if(Ji)return Rr;Ji=!0;var i,e=ad(),t=ld(),r=cd(),s=ud(),n=Fs(),o=sr(),a=dd(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new o},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=hd()(),f=fd()(),y=Object.getPrototypeOf||(f?function(Y){return Y.__proto__}:null),b={},w=typeof Uint8Array>"u"||!y?i:y(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?i:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?i:ArrayBuffer,"%ArrayIteratorPrototype%":g&&y?y([][Symbol.iterator]()):i,"%AsyncFromSyncIteratorPrototype%":i,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?i:Atomics,"%BigInt%":typeof BigInt>"u"?i:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?i:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?i:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?i:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?i:Float32Array,"%Float64Array%":typeof Float64Array>"u"?i:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?i:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?i:Int8Array,"%Int16Array%":typeof Int16Array>"u"?i:Int16Array,"%Int32Array%":typeof Int32Array>"u"?i:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&y?y(y([][Symbol.iterator]())):i,"%JSON%":typeof JSON=="object"?JSON:i,"%Map%":typeof Map>"u"?i:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!y?i:y(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?i:Promise,"%Proxy%":typeof Proxy>"u"?i:Proxy,"%RangeError%":r,"%ReferenceError%":s,"%Reflect%":typeof Reflect>"u"?i:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?i:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!y?i:y(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?i:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&y?y(""[Symbol.iterator]()):i,"%Symbol%":g?Symbol:i,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?i:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?i:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?i:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?i:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?i:WeakMap,"%WeakRef%":typeof WeakRef>"u"?i:WeakRef,"%WeakSet%":typeof WeakSet>"u"?i:WeakSet};if(y)try{null.error}catch(Y){var k=y(y(Y));m["%Error.prototype%"]=k}var S=function Y(W){var ee;if(W==="%AsyncFunction%")ee=c("async function () {}");else if(W==="%GeneratorFunction%")ee=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")ee=c("async function* () {}");else if(W==="%AsyncGenerator%"){var D=Y("%AsyncGeneratorFunction%");D&&(ee=D.prototype)}else if(W==="%AsyncIteratorPrototype%"){var X=Y("%AsyncGenerator%");X&&y&&(ee=y(X.prototype))}return m[W]=ee,ee},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},x=Ii(),E=md(),I=x.call(Function.call,Array.prototype.concat),P=x.call(Function.apply,Array.prototype.splice),O=x.call(Function.call,String.prototype.replace),B=x.call(Function.call,String.prototype.slice),T=x.call(Function.call,RegExp.prototype.exec),$=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,M=/\\(\\)?/g,U=function(Y){var W=B(Y,0,1),ee=B(Y,-1);if(W==="%"&&ee!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(ee==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var D=[];return O(Y,$,function(X,L,J,ge){D[D.length]=J?O(ge,M,"$1"):L||X}),D},oe=function(Y,W){var ee=Y,D;if(E(v,ee)&&(D=v[ee],ee="%"+D[0]+"%"),E(m,ee)){var X=m[ee];if(X===b&&(X=S(ee)),typeof X>"u"&&!W)throw new o("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:D,name:ee,value:X}}throw new n("intrinsic "+Y+" does not exist!")};return Rr=function(Y,W){if(typeof Y!="string"||Y.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof W!="boolean")throw new o('"allowMissing" argument must be a boolean');if(T(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ee=U(Y),D=ee.length>0?ee[0]:"",X=oe("%"+D+"%",W),L=X.name,J=X.value,ge=!1,re=X.alias;re&&(D=re[0],P(ee,I([0,1],re)));for(var we=1,G=!0;we<ee.length;we+=1){var j=ee[we],ne=B(j,0,1),z=B(j,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!G)&&(ge=!0),D+="."+j,L="%"+D+"%",E(m,L))J=m[L];else if(J!=null){if(!(j in J)){if(!W)throw new o("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=ee.length){var K=u(J,j);G=!!K,G&&"get"in K&&!("originalValue"in K.get)?J=K.get:J=J[j]}else G=E(J,j),J=J[j];G&&!ge&&(m[L]=J)}}return J},Rr}function Ti(){if(Qi)return Nr;Qi=!0;var i=Vt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Nr=e,Nr}function $s(){if(Xi)return jr;Xi=!0;var i=Vt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return jr=e,jr}function gd(){if(Zi)return Ur;Zi=!0;var i=Ti(),e=Fs(),t=sr(),r=$s();return Ur=function(s,n,o){if(!s||typeof s!="object"&&typeof s!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(s,n);if(i)i(s,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:o,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)s[n]=o;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Ur}function yd(){if(eo)return Dr;eo=!0;var i=Ti(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},Dr=e,Dr}function bd(){if(to)return Br;to=!0;var i=Vt(),e=gd(),t=yd()(),r=$s(),s=sr(),n=i("%Math.floor%");return Br=function(o,a){if(typeof o!="function")throw new s("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new s("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in o&&r){var d=r(o,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(o,"length",a,!0,!0):e(o,"length",a)),o},Br}function vd(){if(ro)return Gt;ro=!0;var i=Ii(),e=Vt(),t=bd(),r=sr(),s=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||i.call(n,s),a=Ti(),l=e("%Math.max%");Gt=function(u){if(typeof u!="function")throw new r("a function is required");var d=o(i,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return o(i,s,arguments)};return a?a(Gt,"apply",{value:c}):Gt.apply=c,Gt}function wd(){if(no)return Fr;no=!0;var i=Vt(),e=vd(),t=e(i("String.prototype.indexOf"));return Fr=function(r,s){var n=i(r,!!s);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Fr}var Ci,Pi,Oi,Mi,Li,Ri,Ni,ji,Ui,Di,Bi,Fi,$i,qi,Hi,Wi,Cr,zi,Pr,Vi,Or,Gi,Mr,Ki,Lr,Yi,Rr,Ji,Nr,Qi,jr,Xi,Ur,Zi,Dr,eo,Br,to,Gt,ro,Fr,no,kd=Je(()=>{le(),ue(),ce(),Ci={},Pi=!1,Oi={},Mi=!1,Li={},Ri=!1,Ni={},ji=!1,Ui={},Di=!1,Bi={},Fi=!1,$i={},qi=!1,Hi={},Wi=!1,Cr={},zi=!1,Pr={},Vi=!1,Or={},Gi=!1,Mr={},Ki=!1,Lr={},Yi=!1,Rr={},Ji=!1,Nr={},Qi=!1,jr={},Xi=!1,Ur={},Zi=!1,Dr={},eo=!1,Br={},to=!1,Gt={},ro=!1,Fr={},no=!1});function io(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function _d(){!jt||!Ut||(jt=!1,Ut.length?it=Ut.concat(it):ar=-1,it.length&&qs())}function qs(){if(!jt){var i=setTimeout(_d,0);jt=!0;for(var e=it.length;e;){for(Ut=it,it=[];++ar<e;)Ut&&Ut[ar].run();ar=-1,e=it.length}Ut=null,jt=!1,clearTimeout(i)}}function Sd(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];it.push(new Hs(i,e)),it.length===1&&!jt&&setTimeout(qs,0)}function Hs(i,e){this.fun=i,this.array=e}function We(){}function xd(i){io("_linkedBinding")}function Ed(i){io("dlopen")}function Ad(){return[]}function Id(){return[]}function Td(i,e){if(!i)throw new Error(e||"assertion error")}function Cd(){return!1}function Pd(){return vt.now()/1e3}function oo(i){var e=Math.floor((Date.now()-vt.now())*.001),t=vt.now()*.001,r=Math.floor(t)+e,s=Math.floor(t%1*1e9);return i&&(r=r-i[0],s=s-i[1],s<0&&(r--,s+=qr)),[r,s]}function It(){return ao}function Od(i){return[]}var it,jt,Ut,ar,Ws,zs,Vs,Gs,Ks,Ys,Js,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,$r,da,ha,fa,pa,ma,ga,ya,ba,va,wa,ka,_a,Sa,xa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,Ma,La,Ra,Na,vt,so,qr,ja,Ua,Da,Ba,Fa,$a,qa,Ha,Wa,za,Va,ao,Ga=Je(()=>{le(),ue(),ce(),it=[],jt=!1,ar=-1,Hs.prototype.run=function(){this.fun.apply(null,this.array)},Ws="browser",zs="x64",Vs="browser",Gs={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Ks=["/usr/bin/node"],Ys=[],Js="v16.8.0",Qs={},Xs=function(i,e){console.warn((e?e+": ":"")+i)},Zs=function(i){io("binding")},ea=function(i){return 0},ta=function(){return"/"},ra=function(i){},na={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},ia=We,oa=[],sa={},aa=!1,la={},ca=We,ua=We,$r=function(){return{}},da=$r,ha=$r,fa=We,pa=We,ma=We,ga={},ya={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ba=We,va=We,wa=We,ka=We,_a=We,Sa=We,xa=We,Ea=void 0,Aa=void 0,Ia=void 0,Ta=We,Ca=2,Pa=1,Oa="/bin/usr/node",Ma=9229,La="node",Ra=[],Na=We,vt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},vt.now===void 0&&(so=Date.now(),vt.timing&&vt.timing.navigationStart&&(so=vt.timing.navigationStart),vt.now=()=>Date.now()-so),qr=1e9,oo.bigint=function(i){var e=oo(i);return typeof BigInt>"u"?e[0]*qr+e[1]:BigInt(e[0]*qr)+BigInt(e[1])},ja=10,Ua={},Da=0,Ba=It,Fa=It,$a=It,qa=It,Ha=It,Wa=We,za=It,Va=It,ao={version:Js,versions:Qs,arch:zs,platform:Vs,release:na,_rawDebug:ia,moduleLoadList:oa,binding:Zs,_linkedBinding:xd,_events:Ua,_eventsCount:Da,_maxListeners:ja,on:It,addListener:Ba,once:Fa,off:$a,removeListener:qa,removeAllListeners:Ha,emit:Wa,prependListener:za,prependOnceListener:Va,listeners:Od,domain:sa,_exiting:aa,config:la,dlopen:Ed,uptime:Pd,_getActiveRequests:Ad,_getActiveHandles:Id,reallyExit:ca,_kill:ua,cpuUsage:$r,resourceUsage:da,memoryUsage:ha,kill:fa,exit:pa,openStdin:ma,allowedNodeEnvironmentFlags:ga,assert:Td,features:ya,_fatalExceptions:ba,setUncaughtExceptionCaptureCallback:va,hasUncaughtExceptionCaptureCallback:Cd,emitWarning:Xs,nextTick:Sd,_tickCallback:wa,_debugProcess:ka,_debugEnd:_a,_startProfilerIdleNotifier:Sa,_stopProfilerIdleNotifier:xa,stdout:Ea,stdin:Ia,stderr:Aa,abort:Ta,umask:ea,chdir:ra,cwd:ta,env:Gs,title:Ws,argv:Ks,execArgv:Ys,pid:Ca,ppid:Pa,execPath:Oa,debugPort:Ma,hrtime:oo,argv0:La,_preload_modules:Ra,setSourceMapsEnabled:Na}});function Md(){if(lo)return Hr;lo=!0;var i=ao;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,o){for(var a="",l=0,c=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}o&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,o){var a=o.dir||o.root,l=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+l:a+n+l:l}var s={resolve:function(){for(var n="",o=!1,a,l=arguments.length-1;l>=-1&&!o;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=i.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,o=c.charCodeAt(0)===47)}return n=t(n,!o),o?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var o=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!o),n.length===0&&!o&&(n="."),n.length>0&&a&&(n+="/"),o?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,o=0;o<arguments.length;++o){var a=arguments[o];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":s.normalize(n)},relative:function(n,o){if(e(n),e(o),n===o||(n=s.resolve(n),o=s.resolve(o),n===o))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<o.length&&o.charCodeAt(u)===47;++u);for(var d=o.length,p=d-u,g=c<p?c:p,f=-1,y=0;y<=g;++y){if(y===g){if(p>g){if(o.charCodeAt(u+y)===47)return o.slice(u+y+1);if(y===0)return o.slice(u+y)}else c>g&&(n.charCodeAt(a+y)===47?f=y:y===0&&(f=0));break}var b=n.charCodeAt(a+y),w=o.charCodeAt(u+y);if(b!==w)break;b===47&&(f=y)}var m="";for(y=a+f+1;y<=l;++y)(y===l||n.charCodeAt(y)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+o.slice(u+f):(u+=f,o.charCodeAt(u)===47&&++u,o.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var o=n.charCodeAt(0),a=o===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(o=n.charCodeAt(u),o===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,o){if(o!==void 0&&typeof o!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(o!==void 0&&o.length>0&&o.length<=n.length){if(o.length===n.length&&o===n)return"";var d=o.length-1,p=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(g===o.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var o=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===46?o===-1?o=d:u!==1&&(u=1):o!==-1&&(u=-1)}return o===-1||l===-1||u===0||u===1&&o===l-1&&o===a+1?"":n.slice(o,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var o={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return o;var a=n.charCodeAt(0),l=a===47,c;l?(o.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,f=n.length-1,y=0;f>=c;--f){if(a=n.charCodeAt(f),a===47){if(!g){d=f+1;break}continue}p===-1&&(g=!1,p=f+1),a===46?u===-1?u=f:y!==1&&(y=1):u!==-1&&(y=-1)}return u===-1||p===-1||y===0||y===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?o.base=o.name=n.slice(1,p):o.base=o.name=n.slice(d,p)):(d===0&&l?(o.name=n.slice(1,u),o.base=n.slice(1,p)):(o.name=n.slice(d,u),o.base=n.slice(d,p)),o.ext=n.slice(u,p)),d>0?o.dir=n.slice(0,d-1):l&&(o.dir="/"),o},sep:"/",delimiter:":",win32:null,posix:null};return s.posix=s,Hr=s,Hr}var Hr,lo,co,Ld=Je(()=>{le(),ue(),ce(),Ga(),Hr={},lo=!1,co=Md()}),Ka={};$t(Ka,{URL:()=>ol,Url:()=>el,default:()=>ze,fileURLToPath:()=>Ja,format:()=>tl,parse:()=>il,pathToFileURL:()=>Qa,resolve:()=>rl,resolveObject:()=>nl});function Rd(){if(ho)return Wr;ho=!0;var i=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=i&&e&&typeof e.get=="function"?e.get:null,r=i&&Map.prototype.forEach,s=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=s&&n&&typeof n.get=="function"?n.get:null,a=s&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,f=Boolean.prototype.valueOf,y=Object.prototype.toString,b=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,S=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,E=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,B=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,M=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===M||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(V){return V.__proto__}:null);function W(V,ie){if(V===1/0||V===-1/0||V!==V||V&&V>-1e3&&V<1e3||x.call(/e/,ie))return ie;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof V=="number"){var Te=V<0?-O(-V):O(V);if(Te!==V){var Pe=String(Te),Le=m.call(ie,Pe.length+1);return k.call(Pe,Ie,"$&_")+"."+k.call(k.call(Le,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ie,"$&_")}var ee=Xa,D=ee.custom,X=K(D)?D:null;Wr=function V(ie,Ie,Te,Pe){var Le=Ie||{};if(se(Le,"quoteStyle")&&Le.quoteStyle!=="single"&&Le.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Le,"maxStringLength")&&(typeof Le.maxStringLength=="number"?Le.maxStringLength<0&&Le.maxStringLength!==1/0:Le.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var ot=se(Le,"customInspect")?Le.customInspect:!0;if(typeof ot!="boolean"&&ot!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Le,"indent")&&Le.indent!==null&&Le.indent!==" "&&!(parseInt(Le.indent,10)===Le.indent&&Le.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Le,"numericSeparator")&&typeof Le.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var st=Le.numericSeparator;if(typeof ie>"u")return"undefined";if(ie===null)return"null";if(typeof ie=="boolean")return ie?"true":"false";if(typeof ie=="string")return ae(ie,Le);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ge=String(ie);return st?W(ie,Ge):Ge}if(typeof ie=="bigint"){var at=String(ie)+"n";return st?W(ie,at):at}var Xt=typeof Le.depth>"u"?5:Le.depth;if(typeof Te>"u"&&(Te=0),Te>=Xt&&Xt>0&&typeof ie=="object")return ge(ie)?"[Array]":"[Object]";var lt=Z(Le,Te);if(typeof Pe>"u")Pe=[];else if(te(Pe,ie)>=0)return"[Circular]";function Ze(ct,Pt,Ft){if(Pt&&(Pe=P.call(Pe),Pe.push(Pt)),Ft){var ut={depth:Le.depth};return se(Le,"quoteStyle")&&(ut.quoteStyle=Le.quoteStyle),V(ct,ut,Te+1,Pe)}return V(ct,Le,Te+1,Pe)}if(typeof ie=="function"&&!we(ie)){var on=q(ie),Zt=_e(ie,Ze);return"[Function"+(on?": "+on:" (anonymous)")+"]"+(Zt.length>0?" { "+I.call(Zt,", ")+" }":"")}if(K(ie)){var hr=M?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):$.call(ie);return typeof ie=="object"&&!M?h(hr):hr}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),N=ie.attributes||[],ke=0;ke<N.length;ke++)C+=" "+N[ke].name+"="+L(J(N[ke].value),"double",Le);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(ge(ie)){if(ie.length===0)return"[]";var xe=_e(ie,Ze);return lt&&!F(xe)?"["+de(xe,lt)+"]":"[ "+I.call(xe,", ")+" ]"}if(G(ie)){var Ae=_e(ie,Ze);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+Ze(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&&ot){if(X&&typeof ie[X]=="function"&&ee)return ee(ie,{depth:Xt-Te});if(ot!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(ct,Pt){Fe.push(Ze(Pt,ie,!0)+" => "+Ze(ct,ie))}),A("Map",t.call(ie),Fe,lt)}if(H(ie)){var Ye=[];return a&&a.call(ie,function(ct){Ye.push(Ze(ct,ie))}),A("Set",o.call(ie),Ye,lt)}if(fe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(be(ie))return _("WeakRef");if(ne(ie))return h(Ze(Number(ie)));if(Q(ie))return h(Ze(B.call(ie)));if(z(ie))return h(f.call(ie));if(j(ie))return h(Ze(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof zr<"u"&&ie===zr)return"{ [object globalThis] }";if(!re(ie)&&!we(ie)){var rt=_e(ie,Ze),fr=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,pr=ie instanceof Object?"":"null prototype",mr=!fr&&U&&Object(ie)===ie&&U in ie?m.call(R(ie),8,-1):pr?"Object":"",sn=fr||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Bt=sn+(mr||pr?"["+I.call(E.call([],mr||[],pr||[]),": ")+"] ":"");return rt.length===0?Bt+"{}":lt?Bt+"{"+de(rt,lt)+"}":Bt+"{ "+I.call(rt,", ")+" }"}return String(ie)};function L(V,ie,Ie){var Te=(Ie.quoteStyle||ie)==="double"?'"':"'";return Te+V+Te}function J(V){return k.call(String(V),/"/g,""")}function ge(V){return R(V)==="[object Array]"&&(!U||!(typeof V=="object"&&U in V))}function re(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 j(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 K(V){if(M)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 Q(V){if(!V||typeof V!="object"||!B)return!1;try{return B.call(V),!0}catch{}return!1}var ye=Object.prototype.hasOwnProperty||function(V){return V in(this||zr)};function se(V,ie){return ye.call(V,ie)}function R(V){return y.call(V)}function q(V){if(V.name)return V.name;var ie=w.call(b.call(V),/^function\s*([\w$]+)/);return ie?ie[1]:null}function te(V,ie){if(V.indexOf)return V.indexOf(ie);for(var Ie=0,Te=V.length;Ie<Te;Ie++)if(V[Ie]===ie)return Ie;return-1}function he(V){if(!t||!V||typeof V!="object")return!1;try{t.call(V);try{o.call(V)}catch{return!0}return V instanceof Map}catch{}return!1}function fe(V){if(!c||!V||typeof V!="object")return!1;try{c.call(V,c);try{d.call(V,d)}catch{return!0}return V instanceof WeakMap}catch{}return!1}function be(V){if(!g||!V||typeof V!="object")return!1;try{return g.call(V),!0}catch{}return!1}function H(V){if(!o||!V||typeof V!="object")return!1;try{o.call(V);try{t.call(V)}catch{return!0}return V instanceof Set}catch{}return!1}function me(V){if(!d||!V||typeof V!="object")return!1;try{d.call(V,d);try{c.call(V,c)}catch{return!0}return V instanceof WeakSet}catch{}return!1}function ve(V){return!V||typeof V!="object"?!1:typeof HTMLElement<"u"&&V instanceof HTMLElement?!0:typeof V.nodeName=="string"&&typeof V.getAttribute=="function"}function ae(V,ie){if(V.length>ie.maxStringLength){var Ie=V.length-ie.maxStringLength,Te="... "+Ie+" more character"+(Ie>1?"s":"");return ae(m.call(V,0,ie.maxStringLength),ie)+Te}var Pe=k.call(k.call(V,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Oe);return L(Pe,"single",ie)}function Oe(V){var ie=V.charCodeAt(0),Ie={8:"b",9:"t",10:"n",12:"f",13:"r"}[ie];return Ie?"\\"+Ie:"\\x"+(ie<16?"0":"")+S.call(ie.toString(16))}function h(V){return"Object("+V+")"}function _(V){return V+" { ? }"}function A(V,ie,Ie,Te){var Pe=Te?de(Ie,Te):I.call(Ie,", ");return V+" ("+ie+") {"+Pe+"}"}function F(V){for(var ie=0;ie<V.length;ie++)if(te(V[ie],`
|
|
1
|
+
var AikaaraChat=(function(Me){"use strict";class Vo{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 hn{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 Vo(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 kr{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 Fc=1e3,qc=10,Hc=400,Wc=600,Ko="#6366f1",zc=12,Vc="system-ui, -apple-system, sans-serif",Go="Type a message...",Kc="bottom-right",Gc="light",Yc={x:20,y:20},pn="aikaara_conversation_id";class Yo extends kr{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 hn(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??qc;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Fc)*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 hn(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 Jo{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 Qo{_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=Xo(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=Xo(t,r);if(o){const n=_r(o),s=_r(r);!n&&s&&Object.assign(o,r,{id:o.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function Xo(i,e,t=15e3){const r=e.attachments&&e.attachments[0],o=(e.metadata??{}).attributes;if(!(!!r||!!(o&&o.fileMessage)))return null;const s=_r(e),a=Zo(e),l=es(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],h=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!h||!!(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=_r(d);if(s&&y&&s===y)return d;const w=Zo(d);if(a&&w&&a===w)return d;const m=es(d);if(l&&m&&l===m)return d}return null}function Zo(i){const e=i.attachments&&i.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=ts(i);if(t)return t}function es(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 _r(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=ts(i);if(r){const o=/[?&]cloudFileId=([^&]+)/.exec(r);if(o)return decodeURIComponent(o[1])}}function ts(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 rs{_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(pn)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(pn)}catch{return null}}saveToStorage(e){try{localStorage.setItem(pn,e)}catch{}}}var fn=Object.defineProperty,Jc=Object.getOwnPropertyDescriptor,Qc=Object.getOwnPropertyNames,Xc=Object.prototype.hasOwnProperty,Qe=(i,e)=>()=>(i&&(e=i(i=0)),e),fe=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Ht=(i,e)=>{for(var t in e)fn(i,t,{get:e[t],enumerable:!0})},Zc=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qc(e))!Xc.call(i,o)&&o!==t&&fn(i,o,{get:()=>e[o],enumerable:!(r=Jc(e,o))||r.enumerable});return i},je=i=>Zc(fn({},"__esModule",{value:!0}),i),le=Qe(()=>{}),De={};Ht(De,{_debugEnd:()=>Yn,_debugProcess:()=>Gn,_events:()=>di,_eventsCount:()=>hi,_exiting:()=>Nn,_fatalExceptions:()=>zn,_getActiveHandles:()=>cs,_getActiveRequests:()=>ls,_kill:()=>Dn,_linkedBinding:()=>ss,_maxListeners:()=>ui,_preload_modules:()=>ai,_rawDebug:()=>On,_startProfilerIdleNotifier:()=>Jn,_stopProfilerIdleNotifier:()=>Qn,_tickCallback:()=>Kn,abort:()=>ti,addListener:()=>pi,allowedNodeEnvironmentFlags:()=>Hn,arch:()=>bn,argv:()=>wn,argv0:()=>si,assert:()=>us,binding:()=>En,browser:()=>Pn,chdir:()=>Tn,config:()=>Rn,cpuUsage:()=>ir,cwd:()=>In,debugPort:()=>oi,default:()=>ki,dlopen:()=>as,domain:()=>Mn,emit:()=>yi,emitWarning:()=>Sn,env:()=>vn,execArgv:()=>kn,execPath:()=>ii,exit:()=>Fn,features:()=>Wn,hasUncaughtExceptionCaptureCallback:()=>ds,hrtime:()=>xr,kill:()=>Bn,listeners:()=>ps,memoryUsage:()=>Un,moduleLoadList:()=>Ln,nextTick:()=>is,off:()=>mi,on:()=>pt,once:()=>fi,openStdin:()=>qn,pid:()=>ri,platform:()=>yn,ppid:()=>ni,prependListener:()=>vi,prependOnceListener:()=>wi,reallyExit:()=>jn,release:()=>Cn,removeAllListeners:()=>bi,removeListener:()=>gi,resourceUsage:()=>$n,setSourceMapsEnabled:()=>li,setUncaughtExceptionCaptureCallback:()=>Vn,stderr:()=>Zn,stdin:()=>ei,stdout:()=>Xn,title:()=>gn,umask:()=>An,uptime:()=>hs,version:()=>_n,versions:()=>xn});function mn(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function eu(){!Mt||!Nt||(Mt=!1,Nt.length?ot=Nt.concat(ot):nr=-1,ot.length&&ns())}function ns(){if(!Mt){var i=setTimeout(eu,0);Mt=!0;for(var e=ot.length;e;){for(Nt=ot,ot=[];++nr<e;)Nt&&Nt[nr].run();nr=-1,e=ot.length}Nt=null,Mt=!1,clearTimeout(i)}}function is(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];ot.push(new os(i,e)),ot.length===1&&!Mt&&setTimeout(ns,0)}function os(i,e){this.fun=i,this.array=e}function We(){}function ss(i){mn("_linkedBinding")}function as(i){mn("dlopen")}function ls(){return[]}function cs(){return[]}function us(i,e){if(!i)throw new Error(e||"assertion error")}function ds(){return!1}function hs(){return ft.now()/1e3}function xr(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+=Sr)),[r,o]}function pt(){return ki}function ps(i){return[]}var ot,Mt,Nt,nr,gn,bn,yn,vn,wn,kn,_n,xn,Sn,En,An,In,Tn,Cn,Pn,On,Ln,Mn,Nn,Rn,jn,Dn,ir,$n,Un,Bn,Fn,qn,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,li,ft,ci,Sr,ui,di,hi,pi,fi,mi,gi,bi,yi,vi,wi,ki,tu=Qe(()=>{le(),ue(),ce(),ot=[],Mt=!1,nr=-1,os.prototype.run=function(){this.fun.apply(null,this.array)},gn="browser",bn="x64",yn="browser",vn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},wn=["/usr/bin/node"],kn=[],_n="v16.8.0",xn={},Sn=function(i,e){console.warn((e?e+": ":"")+i)},En=function(i){mn("binding")},An=function(i){return 0},In=function(){return"/"},Tn=function(i){},Cn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Pn=!0,On=We,Ln=[],Mn={},Nn=!1,Rn={},jn=We,Dn=We,ir=function(){return{}},$n=ir,Un=ir,Bn=We,Fn=We,qn=We,Hn={},Wn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},zn=We,Vn=We,Kn=We,Gn=We,Yn=We,Jn=We,Qn=We,Xn=void 0,Zn=void 0,ei=void 0,ti=We,ri=2,ni=1,ii="/bin/usr/node",oi=9229,si="node",ai=[],li=We,ft={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},ft.now===void 0&&(ci=Date.now(),ft.timing&&ft.timing.navigationStart&&(ci=ft.timing.navigationStart),ft.now=()=>Date.now()-ci),Sr=1e9,xr.bigint=function(i){var e=xr(i);return typeof BigInt>"u"?e[0]*Sr+e[1]:BigInt(e[0]*Sr)+BigInt(e[1])},ui=10,di={},hi=0,pi=pt,fi=pt,mi=pt,gi=pt,bi=pt,yi=We,vi=pt,wi=pt,ki={version:_n,versions:xn,arch:bn,platform:yn,browser:Pn,release:Cn,_rawDebug:On,moduleLoadList:Ln,binding:En,_linkedBinding:ss,_events:di,_eventsCount:hi,_maxListeners:ui,on:pt,addListener:pi,once:fi,off:mi,removeListener:gi,removeAllListeners:bi,emit:yi,prependListener:vi,prependOnceListener:wi,listeners:ps,domain:Mn,_exiting:Nn,config:Rn,dlopen:as,uptime:hs,_getActiveRequests:ls,_getActiveHandles:cs,reallyExit:jn,_kill:Dn,cpuUsage:ir,resourceUsage:$n,memoryUsage:Un,kill:Bn,exit:Fn,openStdin:qn,allowedNodeEnvironmentFlags:Hn,assert:us,features:Wn,_fatalExceptions:zn,setUncaughtExceptionCaptureCallback:Vn,hasUncaughtExceptionCaptureCallback:ds,emitWarning:Sn,nextTick:is,_tickCallback:Kn,_debugProcess:Gn,_debugEnd:Yn,_startProfilerIdleNotifier:Jn,_stopProfilerIdleNotifier:Qn,stdout:Xn,stdin:ei,stderr:Zn,abort:ti,umask:An,chdir:Tn,cwd:In,env:vn,title:gn,argv:wn,execArgv:kn,pid:ri,ppid:ni,execPath:ii,debugPort:oi,hrtime:xr,argv0:si,_preload_modules:ai,setSourceMapsEnabled:li}}),ce=Qe(()=>{tu()});function ru(){if(_i)return Wt;_i=!0,Wt.byteLength=a,Wt.toByteArray=c,Wt.fromByteArray=h;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 p=g.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=p);var y=b===p?0:4-b%4;return[b,y]}function a(g){var p=s(g),b=p[0],y=p[1];return(b+y)*3/4-y}function l(g,p,b){return(p+b)*3/4-b}function c(g){var p,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,x=w>0?y-4:y,v;for(v=0;v<x;v+=4)p=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=p>>16&255,m[k++]=p>>8&255,m[k++]=p&255;return w===2&&(p=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=p&255),w===1&&(p=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=p>>8&255,m[k++]=p&255),m}function u(g){return i[g>>18&63]+i[g>>12&63]+i[g>>6&63]+i[g&63]}function d(g,p,b){for(var y,w=[],m=p;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 h(g){for(var p,b=g.length,y=b%3,w=[],m=16383,k=0,x=b-y;k<x;k+=m)w.push(d(g,k,k+m>x?x:k+m));return y===1?(p=g[b-1],w.push(i[p>>2]+i[p<<4&63]+"==")):y===2&&(p=(g[b-2]<<8)+g[b-1],w.push(i[p>>10]+i[p>>4&63]+i[p<<2&63]+"=")),w.join("")}return Wt}function nu(){return xi?or:(xi=!0,or.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,h=t?-1:1,g=i[e+d];for(d+=h,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+i[e+d],d+=h,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+i[e+d],d+=h,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)},or.write=function(i,e,t,r,o,n){var s,a,l,c=n*8-o-1,u=(1<<c)-1,d=u>>1,h=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,p=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+=h/l:e+=h*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+=p,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;i[t+g]=s&255,g+=p,s/=256,c-=8);i[t+g-p]|=b*128},or)}function iu(){if(Si)return Et;Si=!0;let i=ru(),e=nu(),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 f=new Uint8Array(1),_={foo:function(){return 42}};return Object.setPrototypeOf(_,Uint8Array.prototype),Object.setPrototypeOf(f,_),f.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(f){if(f>r)throw new RangeError('The value "'+f+'" is invalid for option "size"');let _=new Uint8Array(f);return Object.setPrototypeOf(_,s.prototype),_}function s(f,_,A){if(typeof f=="number"){if(typeof _=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(f)}return a(f,_,A)}s.poolSize=8192;function a(f,_,A){if(typeof f=="string")return d(f,_);if(ArrayBuffer.isView(f))return g(f);if(f==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f);if(H(f,ArrayBuffer)||f&&H(f.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(H(f,SharedArrayBuffer)||f&&H(f.buffer,SharedArrayBuffer)))return p(f,_,A);if(typeof f=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let B=f.valueOf&&f.valueOf();if(B!=null&&B!==f)return s.from(B,_,A);let Z=b(f);if(Z)return Z;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof f[Symbol.toPrimitive]=="function")return s.from(f[Symbol.toPrimitive]("string"),_,A);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof f)}s.from=function(f,_,A){return a(f,_,A)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array);function l(f){if(typeof f!="number")throw new TypeError('"size" argument must be of type number');if(f<0)throw new RangeError('The value "'+f+'" is invalid for option "size"')}function c(f,_,A){return l(f),f<=0?n(f):_!==void 0?typeof A=="string"?n(f).fill(_,A):n(f).fill(_):n(f)}s.alloc=function(f,_,A){return c(f,_,A)};function u(f){return l(f),n(f<0?0:y(f)|0)}s.allocUnsafe=function(f){return u(f)},s.allocUnsafeSlow=function(f){return u(f)};function d(f,_){if((typeof _!="string"||_==="")&&(_="utf8"),!s.isEncoding(_))throw new TypeError("Unknown encoding: "+_);let A=m(f,_)|0,B=n(A),Z=B.write(f,_);return Z!==A&&(B=B.slice(0,Z)),B}function h(f){let _=f.length<0?0:y(f.length)|0,A=n(_);for(let B=0;B<_;B+=1)A[B]=f[B]&255;return A}function g(f){if(H(f,Uint8Array)){let _=new Uint8Array(f);return p(_.buffer,_.byteOffset,_.byteLength)}return h(f)}function p(f,_,A){if(_<0||f.byteLength<_)throw new RangeError('"offset" is outside of buffer bounds');if(f.byteLength<_+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return _===void 0&&A===void 0?B=new Uint8Array(f):A===void 0?B=new Uint8Array(f,_):B=new Uint8Array(f,_,A),Object.setPrototypeOf(B,s.prototype),B}function b(f){if(s.isBuffer(f)){let _=y(f.length)|0,A=n(_);return A.length===0||f.copy(A,0,0,_),A}if(f.length!==void 0)return typeof f.length!="number"||me(f.length)?n(0):h(f);if(f.type==="Buffer"&&Array.isArray(f.data))return h(f.data)}function y(f){if(f>=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return f|0}function w(f){return+f!=f&&(f=0),s.alloc(+f)}s.isBuffer=function(f){return f!=null&&f._isBuffer===!0&&f!==s.prototype},s.compare=function(f,_){if(H(f,Uint8Array)&&(f=s.from(f,f.offset,f.byteLength)),H(_,Uint8Array)&&(_=s.from(_,_.offset,_.byteLength)),!s.isBuffer(f)||!s.isBuffer(_))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===_)return 0;let A=f.length,B=_.length;for(let Z=0,de=Math.min(A,B);Z<de;++Z)if(f[Z]!==_[Z]){A=f[Z],B=_[Z];break}return A<B?-1:B<A?1:0},s.isEncoding=function(f){switch(String(f).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(f,_){if(!Array.isArray(f))throw new TypeError('"list" argument must be an Array of Buffers');if(f.length===0)return s.alloc(0);let A;if(_===void 0)for(_=0,A=0;A<f.length;++A)_+=f[A].length;let B=s.allocUnsafe(_),Z=0;for(A=0;A<f.length;++A){let de=f[A];if(H(de,Uint8Array))Z+de.length>B.length?(s.isBuffer(de)||(de=s.from(de)),de.copy(B,Z)):Uint8Array.prototype.set.call(B,de,Z);else if(s.isBuffer(de))de.copy(B,Z);else throw new TypeError('"list" argument must be an Array of Buffers');Z+=de.length}return B};function m(f,_){if(s.isBuffer(f))return f.length;if(ArrayBuffer.isView(f)||H(f,ArrayBuffer))return f.byteLength;if(typeof f!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof f);let A=f.length,B=arguments.length>2&&arguments[2]===!0;if(!B&&A===0)return 0;let Z=!1;for(;;)switch(_){case"ascii":case"latin1":case"binary":return A;case"utf8":case"utf-8":return q(f).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A*2;case"hex":return A>>>1;case"base64":return pe(f).length;default:if(Z)return B?-1:q(f).length;_=(""+_).toLowerCase(),Z=!0}}s.byteLength=m;function k(f,_,A){let B=!1;if((_===void 0||_<0)&&(_=0),_>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,_>>>=0,A<=_))return"";for(f||(f="utf8");;)switch(f){case"hex":return W(this,_,A);case"utf8":case"utf-8":return F(this,_,A);case"ascii":return oe(this,_,A);case"latin1":case"binary":return Y(this,_,A);case"base64":return T(this,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,_,A);default:if(B)throw new TypeError("Unknown encoding: "+f);f=(f+"").toLowerCase(),B=!0}}s.prototype._isBuffer=!0;function x(f,_,A){let B=f[_];f[_]=f[A],f[A]=B}s.prototype.swap16=function(){let f=this.length;if(f%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let _=0;_<f;_+=2)x(this,_,_+1);return this},s.prototype.swap32=function(){let f=this.length;if(f%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let _=0;_<f;_+=4)x(this,_,_+3),x(this,_+1,_+2);return this},s.prototype.swap64=function(){let f=this.length;if(f%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let _=0;_<f;_+=8)x(this,_,_+7),x(this,_+1,_+6),x(this,_+2,_+5),x(this,_+3,_+4);return this},s.prototype.toString=function(){let f=this.length;return f===0?"":arguments.length===0?F(this,0,f):k.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(f){if(!s.isBuffer(f))throw new TypeError("Argument must be a Buffer");return this===f?!0:s.compare(this,f)===0},s.prototype.inspect=function(){let f="",_=Et.INSPECT_MAX_BYTES;return f=this.toString("hex",0,_).replace(/(.{2})/g,"$1 ").trim(),this.length>_&&(f+=" ... "),"<Buffer "+f+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(f,_,A,B,Z){if(H(f,Uint8Array)&&(f=s.from(f,f.offset,f.byteLength)),!s.isBuffer(f))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof f);if(_===void 0&&(_=0),A===void 0&&(A=f?f.length:0),B===void 0&&(B=0),Z===void 0&&(Z=this.length),_<0||A>f.length||B<0||Z>this.length)throw new RangeError("out of range index");if(B>=Z&&_>=A)return 0;if(B>=Z)return-1;if(_>=A)return 1;if(_>>>=0,A>>>=0,B>>>=0,Z>>>=0,this===f)return 0;let de=Z-B,_e=A-_,V=Math.min(de,_e),ie=this.slice(B,Z),Ie=f.slice(_,A);for(let Te=0;Te<V;++Te)if(ie[Te]!==Ie[Te]){de=ie[Te],_e=Ie[Te];break}return de<_e?-1:_e<de?1:0};function v(f,_,A,B,Z){if(f.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=Z?0:f.length-1),A<0&&(A=f.length+A),A>=f.length){if(Z)return-1;A=f.length-1}else if(A<0)if(Z)A=0;else return-1;if(typeof _=="string"&&(_=s.from(_,B)),s.isBuffer(_))return _.length===0?-1:S(f,_,A,B,Z);if(typeof _=="number")return _=_&255,typeof Uint8Array.prototype.indexOf=="function"?Z?Uint8Array.prototype.indexOf.call(f,_,A):Uint8Array.prototype.lastIndexOf.call(f,_,A):S(f,[_],A,B,Z);throw new TypeError("val must be string, number or Buffer")}function S(f,_,A,B,Z){let de=1,_e=f.length,V=_.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(f.length<2||_.length<2)return-1;de=2,_e/=2,V/=2,A/=2}function ie(Te,Oe){return de===1?Te[Oe]:Te.readUInt16BE(Oe*de)}let Ie;if(Z){let Te=-1;for(Ie=A;Ie<_e;Ie++)if(ie(f,Ie)===ie(_,Te===-1?0:Ie-Te)){if(Te===-1&&(Te=Ie),Ie-Te+1===V)return Te*de}else Te!==-1&&(Ie-=Ie-Te),Te=-1}else for(A+V>_e&&(A=_e-V),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Oe=0;Oe<V;Oe++)if(ie(f,Ie+Oe)!==ie(_,Oe)){Te=!1;break}if(Te)return Ie}return-1}s.prototype.includes=function(f,_,A){return this.indexOf(f,_,A)!==-1},s.prototype.indexOf=function(f,_,A){return v(this,f,_,A,!0)},s.prototype.lastIndexOf=function(f,_,A){return v(this,f,_,A,!1)};function E(f,_,A,B){A=Number(A)||0;let Z=f.length-A;B?(B=Number(B),B>Z&&(B=Z)):B=Z;let de=_.length;B>de/2&&(B=de/2);let _e;for(_e=0;_e<B;++_e){let V=parseInt(_.substr(_e*2,2),16);if(me(V))return _e;f[A+_e]=V}return _e}function I(f,_,A,B){return ye(q(_,f.length-A),f,A,B)}function P(f,_,A,B){return ye(te(_),f,A,B)}function O(f,_,A,B){return ye(pe(_),f,A,B)}function U(f,_,A,B){return ye(he(_,f.length-A),f,A,B)}s.prototype.write=function(f,_,A,B){if(_===void 0)B="utf8",A=this.length,_=0;else if(A===void 0&&typeof _=="string")B=_,A=this.length,_=0;else if(isFinite(_))_=_>>>0,isFinite(A)?(A=A>>>0,B===void 0&&(B="utf8")):(B=A,A=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Z=this.length-_;if((A===void 0||A>Z)&&(A=Z),f.length>0&&(A<0||_<0)||_>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,f,_,A);case"utf8":case"utf-8":return I(this,f,_,A);case"ascii":case"latin1":case"binary":return P(this,f,_,A);case"base64":return O(this,f,_,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,f,_,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(f,_,A){return _===0&&A===f.length?i.fromByteArray(f):i.fromByteArray(f.slice(_,A))}function F(f,_,A){A=Math.min(f.length,A);let B=[],Z=_;for(;Z<A;){let de=f[Z],_e=null,V=de>239?4:de>223?3:de>191?2:1;if(Z+V<=A){let ie,Ie,Te,Oe;switch(V){case 1:de<128&&(_e=de);break;case 2:ie=f[Z+1],(ie&192)===128&&(Oe=(de&31)<<6|ie&63,Oe>127&&(_e=Oe));break;case 3:ie=f[Z+1],Ie=f[Z+2],(ie&192)===128&&(Ie&192)===128&&(Oe=(de&15)<<12|(ie&63)<<6|Ie&63,Oe>2047&&(Oe<55296||Oe>57343)&&(_e=Oe));break;case 4:ie=f[Z+1],Ie=f[Z+2],Te=f[Z+3],(ie&192)===128&&(Ie&192)===128&&(Te&192)===128&&(Oe=(de&15)<<18|(ie&63)<<12|(Ie&63)<<6|Te&63,Oe>65535&&Oe<1114112&&(_e=Oe))}}_e===null?(_e=65533,V=1):_e>65535&&(_e-=65536,B.push(_e>>>10&1023|55296),_e=56320|_e&1023),B.push(_e),Z+=V}return D(B)}let L=4096;function D(f){let _=f.length;if(_<=L)return String.fromCharCode.apply(String,f);let A="",B=0;for(;B<_;)A+=String.fromCharCode.apply(String,f.slice(B,B+=L));return A}function oe(f,_,A){let B="";A=Math.min(f.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(f[Z]&127);return B}function Y(f,_,A){let B="";A=Math.min(f.length,A);for(let Z=_;Z<A;++Z)B+=String.fromCharCode(f[Z]);return B}function W(f,_,A){let B=f.length;(!_||_<0)&&(_=0),(!A||A<0||A>B)&&(A=B);let Z="";for(let de=_;de<A;++de)Z+=ve[f[de]];return Z}function ee(f,_,A){let B=f.slice(_,A),Z="";for(let de=0;de<B.length-1;de+=2)Z+=String.fromCharCode(B[de]+B[de+1]*256);return Z}s.prototype.slice=function(f,_){let A=this.length;f=~~f,_=_===void 0?A:~~_,f<0?(f+=A,f<0&&(f=0)):f>A&&(f=A),_<0?(_+=A,_<0&&(_=0)):_>A&&(_=A),_<f&&(_=f);let B=this.subarray(f,_);return Object.setPrototypeOf(B,s.prototype),B};function $(f,_,A){if(f%1!==0||f<0)throw new RangeError("offset is not uint");if(f+_>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(f,_,A){f=f>>>0,_=_>>>0,A||$(f,_,this.length);let B=this[f],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[f+de]*Z;return B},s.prototype.readUintBE=s.prototype.readUIntBE=function(f,_,A){f=f>>>0,_=_>>>0,A||$(f,_,this.length);let B=this[f+--_],Z=1;for(;_>0&&(Z*=256);)B+=this[f+--_]*Z;return B},s.prototype.readUint8=s.prototype.readUInt8=function(f,_){return f=f>>>0,_||$(f,1,this.length),this[f]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(f,_){return f=f>>>0,_||$(f,2,this.length),this[f]|this[f+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(f,_){return f=f>>>0,_||$(f,2,this.length),this[f]<<8|this[f+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(f,_){return f=f>>>0,_||$(f,4,this.length),(this[f]|this[f+1]<<8|this[f+2]<<16)+this[f+3]*16777216},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(f,_){return f=f>>>0,_||$(f,4,this.length),this[f]*16777216+(this[f+1]<<16|this[f+2]<<8|this[f+3])},s.prototype.readBigUInt64LE=ae(function(f){f=f>>>0,Q(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=_+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,Z=this[++f]+this[++f]*2**8+this[++f]*2**16+A*2**24;return BigInt(B)+(BigInt(Z)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(f){f=f>>>0,Q(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=_*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],Z=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(Z)}),s.prototype.readIntLE=function(f,_,A){f=f>>>0,_=_>>>0,A||$(f,_,this.length);let B=this[f],Z=1,de=0;for(;++de<_&&(Z*=256);)B+=this[f+de]*Z;return Z*=128,B>=Z&&(B-=Math.pow(2,8*_)),B},s.prototype.readIntBE=function(f,_,A){f=f>>>0,_=_>>>0,A||$(f,_,this.length);let B=_,Z=1,de=this[f+--B];for(;B>0&&(Z*=256);)de+=this[f+--B]*Z;return Z*=128,de>=Z&&(de-=Math.pow(2,8*_)),de},s.prototype.readInt8=function(f,_){return f=f>>>0,_||$(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},s.prototype.readInt16LE=function(f,_){f=f>>>0,_||$(f,2,this.length);let A=this[f]|this[f+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(f,_){f=f>>>0,_||$(f,2,this.length);let A=this[f+1]|this[f]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(f,_){return f=f>>>0,_||$(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},s.prototype.readInt32BE=function(f,_){return f=f>>>0,_||$(f,4,this.length),this[f]<<24|this[f+1]<<16|this[f+2]<<8|this[f+3]},s.prototype.readBigInt64LE=ae(function(f){f=f>>>0,Q(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=this[f+4]+this[f+5]*2**8+this[f+6]*2**16+(A<<24);return(BigInt(B)<<BigInt(32))+BigInt(_+this[++f]*256+this[++f]*65536+this[++f]*16777216)}),s.prototype.readBigInt64BE=ae(function(f){f=f>>>0,Q(f,"offset");let _=this[f],A=this[f+7];(_===void 0||A===void 0)&&be(f,this.length-8);let B=(_<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(B)<<BigInt(32))+BigInt(this[++f]*16777216+this[++f]*65536+this[++f]*256+A)}),s.prototype.readFloatLE=function(f,_){return f=f>>>0,_||$(f,4,this.length),e.read(this,f,!0,23,4)},s.prototype.readFloatBE=function(f,_){return f=f>>>0,_||$(f,4,this.length),e.read(this,f,!1,23,4)},s.prototype.readDoubleLE=function(f,_){return f=f>>>0,_||$(f,8,this.length),e.read(this,f,!0,52,8)},s.prototype.readDoubleBE=function(f,_){return f=f>>>0,_||$(f,8,this.length),e.read(this,f,!1,52,8)};function X(f,_,A,B,Z,de){if(!s.isBuffer(f))throw new TypeError('"buffer" argument must be a Buffer instance');if(_>Z||_<de)throw new RangeError('"value" argument is out of bounds');if(A+B>f.length)throw new RangeError("Index out of range")}s.prototype.writeUintLE=s.prototype.writeUIntLE=function(f,_,A,B){if(f=+f,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;X(this,f,_,A,_e,0)}let Z=1,de=0;for(this[_]=f&255;++de<A&&(Z*=256);)this[_+de]=f/Z&255;return _+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(f,_,A,B){if(f=+f,_=_>>>0,A=A>>>0,!B){let _e=Math.pow(2,8*A)-1;X(this,f,_,A,_e,0)}let Z=A-1,de=1;for(this[_+Z]=f&255;--Z>=0&&(de*=256);)this[_+Z]=f/de&255;return _+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,1,255,0),this[_]=f&255,_+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,2,65535,0),this[_]=f&255,this[_+1]=f>>>8,_+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,2,65535,0),this[_]=f>>>8,this[_+1]=f&255,_+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,4,4294967295,0),this[_+3]=f>>>24,this[_+2]=f>>>16,this[_+1]=f>>>8,this[_]=f&255,_+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,4,4294967295,0),this[_]=f>>>24,this[_+1]=f>>>16,this[_+2]=f>>>8,this[_+3]=f&255,_+4};function M(f,_,A,B,Z){G(_,B,Z,f,A,7);let de=Number(_&BigInt(4294967295));f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return f[A++]=_e,_e=_e>>8,f[A++]=_e,_e=_e>>8,f[A++]=_e,_e=_e>>8,f[A++]=_e,A}function J(f,_,A,B,Z){G(_,B,Z,f,A,7);let de=Number(_&BigInt(4294967295));f[A+7]=de,de=de>>8,f[A+6]=de,de=de>>8,f[A+5]=de,de=de>>8,f[A+4]=de;let _e=Number(_>>BigInt(32)&BigInt(4294967295));return f[A+3]=_e,_e=_e>>8,f[A+2]=_e,_e=_e>>8,f[A+1]=_e,_e=_e>>8,f[A]=_e,A+8}s.prototype.writeBigUInt64LE=ae(function(f,_=0){return M(this,f,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(f,_=0){return J(this,f,_,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(f,_,A,B){if(f=+f,_=_>>>0,!B){let V=Math.pow(2,8*A-1);X(this,f,_,A,V-1,-V)}let Z=0,de=1,_e=0;for(this[_]=f&255;++Z<A&&(de*=256);)f<0&&_e===0&&this[_+Z-1]!==0&&(_e=1),this[_+Z]=(f/de>>0)-_e&255;return _+A},s.prototype.writeIntBE=function(f,_,A,B){if(f=+f,_=_>>>0,!B){let V=Math.pow(2,8*A-1);X(this,f,_,A,V-1,-V)}let Z=A-1,de=1,_e=0;for(this[_+Z]=f&255;--Z>=0&&(de*=256);)f<0&&_e===0&&this[_+Z+1]!==0&&(_e=1),this[_+Z]=(f/de>>0)-_e&255;return _+A},s.prototype.writeInt8=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,1,127,-128),f<0&&(f=255+f+1),this[_]=f&255,_+1},s.prototype.writeInt16LE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,2,32767,-32768),this[_]=f&255,this[_+1]=f>>>8,_+2},s.prototype.writeInt16BE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,2,32767,-32768),this[_]=f>>>8,this[_+1]=f&255,_+2},s.prototype.writeInt32LE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,4,2147483647,-2147483648),this[_]=f&255,this[_+1]=f>>>8,this[_+2]=f>>>16,this[_+3]=f>>>24,_+4},s.prototype.writeInt32BE=function(f,_,A){return f=+f,_=_>>>0,A||X(this,f,_,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[_]=f>>>24,this[_+1]=f>>>16,this[_+2]=f>>>8,this[_+3]=f&255,_+4},s.prototype.writeBigInt64LE=ae(function(f,_=0){return M(this,f,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(f,_=0){return J(this,f,_,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ge(f,_,A,B,Z,de){if(A+B>f.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function re(f,_,A,B,Z){return _=+_,A=A>>>0,Z||ge(f,_,A,4),e.write(f,_,A,B,23,4),A+4}s.prototype.writeFloatLE=function(f,_,A){return re(this,f,_,!0,A)},s.prototype.writeFloatBE=function(f,_,A){return re(this,f,_,!1,A)};function we(f,_,A,B,Z){return _=+_,A=A>>>0,Z||ge(f,_,A,8),e.write(f,_,A,B,52,8),A+8}s.prototype.writeDoubleLE=function(f,_,A){return we(this,f,_,!0,A)},s.prototype.writeDoubleBE=function(f,_,A){return we(this,f,_,!1,A)},s.prototype.copy=function(f,_,A,B){if(!s.isBuffer(f))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),_>=f.length&&(_=f.length),_||(_=0),B>0&&B<A&&(B=A),B===A||f.length===0||this.length===0)return 0;if(_<0)throw new RangeError("targetStart out of bounds");if(A<0||A>=this.length)throw new RangeError("Index out of range");if(B<0)throw new RangeError("sourceEnd out of bounds");B>this.length&&(B=this.length),f.length-_<B-A&&(B=f.length-_+A);let Z=B-A;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(_,A,B):Uint8Array.prototype.set.call(f,this.subarray(A,B),_),Z},s.prototype.fill=function(f,_,A,B){if(typeof f=="string"){if(typeof _=="string"?(B=_,_=0,A=this.length):typeof A=="string"&&(B=A,A=this.length),B!==void 0&&typeof B!="string")throw new TypeError("encoding must be a string");if(typeof B=="string"&&!s.isEncoding(B))throw new TypeError("Unknown encoding: "+B);if(f.length===1){let de=f.charCodeAt(0);(B==="utf8"&&de<128||B==="latin1")&&(f=de)}}else typeof f=="number"?f=f&255:typeof f=="boolean"&&(f=Number(f));if(_<0||this.length<_||this.length<A)throw new RangeError("Out of range index");if(A<=_)return this;_=_>>>0,A=A===void 0?this.length:A>>>0,f||(f=0);let Z;if(typeof f=="number")for(Z=_;Z<A;++Z)this[Z]=f;else{let de=s.isBuffer(f)?f:s.from(f,B),_e=de.length;if(_e===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(Z=0;Z<A-_;++Z)this[Z+_]=de[Z%_e]}return this};let K={};function j(f,_,A){K[f]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:_.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${f}]`,this.stack,delete this.name}get code(){return f}set code(B){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:B,writable:!0})}toString(){return`${this.name} [${f}]: ${this.message}`}}}j("ERR_BUFFER_OUT_OF_BOUNDS",function(f){return f?`${f} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(f,_){return`The "${f}" argument must be of type number. Received type ${typeof _}`},TypeError),j("ERR_OUT_OF_RANGE",function(f,_,A){let B=`The value of "${f}" is out of range.`,Z=A;return Number.isInteger(A)&&Math.abs(A)>4294967296?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"),B+=` It must be ${_}. Received ${Z}`,B},RangeError);function ne(f){let _="",A=f.length,B=f[0]==="-"?1:0;for(;A>=B+4;A-=3)_=`_${f.slice(A-3,A)}${_}`;return`${f.slice(0,A)}${_}`}function z(f,_,A){Q(_,"offset"),(f[_]===void 0||f[_+A]===void 0)&&be(_,f.length-(A+1))}function G(f,_,A,B,Z,de){if(f>A||f<_){let _e=typeof _=="bigint"?"n":"",V;throw _===0||_===BigInt(0)?V=`>= 0${_e} and < 2${_e} ** ${(de+1)*8}${_e}`:V=`>= -(2${_e} ** ${(de+1)*8-1}${_e}) and < 2 ** ${(de+1)*8-1}${_e}`,new K.ERR_OUT_OF_RANGE("value",V,f)}z(B,Z,de)}function Q(f,_){if(typeof f!="number")throw new K.ERR_INVALID_ARG_TYPE(_,"number",f)}function be(f,_,A){throw Math.floor(f)!==f?(Q(f,A),new K.ERR_OUT_OF_RANGE("offset","an integer",f)):_<0?new K.ERR_BUFFER_OUT_OF_BOUNDS:new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${_}`,f)}let se=/[^+/0-9A-Za-z-_]/g;function N(f){if(f=f.split("=")[0],f=f.trim().replace(se,""),f.length<2)return"";for(;f.length%4!==0;)f=f+"=";return f}function q(f,_){_=_||1/0;let A,B=f.length,Z=null,de=[];for(let _e=0;_e<B;++_e){if(A=f.charCodeAt(_e),A>55295&&A<57344){if(!Z){if(A>56319){(_-=3)>-1&&de.push(239,191,189);continue}else if(_e+1===B){(_-=3)>-1&&de.push(239,191,189);continue}Z=A;continue}if(A<56320){(_-=3)>-1&&de.push(239,191,189),Z=A;continue}A=(Z-55296<<10|A-56320)+65536}else Z&&(_-=3)>-1&&de.push(239,191,189);if(Z=null,A<128){if((_-=1)<0)break;de.push(A)}else if(A<2048){if((_-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((_-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((_-=4)<0)break;de.push(A>>18|240,A>>12&63|128,A>>6&63|128,A&63|128)}else throw new Error("Invalid code point")}return de}function te(f){let _=[];for(let A=0;A<f.length;++A)_.push(f.charCodeAt(A)&255);return _}function he(f,_){let A,B,Z,de=[];for(let _e=0;_e<f.length&&!((_-=2)<0);++_e)A=f.charCodeAt(_e),B=A>>8,Z=A%256,de.push(Z),de.push(B);return de}function pe(f){return i.toByteArray(N(f))}function ye(f,_,A,B){let Z;for(Z=0;Z<B&&!(Z+A>=_.length||Z>=f.length);++Z)_[Z+A]=f[Z];return Z}function H(f,_){return f instanceof _||f!=null&&f.constructor!=null&&f.constructor.name!=null&&f.constructor.name===_.name}function me(f){return f!==f}let ve=(function(){let f="0123456789abcdef",_=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let Z=0;Z<16;++Z)_[B+Z]=f[A]+f[Z]}return _})();function ae(f){return typeof BigInt>"u"?Le:f}function Le(){throw new Error("BigInt not supported")}return Et}var Wt,_i,or,xi,Et,Si,ou=Qe(()=>{le(),ue(),ce(),Wt={},_i=!1,or={},xi=!1,Et={},Si=!1}),qe={};Ht(qe,{Buffer:()=>Er,INSPECT_MAX_BYTES:()=>fs,default:()=>mt,kMaxLength:()=>ms});var mt,Er,fs,ms,He=Qe(()=>{le(),ue(),ce(),ou(),mt=iu(),mt.Buffer,mt.SlowBuffer,mt.INSPECT_MAX_BYTES,mt.kMaxLength,Er=mt.Buffer,fs=mt.INSPECT_MAX_BYTES,ms=mt.kMaxLength}),ue=Qe(()=>{He()}),Be=fe((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}}),gs=fe((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"{}"}}}}),Ye=fe((i,e)=>{le(),ue(),ce();var{format:t,inspect:r}=gs(),{AggregateError:o}=Be(),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,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function h(m){let k="",x=m.length,v=m[0]==="-"?1:0;for(;x>=v+4;x-=3)k=`_${m.slice(x-3,x)}${k}`;return`${m.slice(0,x)}${k}`}function g(m,k,x){if(typeof k=="function")return d(k.length<=x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${k.length}).`),k(...x);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===x.length,`Code: ${m}; The provided arguments length (${x.length}) does not match the required ones (${v}).`),x.length===0?k:t(k,...x)}function p(m,k,x){x||(x=Error);class v extends x{constructor(...E){super(g(m,k,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 k=c+m.name;return Object.defineProperty(m,"name",{value:k}),m}function y(m,k){if(m&&k&&m!==k){if(Array.isArray(k.errors))return k.errors.push(m),k;let x=new n([k,m],k.message);return x.code=k.code,x}return m||k}var w=class extends Error{constructor(m="The operation was aborted",k=void 0){if(k!==void 0&&typeof k!="object")throw new u.ERR_INVALID_ARG_TYPE("options","Object",k);super(m,k),this.code="ABORT_ERR",this.name="AbortError"}};p("ERR_ASSERTION","%s",Error),p("ERR_INVALID_ARG_TYPE",(m,k,x)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let S=[],E=[],I=[];for(let O of k)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),p("ERR_INVALID_ARG_VALUE",(m,k,x="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${x}. Received ${v}`},TypeError),p("ERR_INVALID_RETURN_VALUE",(m,k,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 "${k}" function but got ${S}.`},TypeError),p("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,x=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),x){case 1:k+=`The ${m[0]} argument`;break;case 2:k+=`The ${m[0]} and ${m[1]} arguments`;break;default:{let v=m.pop();k+=`The ${m.join(", ")}, and ${v} arguments`}break}return`${k} must be specified`},TypeError),p("ERR_OUT_OF_RANGE",(m,k,x)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(x)&&Math.abs(x)>2**32)v=h(String(x));else if(typeof x=="bigint"){v=String(x);let S=BigInt(2)**BigInt(32);(x>S||x<-S)&&(v=h(v)),v+="n"}else v=r(x);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),p("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),p("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),p("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),p("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),p("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),p("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),p("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),p("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),p("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),p("ERR_STREAM_WRITE_AFTER_END","write after end",Error),p("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),sr=fe((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}),At={};Ht(At,{EventEmitter:()=>bs,default:()=>zt,defaultMaxListeners:()=>ys,init:()=>vs,listenerCount:()=>ws,on:()=>ks,once:()=>_s});function su(){if(Ei)return ar;Ei=!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)}ar=n,ar.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 U=I[x];if(U===void 0)return!1;if(typeof U=="function")e(U,this,v);else for(var T=U.length,F=p(U,T),S=0;S<T;++S)e(F[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 U=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");U.name="MaxListenersExceededWarning",U.emitter=x,U.type=v,U.count=O.length,r(U)}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 h(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):p(I,I.length)}n.prototype.listeners=function(x){return h(this,x,!0)},n.prototype.rawListeners=function(x){return h(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 p(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))}k(x,v,P,{once:!0}),v!=="error"&&m(x,I,{once:!0})})}function m(x,v,S){typeof x.on=="function"&&k(x,"error",v,S)}function k(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 ar}var ar,Ei,zt,bs,ys,vs,ws,ks,_s,Rt=Qe(()=>{le(),ue(),ce(),ar={},Ei=!1,zt=su(),zt.once,zt.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)})},zt.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:bs,defaultMaxListeners:ys,init:vs,listenerCount:ws,on:ks,once:_s}=zt}),Xe=fe((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),{format:r,inspect:o}=gs(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ye(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=Be(),c=globalThis.AbortSignal||sr().AbortSignal,u=globalThis.AbortController||sr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,h=globalThis.Blob||t.Blob,g=typeof h<"u"?function(y){return y instanceof h}:function(y){return!1},p=(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,k)=>{y=m,w=k}),resolve:y,reject:w}},promisify(y){return new Promise((w,m)=>{y((k,...x)=>k?m(k):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:(Rt(),je(At)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);p(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 k;(k=m)===null||k===void 0||k()}}},AbortSignalAny:c.any||function(y){if(y.length===1)return y[0];let w=new u,m=()=>w.abort();return y.forEach(k=>{p(k,"signals"),k.addEventListener("abort",m,{once:!0})}),w.signal.addEventListener("abort",()=>{y.forEach(k=>k.removeEventListener("abort",m))},{once:!0}),w.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),lr=fe((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:h,String:g,StringPrototypeToUpperCase:p,StringPrototypeTrim:b}=Be(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:v}}=Ye(),{normalizeEncoding:S}=Xe(),{isAsyncFunction:E,isArrayBufferView:I}=Xe().types,P={};function O(H){return H===(H|0)}function U(H){return H===H>>>0}var T=/^[0-7]+$/,F="must be a 32-bit unsigned integer or an octal string";function L(H,me,ve){if(typeof H>"u"&&(H=ve),typeof H=="string"){if(h(T,H)===null)throw new k(me,H,F);H=u(H,8)}return Y(H,me),H}var D=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)}),Y=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,Le=4294967295;if(H<ae||H>Le)throw new x(me,`>= ${ae} && <= ${Le}`,H)});function W(H,me){if(typeof H!="string")throw new m(me,"string",H)}function ee(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 $=y((H,me,ve)=>{if(!r(ve,H)){let ae="must be one of: "+o(n(ve,Le=>typeof Le=="string"?`'${Le}'`:g(Le)),", ");throw new k(me,H,ae)}});function X(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 J=y((H,me,ve=null)=>{let ae=M(ve,"allowArray",!1),Le=M(ve,"allowFunction",!1);if(!M(ve,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Le||typeof H!="function"))throw new m(me,"Object",H)}),ge=y((H,me)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(me,"a dictionary",H)}),re=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 k(me,H,ae)}});function we(H,me){re(H,me);for(let ve=0;ve<H.length;ve++)W(H[ve],`${me}[${ve}]`)}function K(H,me){re(H,me);for(let ve=0;ve<H.length;ve++)X(H[ve],`${me}[${ve}]`)}function j(H,me){re(H,me);for(let ve=0;ve<H.length;ve++){let ae=H[ve],Le=`${me}[${ve}]`;if(ae==null)throw new m(Le,"AbortSignal",ae);be(ae,Le)}}function ne(H,me="signal"){if(W(H,me),P[H]===void 0)throw P[p(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 G(H,me){let ve=S(me),ae=H.length;if(ve==="hex"&&ae%2!==0)throw new k("encoding",me,`is invalid for data of length ${ae}`)}function Q(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 be=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)}),N=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 te(H,me,ve){if(!r(ve,H))throw new m(me,`('${o(ve,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function pe(H,me){if(typeof H>"u"||!h(he,H))throw new k(me,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return pe(H,"hints"),H;if(t(H)){let me=H.length,ve="";if(me===0)return ve;for(let ae=0;ae<me;ae++){let Le=H[ae];pe(Le,"hints"),ve+=Le,ae!==me-1&&(ve+=", ")}return ve}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:U,parseFileMode:L,validateArray:re,validateStringArray:we,validateBooleanArray:K,validateAbortSignalArray:j,validateBoolean:X,validateBuffer:z,validateDictionary:ge,validateEncoding:G,validateFunction:se,validateInt32:oe,validateInteger:D,validateNumber:ee,validateObject:J,validateOneOf:$,validatePlainFunction:N,validatePort:Q,validateSignalName:ne,validateString:W,validateUint32:Y,validateUndefined:q,validateUnion:te,validateAbortSignal:be,validateLinkHeaderValue:ye}}),jt=fe((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,h=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):h=-1,c.length&&p())}function p(){if(!u){var w=a(g);u=!0;for(var m=c.length;m;){for(d=c,c=[];++h<m;)d&&d[h].run();h=-1,m=c.length}d=null,u=!1,l(w)}}t.nextTick=function(w){var m=new Array(arguments.length-1);if(arguments.length>1)for(var k=1;k<arguments.length;k++)m[k-1]=arguments[k];c.push(new b(w,m)),c.length===1&&!u&&a(p)};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}}),gt=fe((i,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:o}=Be(),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 h(M,J=!1){var ge;return!!(M&&typeof M.pipe=="function"&&typeof M.on=="function"&&(!J||typeof M.pause=="function"&&typeof M.resume=="function")&&(!M._writableState||((ge=M._readableState)===null||ge===void 0?void 0:ge.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 p(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 k(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,ge=M._readableState,re=J||ge;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 ge=M._writableState;return ge!=null&&ge.errored?!1:typeof ge?.finished!="boolean"?null:!!(ge.finished||J===!1&&ge.ended===!0&&ge.length===0)}function I(M){if(!h(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(!h(M))return null;let ge=M._readableState;return ge!=null&&ge.errored?!1:typeof ge?.endEmitted!="boolean"?null:!!(ge.endEmitted||J===!1&&ge.ended===!0&&ge.length===0)}function O(M){return M&&M[a]!=null?M[a]:typeof M?.readable!="boolean"?null:v(M)?!1:h(M)&&M.readable&&!P(M)}function U(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&&U(M)):null}function F(M){var J,ge;return b(M)?M.writableErrored?M.writableErrored:(J=(ge=M._writableState)===null||ge===void 0?void 0:ge.errored)!==null&&J!==void 0?J:null:null}function L(M){var J,ge;return b(M)?M.readableErrored?M.readableErrored:(J=(ge=M._readableState)===null||ge===void 0?void 0:ge.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,ge=M._readableState;return typeof J?.closed=="boolean"||typeof ge?.closed=="boolean"?J?.closed||ge?.closed:typeof M._closed=="boolean"&&oe(M)?M._closed:null}function oe(M){return typeof M._closed=="boolean"&&typeof M._defaultKeepAlive=="boolean"&&typeof M._removedConnection=="boolean"&&typeof M._removedContLen=="boolean"}function Y(M){return typeof M._sent100=="boolean"&&oe(M)}function W(M){var J;return typeof M._consuming=="boolean"&&typeof M._dumped=="boolean"&&((J=M.req)===null||J===void 0?void 0:J.upgradeOrConnect)===void 0}function ee(M){if(!b(M))return null;let J=M._writableState,ge=M._readableState,re=J||ge;return!re&&Y(M)||!!(re&&re.autoDestroy&&re.emitClose&&re.closed===!1)}function $(M){var J;return!!(M&&((J=M[c])!==null&&J!==void 0?J:M.readableDidRead||M.readableAborted))}function X(M){var J,ge,re,we,K,j,ne,z,G,Q;return!!(M&&((J=(ge=(re=(we=(K=(j=M[s])!==null&&j!==void 0?j:M.readableErrored)!==null&&K!==void 0?K:M.writableErrored)!==null&&we!==void 0?we:(ne=M._readableState)===null||ne===void 0?void 0:ne.errorEmitted)!==null&&re!==void 0?re:(z=M._writableState)===null||z===void 0?void 0:z.errorEmitted)!==null&&ge!==void 0?ge:(G=M._readableState)===null||G===void 0?void 0:G.errored)!==null&&J!==void 0?J:!((Q=M._writableState)===null||Q===void 0)&&Q.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:$,kIsDisturbed:c,isErrored:X,kIsErrored:s,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:D,isDuplexNodeStream:p,isFinished:T,isIterable:x,isReadableNodeStream:h,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:L,isNodeStream:b,isWebStream:k,isWritable:U,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:S,isWritableFinished:E,isWritableErrored:F,isServerRequest:W,isServerResponse:Y,willEmitClose:ee,isTransformStream:m}}),It=fe((i,e)=>{le(),ue(),ce();var t=jt(),{AbortError:r,codes:o}=Ye(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=o,{kEmptyObject:a,once:l}=Xe(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:h}=lr(),{Promise:g,PromisePrototypeThen:p,SymbolDispose:b}=Be(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:x,isReadableErrored:v,isWritable:S,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:U,willEmitClose:T,kIsClosedPromise:F}=gt(),L;function D($){return $.setHeader&&typeof $.abort=="function"}var oe=()=>{};function Y($,X,M){var J,ge;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),k($)||I($))return W($,X,M);if(!U($))throw new n("stream",["ReadableStream","WritableStream","Stream"],$);let re=(J=X.readable)!==null&&J!==void 0?J:m($),we=(ge=X.writable)!==null&&ge!==void 0?ge:E($),K=$._writableState,j=$._readableState,ne=()=>{$.writable||Q()},z=T($)&&m($)===re&&E($)===we,G=P($,!1),Q=()=>{G=!0,$.destroyed&&(z=!1),!(z&&(!$.readable||re))&&(!re||be)&&M.call($)},be=x($,!1),se=()=>{be=!0,$.destroyed&&(z=!1),!(z&&(!$.writable||we))&&(!we||G)&&M.call($)},N=H=>{M.call($,H)},q=y($),te=()=>{q=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);if(re&&!be&&m($,!0)&&!x($,!1))return M.call($,new s);if(we&&!G&&!P($,!1))return M.call($,new s);M.call($)},he=()=>{q=!0;let H=O($)||v($);if(H&&typeof H!="boolean")return M.call($,H);M.call($)},pe=()=>{$.req.on("finish",Q)};D($)?($.on("complete",Q),z||$.on("abort",te),$.req?pe():$.on("request",pe)):we&&!K&&($.on("end",ne),$.on("close",ne)),!z&&typeof $.aborted=="boolean"&&$.on("aborted",te),$.on("end",se),$.on("finish",Q),X.error!==!1&&$.on("error",N),$.on("close",te),q?t.nextTick(te):K!=null&&K.errorEmitted||j!=null&&j.errorEmitted?z||t.nextTick(he):(!re&&(!z||w($))&&(G||S($)===!1)||!we&&(!z||S($))&&(be||w($)===!1)||j&&$.req&&$.aborted)&&t.nextTick(he);let ye=()=>{M=oe,$.removeListener("aborted",te),$.removeListener("complete",Q),$.removeListener("abort",te),$.removeListener("request",pe),$.req&&$.req.removeListener("finish",Q),$.removeListener("end",ne),$.removeListener("close",ne),$.removeListener("finish",Q),$.removeListener("end",se),$.removeListener("error",N),$.removeListener("close",te)};if(X.signal&&!q){let H=()=>{let me=M;ye(),me.call($,new r(void 0,{cause:X.signal.reason}))};if(X.signal.aborted)t.nextTick(H);else{L=L||Xe().addAbortListener;let me=L(X.signal,H),ve=M;M=l((...ae)=>{me[b](),ve.apply($,ae)})}}return ye}function W($,X,M){let J=!1,ge=oe;if(X.signal)if(ge=()=>{J=!0,M.call($,new r(void 0,{cause:X.signal.reason}))},X.signal.aborted)t.nextTick(ge);else{L=L||Xe().addAbortListener;let we=L(X.signal,ge),K=M;M=l((...j)=>{we[b](),K.apply($,j)})}let re=(...we)=>{J||t.nextTick(()=>M.apply($,we))};return p($[F].promise,re,re),oe}function ee($,X){var M;let J=!1;return X===null&&(X=a),(M=X)!==null&&M!==void 0&&M.cleanup&&(h(X.cleanup,"cleanup"),J=X.cleanup),new g((ge,re)=>{let we=Y($,X,K=>{J&&we(),K?re(K):ge()})})}e.exports=Y,e.exports.finished=ee}),Vt=fe((i,e)=>{le(),ue(),ce();var t=jt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:n}=Ye(),{Symbol:s}=Be(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=gt(),d=s("kDestroy"),h=s("kConstruct");function g(T,F,L){T&&(T.stack,F&&!F.errored&&(F.errored=T),L&&!L.errored&&(L.errored=T))}function p(T,F){let L=this._readableState,D=this._writableState,oe=D||L;return D!=null&&D.destroyed||L!=null&&L.destroyed?(typeof F=="function"&&F(),this):(g(T,D,L),D&&(D.destroyed=!0),L&&(L.destroyed=!0),oe.constructed?b(this,T,F):this.once(d,function(Y){b(this,r(Y,T),F)}),this)}function b(T,F,L){let D=!1;function oe(Y){if(D)return;D=!0;let W=T._readableState,ee=T._writableState;g(Y,ee,W),ee&&(ee.closed=!0),W&&(W.closed=!0),typeof L=="function"&&L(Y),Y?t.nextTick(y,T,Y):t.nextTick(w,T)}try{T._destroy(F||null,oe)}catch(Y){oe(Y)}}function y(T,F){m(T,F),w(T)}function w(T){let F=T._readableState,L=T._writableState;L&&(L.closeEmitted=!0),F&&(F.closeEmitted=!0),(L!=null&&L.emitClose||F!=null&&F.emitClose)&&T.emit("close")}function m(T,F){let L=T._readableState,D=T._writableState;D!=null&&D.errorEmitted||L!=null&&L.errorEmitted||(D&&(D.errorEmitted=!0),L&&(L.errorEmitted=!0),T.emit("error",F))}function k(){let T=this._readableState,F=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),F&&(F.constructed=!0,F.destroyed=!1,F.closed=!1,F.closeEmitted=!1,F.errored=null,F.errorEmitted=!1,F.finalCalled=!1,F.prefinished=!1,F.ended=F.writable===!1,F.ending=F.writable===!1,F.finished=F.writable===!1)}function x(T,F,L){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(F):F&&(F.stack,oe&&!oe.errored&&(oe.errored=F),D&&!D.errored&&(D.errored=F),L?t.nextTick(m,T,F):m(T,F))}function v(T,F){if(typeof T._construct!="function")return;let L=T._readableState,D=T._writableState;L&&(L.constructed=!1),D&&(D.constructed=!1),T.once(h,F),!(T.listenerCount(h)>1)&&t.nextTick(S,T)}function S(T){let F=!1;function L(D){if(F){x(T,D??new o);return}F=!0;let oe=T._readableState,Y=T._writableState,W=Y||oe;oe&&(oe.constructed=!0),Y&&(Y.constructed=!0),W.destroyed?T.emit(d,D):D?x(T,D,!0):t.nextTick(E,T)}try{T._construct(D=>{t.nextTick(L,D)})}catch(D){t.nextTick(L,D)}}function E(T){T.emit(h)}function I(T){return T?.setHeader&&typeof T.abort=="function"}function P(T){T.emit("close")}function O(T,F){T.emit("error",F),t.nextTick(P,T)}function U(T,F){!T||l(T)||(!F&&!c(T)&&(F=new n),u(T)?(T.socket=null,T.destroy(F)):I(T)?T.abort():I(T.req)?T.req.abort():typeof T.destroy=="function"?T.destroy(F):typeof T.close=="function"?T.close():F?t.nextTick(O,T,F):t.nextTick(P,T),T.destroyed||(T[a]=!0))}e.exports={construct:v,destroyer:U,destroy:p,undestroy:k,errorOrDestroy:x}}),Ai=fe((i,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Be(),{EventEmitter:o}=(Rt(),je(At));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",p));let h=!1;function g(){h||(h=!0,a.end())}function p(){h||(h=!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",p),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}}),Ar=fe((i,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Be(),{AbortError:r,codes:o}=Ye(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=gt(),l=It(),{ERR_INVALID_ARG_TYPE:c}=o,u,d=(h,g)=>{if(typeof h!="object"||!("aborted"in h))throw new c(g,"AbortSignal",h)};e.exports.addAbortSignal=function(h,g){if(d(h,"signal"),!n(g)&&!s(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(h,g)},e.exports.addAbortSignalNoValidate=function(h,g){if(typeof h!="object"||!("aborted"in h))return g;let p=n(g)?()=>{g.destroy(new r(void 0,{cause:h.reason}))}:()=>{g[a](new r(void 0,{cause:h.reason}))};if(h.aborted)p();else{u=u||Xe().addAbortListener;let b=u(h,p);l(g,b[t])}return g}}),au=fe((i,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:o,Uint8Array:n}=Be(),{Buffer:s}=(He(),je(qe)),{inspect:a}=Xe();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 h=u.data;if(l>h.length)c+=h,l-=h.length;else{l===h.length?(c+=h,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(h,0,l),this.head=u,u.data=t(h,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,h=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),++h,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}++h}while((d=d.next)!==null);return this.length-=h,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),Ir=fe((i,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Be(),{validateInteger:o}=lr(),{ERR_INVALID_ARG_VALUE:n}=Ye().codes,s=16*1024,a=16;function l(h,g,p){return h.highWaterMark!=null?h.highWaterMark:g?h[p]:null}function c(h){return h?a:s}function u(h,g){o(g,"value",0),h?a=g:s=g}function d(h,g,p,b){let y=l(g,b,p);if(y!=null){if(!r(y)||y<0){let w=b?`options.${p}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(h.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),lu=fe((i,e)=>{le(),ue(),ce();var t=(He(),je(qe)),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)}}),cu=fe(i=>{le(),ue(),ce();var e=lu().Buffer,t=e.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function o(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}i.StringDecoder=n;function n(m){this.encoding=o(m);var k;switch(this.encoding){case"utf16le":this.text=h,this.end=g,k=4;break;case"utf8":this.fillLast=c,k=4;break;case"base64":this.text=p,this.end=b,k=3;break;default:this.write=y,this.end=w;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(k)}n.prototype.write=function(m){if(m.length===0)return"";var k,x;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;return x<m.length?k?k+this.text(m,x):this.text(m,x):k||""},n.prototype.end=d,n.prototype.text=u,n.prototype.fillLast=function(m){if(this.lastNeed<=m.length)return m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,this.lastTotal-this.lastNeed,0,m.length),this.lastNeed-=m.length};function 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,k,x){var v=k.length-1;if(v<x)return 0;var S=s(k[v]);return S>=0?(S>0&&(m.lastNeed=S-1),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(m.lastNeed=S-2),S):--v<x||S===-2?0:(S=s(k[v]),S>=0?(S>0&&(S===2?S=0:m.lastNeed=S-3),S):0))}function l(m,k,x){if((k[0]&192)!==128)return m.lastNeed=0,"�";if(m.lastNeed>1&&k.length>1){if((k[1]&192)!==128)return m.lastNeed=1,"�";if(m.lastNeed>2&&k.length>2&&(k[2]&192)!==128)return m.lastNeed=2,"�"}}function c(m){var k=this.lastTotal-this.lastNeed,x=l(this,m);if(x!==void 0)return x;if(this.lastNeed<=m.length)return m.copy(this.lastChar,k,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);m.copy(this.lastChar,k,0,m.length),this.lastNeed-=m.length}function u(m,k){var x=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=x;var v=m.length-(x-this.lastNeed);return m.copy(this.lastChar,0,v),m.toString("utf8",k,v)}function d(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+"�":k}function h(m,k){if((m.length-k)%2===0){var x=m.toString("utf16le",k);if(x){var v=x.charCodeAt(x.length-1);if(v>=55296&&v<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function g(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,x)}return k}function p(m,k){var x=(m.length-k)%3;return x===0?m.toString("base64",k):(this.lastNeed=3-x,this.lastTotal=3,x===1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-x))}function b(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function y(m){return m.toString(this.encoding)}function w(m){return m&&m.length?this.write(m):""}}),xs=fe((i,e)=>{le(),ue(),ce();var t=jt(),{PromisePrototypeThen:r,SymbolAsyncIterator:o,SymbolIterator:n}=Be(),{Buffer:s}=(He(),je(qe)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ye().codes;function c(u,d,h){let g;if(typeof d=="string"||d instanceof s)return new u({objectMode:!0,...h,read(){this.push(d),this.push(null)}});let p;if(d&&d[o])p=!0,g=d[o]();else if(d&&d[n])p=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...h}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,x){r(w(k),()=>t.nextTick(x,k),v=>t.nextTick(x,v||k))};async function w(k){let x=k!=null,v=typeof g.throw=="function";if(x&&v){let{value:S,done:E}=await g.throw(k);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:k,done:x}=p?await g.next():g.next();if(x)b.push(null);else{let v=k&&typeof k.then=="function"?await k:k;if(v===null)throw y=!1,new l;if(b.push(v))continue;y=!1}}catch(k){b.destroy(k)}break}}return b}e.exports=c}),Tr=fe((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:o,NumberIsNaN:n,NumberParseInt:s,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:h,SymbolAsyncIterator:g,Symbol:p}=Be();e.exports=ae,ae.ReadableState=ve;var{EventEmitter:b}=(Rt(),je(At)),{Stream:y,prependListener:w}=Ai(),{Buffer:m}=(He(),je(qe)),{addAbortSignal:k}=Ar(),x=It(),v=Xe().debuglog("stream",C=>{v=C}),S=au(),E=Vt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=Ir(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:U,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:F,ERR_STREAM_PUSH_AFTER_EOF:L,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:D},AbortError:oe}=Ye(),{validateObject:Y}=lr(),W=p("kPaused"),{StringDecoder:ee}=cu(),$=xs();c(ae.prototype,y.prototype),c(ae,y);var X=()=>{},{errorOrDestroy:M}=E,J=1,ge=2,re=4,we=8,K=16,j=32,ne=64,z=128,G=256,Q=512,be=1024,se=2048,N=4096,q=8192,te=16384,he=32768,pe=65536,ye=1<<17,H=1<<18;function me(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(R){R?this.state|=C:this.state&=~C}}}a(ve.prototype,{objectMode:me(J),ended:me(ge),endEmitted:me(re),reading:me(we),constructed:me(K),sync:me(j),needReadable:me(ne),emittedReadable:me(z),readableListening:me(G),resumeScheduled:me(Q),errorEmitted:me(be),emitClose:me(se),autoDestroy:me(N),destroyed:me(q),closed:me(te),closeEmitted:me(he),multiAwaitDrain:me(pe),readingMore:me(ye),dataEmitted:me(H)});function ve(C,R,ke){typeof ke!="boolean"&&(ke=R instanceof bt()),this.state=se|N|K|j,C&&C.objectMode&&(this.state|=J),ke&&C&&C.readableObjectMode&&(this.state|=J),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new S,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,C&&C.emitClose===!1&&(this.state&=~se),C&&C.autoDestroy===!1&&(this.state&=~N),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new ee(C.encoding),this.encoding=C.encoding)}function ae(C){if(!(this instanceof ae))return new ae(C);let R=this instanceof bt();this._readableState=new ve(C,this,R),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&&!R&&k(C.signal,this)),y.call(this,C),E.construct(this,()=>{this._readableState.needReadable&&V(this,this._readableState)})}ae.prototype.destroy=E.destroy,ae.prototype._undestroy=E.undestroy,ae.prototype._destroy=function(C,R){R(C)},ae.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},ae.prototype[h]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new oe,this.destroy(C)),new u((R,ke)=>x(this,Se=>Se&&Se!==C?ke(Se):R(null)))},ae.prototype.push=function(C,R){return Le(this,C,R,!1)},ae.prototype.unshift=function(C,R){return Le(this,C,R,!0)};function Le(C,R,ke,Se){v("readableAddChunk",R);let Ae=C._readableState,Fe;if((Ae.state&J)===0&&(typeof R=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(Se&&Ae.encoding?R=m.from(R,ke).toString(Ae.encoding):(R=m.from(R,ke),ke=""))):R instanceof m?ke="":y._isUint8Array(R)?(R=y._uint8ArrayToBuffer(R),ke=""):R!=null&&(Fe=new U("chunk",["string","Buffer","Uint8Array"],R))),Fe)M(C,Fe);else if(R===null)Ae.state&=~we,Z(C,Ae);else if((Ae.state&J)!==0||R&&R.length>0)if(Se)if((Ae.state&re)!==0)M(C,new D);else{if(Ae.destroyed||Ae.errored)return!1;f(C,Ae,R,!0)}else if(Ae.ended)M(C,new L);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~we,Ae.decoder&&!ke?(R=Ae.decoder.write(R),Ae.objectMode||R.length!==0?f(C,Ae,R,!1):V(C,Ae)):f(C,Ae,R,!1)}else Se||(Ae.state&=~we,V(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function f(C,R,ke,Se){R.flowing&&R.length===0&&!R.sync&&C.listenerCount("data")>0?((R.state&pe)!==0?R.awaitDrainWriters.clear():R.awaitDrainWriters=null,R.dataEmitted=!0,C.emit("data",ke)):(R.length+=R.objectMode?1:ke.length,Se?R.buffer.unshift(ke):R.buffer.push(ke),(R.state&ne)!==0&&de(C)),V(C,R)}ae.prototype.isPaused=function(){let C=this._readableState;return C[W]===!0||C.flowing===!1},ae.prototype.setEncoding=function(C){let R=new ee(C);this._readableState.decoder=R,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,Se="";for(let Ae of ke)Se+=R.write(Ae);return ke.clear(),Se!==""&&ke.push(Se),this._readableState.length=Se.length,this};var _=1073741824;function A(C){if(C>_)throw new F("size","<= 1GiB",C);return C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++,C}function B(C,R){return C<=0||R.length===0&&R.ended?0:(R.state&J)!==0?1:n(C)?R.flowing&&R.length?R.buffer.first().length:R.length:C<=R.length?C:R.ended?R.length:0}ae.prototype.read=function(C){v("read",C),C===void 0?C=NaN:o(C)||(C=s(C,10));let R=this._readableState,ke=C;if(C>R.highWaterMark&&(R.highWaterMark=A(C)),C!==0&&(R.state&=~z),C===0&&R.needReadable&&((R.highWaterMark!==0?R.length>=R.highWaterMark:R.length>0)||R.ended))return v("read: emitReadable",R.length,R.ended),R.length===0&&R.ended?ut(this):de(this),null;if(C=B(C,R),C===0&&R.ended)return R.length===0&&ut(this),null;let Se=(R.state&ne)!==0;if(v("need readable",Se),(R.length===0||R.length-C<R.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),R.ended||R.reading||R.destroyed||R.errored||!R.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),R.state|=we|j,R.length===0&&(R.state|=ne);try{this._read(R.highWaterMark)}catch(Fe){M(this,Fe)}R.state&=~j,R.reading||(C=B(ke,R))}let Ae;return C>0?Ae=tr(C,R):Ae=null,Ae===null?(R.needReadable=R.length<=R.highWaterMark,C=0):(R.length-=C,R.multiAwaitDrain?R.awaitDrainWriters.clear():R.awaitDrainWriters=null),R.length===0&&(R.ended||(R.needReadable=!0),ke!==C&&R.ended&&ut(this)),Ae!==null&&!R.errorEmitted&&!R.closeEmitted&&(R.dataEmitted=!0,this.emit("data",Ae)),Ae};function Z(C,R){if(v("onEofChunk"),!R.ended){if(R.decoder){let ke=R.decoder.end();ke&&ke.length&&(R.buffer.push(ke),R.length+=R.objectMode?1:ke.length)}R.ended=!0,R.sync?de(C):(R.needReadable=!1,R.emittedReadable=!0,_e(C))}}function de(C){let R=C._readableState;v("emitReadable",R.needReadable,R.emittedReadable),R.needReadable=!1,R.emittedReadable||(v("emitReadable",R.flowing),R.emittedReadable=!0,t.nextTick(_e,C))}function _e(C){let R=C._readableState;v("emitReadable_",R.destroyed,R.length,R.ended),!R.destroyed&&!R.errored&&(R.length||R.ended)&&(C.emit("readable"),R.emittedReadable=!1),R.needReadable=!R.flowing&&!R.ended&&R.length<=R.highWaterMark,lt(C)}function V(C,R){!R.readingMore&&R.constructed&&(R.readingMore=!0,t.nextTick(ie,C,R))}function ie(C,R){for(;!R.reading&&!R.ended&&(R.length<R.highWaterMark||R.flowing&&R.length===0);){let ke=R.length;if(v("maybeReadMore read 0"),C.read(0),ke===R.length)break}R.readingMore=!1}ae.prototype._read=function(C){throw new T("_read()")},ae.prototype.pipe=function(C,R){let ke=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,R);let Ae=(!R||R.end!==!1)&&C!==t.stdout&&C!==t.stderr?Je:qt;Se.endEmitted?t.nextTick(Ae):ke.once("end",Ae),C.on("unpipe",Fe);function Fe(ht,St){v("onunpipe"),ht===ke&&St&&St.hasUnpiped===!1&&(St.hasUnpiped=!0,yr())}function Je(){v("onend"),C.end()}let it,br=!1;function yr(){v("cleanup"),C.removeListener("close",dt),C.removeListener("finish",Lt),it&&C.removeListener("drain",it),C.removeListener("error",Ft),C.removeListener("unpipe",Fe),ke.removeListener("end",Je),ke.removeListener("end",qt),ke.removeListener("data",dn),br=!0,it&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&it()}function vr(){br||(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)),ke.pause()),it||(it=Ie(ke,C),C.on("drain",it))}ke.on("data",dn);function dn(ht){v("ondata");let St=C.write(ht);v("dest.write",St),St===!1&&vr()}function Ft(ht){if(v("onerror",ht),qt(),C.removeListener("error",Ft),C.listenerCount("error")===0){let St=C._writableState||C._readableState;St&&!St.errorEmitted?M(C,ht):C.emit("error",ht)}}w(C,"error",Ft);function dt(){C.removeListener("finish",Lt),qt()}C.once("close",dt);function Lt(){v("onfinish"),C.removeListener("close",dt),qt()}C.once("finish",Lt);function qt(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?vr():Se.flowing||(v("pipe resume"),ke.resume()),C};function Ie(C,R){return function(){let ke=C._readableState;ke.awaitDrainWriters===R?(v("pipeOnDrain",1),ke.awaitDrainWriters=null):ke.multiAwaitDrain&&(v("pipeOnDrain",ke.awaitDrainWriters.size),ke.awaitDrainWriters.delete(R)),(!ke.awaitDrainWriters||ke.awaitDrainWriters.size===0)&&C.listenerCount("data")&&C.resume()}}ae.prototype.unpipe=function(C){let R=this._readableState,ke={hasUnpiped:!1};if(R.pipes.length===0)return this;if(!C){let Ae=R.pipes;R.pipes=[],this.pause();for(let Fe=0;Fe<Ae.length;Fe++)Ae[Fe].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(R.pipes,C);return Se===-1?this:(R.pipes.splice(Se,1),R.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},ae.prototype.on=function(C,R){let ke=y.prototype.on.call(this,C,R),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(Oe,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,R){let ke=y.prototype.removeListener.call(this,C,R);return C==="readable"&&t.nextTick(Te,this),ke},ae.prototype.off=ae.prototype.removeListener,ae.prototype.removeAllListeners=function(C){let R=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Te,this),R};function Te(C){let R=C._readableState;R.readableListening=C.listenerCount("readable")>0,R.resumeScheduled&&R[W]===!1?R.flowing=!0:C.listenerCount("data")>0?C.resume():R.readableListening||(R.flowing=null)}function Oe(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,Ne(this,C)),C[W]=!1,this};function Ne(C,R){R.resumeScheduled||(R.resumeScheduled=!0,t.nextTick(at,C,R))}function at(C,R){v("resume",R.reading),R.reading||C.read(0),R.resumeScheduled=!1,C.emit("resume"),lt(C),R.flowing&&!R.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[W]=!0,this};function lt(C){let R=C._readableState;for(v("flow",R.flowing);R.flowing&&C.read()!==null;);}ae.prototype.wrap=function(C){let R=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(R=!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=()=>{R&&C.resume&&(R=!1,C.resume())};let ke=l(C);for(let Se=1;Se<ke.length;Se++){let Ae=ke[Se];this[Ae]===void 0&&typeof C[Ae]=="function"&&(this[Ae]=C[Ae].bind(C))}return this},ae.prototype[g]=function(){return Ge(this)},ae.prototype.iterator=function(C){return C!==void 0&&Y(C,"options"),Ge(this,C)};function Ge(C,R){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let ke=ct(C,R);return ke.stream=C,ke}async function*ct(C,R){let ke=X;function Se(Je){this===C?(ke(),ke=X):ke=Je}C.on("readable",Se);let Ae,Fe=x(C,{writable:!1},Je=>{Ae=Je?O(Ae,Je):null,ke(),ke=X});try{for(;;){let Je=C.destroyed?null:C.read();if(Je!==null)yield Je;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Je){throw Ae=O(Ae,Je),Ae}finally{(Ae||R?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?E.destroyer(C,null):(C.off("readable",Se),Fe())}}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[W]!==!1},set(C){this[W]=!!C}}}),ae._fromList=tr;function tr(C,R){if(R.length===0)return null;let ke;return R.objectMode?ke=R.buffer.shift():!C||C>=R.length?(R.decoder?ke=R.buffer.join(""):R.buffer.length===1?ke=R.buffer.first():ke=R.buffer.concat(R.length),R.buffer.clear()):ke=R.buffer.consume(C,R.decoder),ke}function ut(C){let R=C._readableState;v("endReadable",R.endEmitted),R.endEmitted||(R.ended=!0,t.nextTick(et,R,C))}function et(C,R){if(v("endReadableNT",C.endEmitted,C.length),!C.errored&&!C.closeEmitted&&!C.endEmitted&&C.length===0){if(C.endEmitted=!0,R.emit("end"),R.writable&&R.allowHalfOpen===!1)t.nextTick(un,R);else if(C.autoDestroy){let ke=R._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&R.destroy()}}}function un(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,R){return $(ae,C,R)};var rr;function gr(){return rr===void 0&&(rr={}),rr}ae.fromWeb=function(C,R){return gr().newStreamReadableFromReadableStream(C,R)},ae.toWeb=function(C,R){return gr().newReadableStreamFromStreamReadable(C,R)},ae.wrap=function(C,R){var ke,Se;return new ae({objectMode:(ke=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&ke!==void 0?ke:!0,...R,destroy(Ae,Fe){E.destroyer(C,Ae),Fe(Ae)}}).wrap(C)}}),Ii=fe((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayPrototypeSlice:r,Error:o,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Be();e.exports=Y,Y.WritableState=D;var{EventEmitter:h}=(Rt(),je(At)),g=Ai().Stream,{Buffer:p}=(He(),je(qe)),b=Vt(),{addAbortSignal:y}=Ar(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=Ir(),{ERR_INVALID_ARG_TYPE:k,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:U}=Ye().codes,{errorOrDestroy:T}=b;l(Y.prototype,g.prototype),l(Y,g);function F(){}var L=u("kOnFinished");function D(N,q,te){typeof te!="boolean"&&(te=q instanceof bt()),this.objectMode=!!(N&&N.objectMode),te&&(this.objectMode=this.objectMode||!!(N&&N.writableObjectMode)),this.highWaterMark=N?w(this,N,"writableHighWaterMark",te):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(N&&N.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=N&&N.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=!N||N.emitClose!==!1,this.autoDestroy=!N||N.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[L]=[]}function oe(N){N.buffered=[],N.bufferedIndex=0,N.allBuffers=!0,N.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 Y(N){let q=this instanceof bt();if(!q&&!n(Y,this))return new Y(N);this._writableState=new D(N,this,q),N&&(typeof N.write=="function"&&(this._write=N.write),typeof N.writev=="function"&&(this._writev=N.writev),typeof N.destroy=="function"&&(this._destroy=N.destroy),typeof N.final=="function"&&(this._final=N.final),typeof N.construct=="function"&&(this._construct=N.construct),N.signal&&y(N.signal,this)),g.call(this,N),b.construct(this,()=>{let te=this._writableState;te.writing||we(this,te),z(this,te)})}s(Y,d,{__proto__:null,value:function(N){return n(this,N)?!0:this!==Y?!1:N&&N._writableState instanceof D}}),Y.prototype.pipe=function(){T(this,new S)};function W(N,q,te,he){let pe=N._writableState;if(typeof te=="function")he=te,te=pe.defaultEncoding;else{if(!te)te=pe.defaultEncoding;else if(te!=="buffer"&&!p.isEncoding(te))throw new U(te);typeof he!="function"&&(he=F)}if(q===null)throw new P;if(!pe.objectMode)if(typeof q=="string")pe.decodeStrings!==!1&&(q=p.from(q,te),te="buffer");else if(q instanceof p)te="buffer";else if(g._isUint8Array(q))q=g._uint8ArrayToBuffer(q),te="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],q);let ye;return pe.ending?ye=new O:pe.destroyed&&(ye=new E("write")),ye?(t.nextTick(he,ye),T(N,ye,!0),ye):(pe.pendingcb++,ee(N,pe,q,te,he))}Y.prototype.write=function(N,q,te){return W(this,N,q,te)===!0},Y.prototype.cork=function(){this._writableState.corked++},Y.prototype.uncork=function(){let N=this._writableState;N.corked&&(N.corked--,N.writing||we(this,N))},Y.prototype.setDefaultEncoding=function(N){if(typeof N=="string"&&(N=c(N)),!p.isEncoding(N))throw new U(N);return this._writableState.defaultEncoding=N,this};function ee(N,q,te,he,pe){let ye=q.objectMode?1:te.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:te,encoding:he,callback:pe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&pe!==F&&(q.allNoop=!1)):(q.writelen=ye,q.writecb=pe,q.writing=!0,q.sync=!0,N._write(te,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function $(N,q,te,he,pe,ye,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new E("write")):te?N._writev(pe,q.onwrite):N._write(pe,ye,q.onwrite),q.sync=!1}function X(N,q,te,he){--q.pendingcb,he(te),re(q),T(N,te)}function M(N,q){let te=N._writableState,he=te.sync,pe=te.writecb;if(typeof pe!="function"){T(N,new v);return}te.writing=!1,te.writecb=null,te.length-=te.writelen,te.writelen=0,q?(q.stack,te.errored||(te.errored=q),N._readableState&&!N._readableState.errored&&(N._readableState.errored=q),he?t.nextTick(X,N,te,q,pe):X(N,te,q,pe)):(te.buffered.length>te.bufferedIndex&&we(N,te),he?te.afterWriteTickInfo!==null&&te.afterWriteTickInfo.cb===pe?te.afterWriteTickInfo.count++:(te.afterWriteTickInfo={count:1,cb:pe,stream:N,state:te},t.nextTick(J,te.afterWriteTickInfo)):ge(N,te,1,pe))}function J({stream:N,state:q,count:te,cb:he}){return q.afterWriteTickInfo=null,ge(N,q,te,he)}function ge(N,q,te,he){for(!q.ending&&!N.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,N.emit("drain"));te-- >0;)q.pendingcb--,he();q.destroyed&&re(q),z(N,q)}function re(N){if(N.writing)return;for(let pe=N.bufferedIndex;pe<N.buffered.length;++pe){var q;let{chunk:ye,callback:H}=N.buffered[pe],me=N.objectMode?1:ye.length;N.length-=me,H((q=N.errored)!==null&&q!==void 0?q:new E("write"))}let te=N[L].splice(0);for(let pe=0;pe<te.length;pe++){var he;te[pe]((he=N.errored)!==null&&he!==void 0?he:new E("end"))}oe(N)}function we(N,q){if(q.corked||q.bufferProcessing||q.destroyed||!q.constructed)return;let{buffered:te,bufferedIndex:he,objectMode:pe}=q,ye=te.length-he;if(!ye)return;let H=he;if(q.bufferProcessing=!0,ye>1&&N._writev){q.pendingcb-=ye-1;let me=q.allNoop?F:ae=>{for(let Le=H;Le<te.length;++Le)te[Le].callback(ae)},ve=q.allNoop&&H===0?te:r(te,H);ve.allBuffers=q.allBuffers,$(N,q,!0,q.length,ve,"",me),oe(q)}else{do{let{chunk:me,encoding:ve,callback:ae}=te[H];te[H++]=null;let Le=pe?1:me.length;$(N,q,!1,Le,me,ve,ae)}while(H<te.length&&!q.writing);H===te.length?oe(q):H>256?(te.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}Y.prototype._write=function(N,q,te){if(this._writev)this._writev([{chunk:N,encoding:q}],te);else throw new x("_write()")},Y.prototype._writev=null,Y.prototype.end=function(N,q,te){let he=this._writableState;typeof N=="function"?(te=N,N=null,q=null):typeof q=="function"&&(te=q,q=null);let pe;if(N!=null){let ye=W(this,N,q);ye instanceof o&&(pe=ye)}return he.corked&&(he.corked=1,this.uncork()),pe||(!he.errored&&!he.ending?(he.ending=!0,z(this,he,!0),he.ended=!0):he.finished?pe=new I("end"):he.destroyed&&(pe=new E("end"))),typeof te=="function"&&(pe||he.finished?t.nextTick(te,pe):he[L].push(te)),this};function K(N){return N.ending&&!N.destroyed&&N.constructed&&N.length===0&&!N.errored&&N.buffered.length===0&&!N.finished&&!N.writing&&!N.errorEmitted&&!N.closeEmitted}function j(N,q){let te=!1;function he(pe){if(te){T(N,pe??v());return}if(te=!0,q.pendingcb--,pe){let ye=q[L].splice(0);for(let H=0;H<ye.length;H++)ye[H](pe);T(N,pe,q.sync)}else K(q)&&(q.prefinished=!0,N.emit("prefinish"),q.pendingcb++,t.nextTick(G,N,q))}q.sync=!0,q.pendingcb++;try{N._final(he)}catch(pe){he(pe)}q.sync=!1}function ne(N,q){!q.prefinished&&!q.finalCalled&&(typeof N._final=="function"&&!q.destroyed?(q.finalCalled=!0,j(N,q)):(q.prefinished=!0,N.emit("prefinish")))}function z(N,q,te){K(q)&&(ne(N,q),q.pendingcb===0&&(te?(q.pendingcb++,t.nextTick((he,pe)=>{K(pe)?G(he,pe):pe.pendingcb--},N,q)):K(q)&&(q.pendingcb++,G(N,q))))}function G(N,q){q.pendingcb--,q.finished=!0;let te=q[L].splice(0);for(let he=0;he<te.length;he++)te[he]();if(N.emit("finish"),q.autoDestroy){let he=N._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&N.destroy()}}a(Y.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(N){this._writableState&&(this._writableState.destroyed=N)}},writable:{__proto__:null,get(){let N=this._writableState;return!!N&&N.writable!==!1&&!N.destroyed&&!N.errored&&!N.ending&&!N.ended},set(N){this._writableState&&(this._writableState.writable=!!N)}},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 N=this._writableState;return N?!N.destroyed&&!N.ending&&N.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;Y.prototype.destroy=function(N,q){let te=this._writableState;return!te.destroyed&&(te.bufferedIndex<te.buffered.length||te[L].length)&&t.nextTick(re,te),Q.call(this,N,q),this},Y.prototype._undestroy=b.undestroy,Y.prototype._destroy=function(N,q){q(N)},Y.prototype[h.captureRejectionSymbol]=function(N){this.destroy(N)};var be;function se(){return be===void 0&&(be={}),be}Y.fromWeb=function(N,q){return se().newStreamWritableFromWritableStream(N,q)},Y.toWeb=function(N){return se().newWritableStreamFromStreamWritable(N)}}),uu=fe((i,e)=>{le(),ue(),ce();var t=jt(),r=(He(),je(qe)),{isReadable:o,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:h}=gt(),g=It(),{AbortError:p,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ye(),{destroyer:w}=Vt(),m=bt(),k=Tr(),x=Ii(),{createDeferredPromise:v}=Xe(),S=xs(),E=globalThis.Blob||r.Blob,I=typeof E<"u"?function(L){return L instanceof E}:function(L){return!1},P=globalThis.AbortController||sr().AbortController,{FunctionPrototypeCall:O}=Be(),U=class extends m{constructor(L){super(L),L?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),L?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function L(D,oe){if(u(D))return D;if(l(D))return F({readable:D});if(c(D))return F({writable:D});if(a(D))return F({writable:!1,readable:!1});if(d(D))return F({readable:k.fromWeb(D)});if(h(D))return F({writable:x.fromWeb(D)});if(typeof D=="function"){let{value:W,write:ee,final:$,destroy:X}=T(D);if(s(W))return S(U,W,{objectMode:!0,write:ee,final:$,destroy:X});let M=W?.then;if(typeof M=="function"){let J,ge=O(M,W,re=>{if(re!=null)throw new y("nully","body",re)},re=>{w(J,re)});return J=new U({objectMode:!0,readable:!1,write:ee,final(re){$(async()=>{try{await ge,t.nextTick(re,null)}catch(we){t.nextTick(re,we)}})},destroy:X})}throw new y("Iterable, AsyncIterable or AsyncFunction",oe,W)}if(I(D))return L(D.arrayBuffer());if(s(D))return S(U,D,{objectMode:!0,writable:!1});if(d(D?.readable)&&h(D?.writable))return U.fromWeb(D);if(typeof D?.writable=="object"||typeof D?.readable=="object"){let W=D!=null&&D.readable?l(D?.readable)?D?.readable:L(D.readable):void 0,ee=D!=null&&D.writable?c(D?.writable)?D?.writable:L(D.writable):void 0;return F({readable:W,writable:ee})}let Y=D?.then;if(typeof Y=="function"){let W;return O(Y,D,ee=>{ee!=null&&W.push(ee),W.push(null)},ee=>{w(W,ee)}),W=new U({objectMode:!0,writable:!1,read(){}})}throw new b(oe,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],D)};function T(L){let{promise:D,resolve:oe}=v(),Y=new P,W=Y.signal;return{value:L((async function*(){for(;;){let ee=D;D=null;let{chunk:$,done:X,cb:M}=await ee;if(t.nextTick(M),X)return;if(W.aborted)throw new p(void 0,{cause:W.reason});({promise:D,resolve:oe}=v()),yield $}})(),{signal:W}),write(ee,$,X){let M=oe;oe=null,M({chunk:ee,done:!1,cb:X})},final(ee){let $=oe;oe=null,$({done:!0,cb:ee})},destroy(ee,$){Y.abort(),$(ee)}}}function F(L){let D=L.readable&&typeof L.readable.read!="function"?k.wrap(L.readable):L.readable,oe=L.writable,Y=!!o(D),W=!!n(oe),ee,$,X,M,J;function ge(re){let we=M;M=null,we?we(re):re&&J.destroy(re)}return J=new U({readableObjectMode:!!(D!=null&&D.readableObjectMode),writableObjectMode:!!(oe!=null&&oe.writableObjectMode),readable:Y,writable:W}),W&&(g(oe,re=>{W=!1,re&&w(D,re),ge(re)}),J._write=function(re,we,K){oe.write(re,we)?K():ee=K},J._final=function(re){oe.end(),$=re},oe.on("drain",function(){if(ee){let re=ee;ee=null,re()}}),oe.on("finish",function(){if($){let re=$;$=null,re()}})),Y&&(g(D,re=>{Y=!1,re&&w(D,re),ge(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 p),X=null,ee=null,$=null,M===null?we(re):(M=we,w(oe,re),w(D,re))},J}}),bt=fe((i,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:o,ObjectSetPrototypeOf:n}=Be();e.exports=l;var s=Tr(),a=Ii();n(l.prototype,s.prototype),n(l,s);{let h=o(a.prototype);for(let g=0;g<h.length;g++){let p=h[g];l.prototype[p]||(l.prototype[p]=a.prototype[p])}}function l(h){if(!(this instanceof l))return new l(h);s.call(this,h),a.call(this,h),h?(this.allowHalfOpen=h.allowHalfOpen!==!1,h.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),h.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(h){this._readableState&&this._writableState&&(this._readableState.destroyed=h,this._writableState.destroyed=h)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(h,g){return u().newStreamDuplexFromReadableWritablePair(h,g)},l.toWeb=function(h){return u().newReadableWritablePairFromDuplex(h)};var d;l.from=function(h){return d||(d=uu()),d(h,"body")}}),Ss=fe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Be();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:o}=Ye().codes,n=bt(),{getHighWaterMark:s}=Ir();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let h=d?s(this,d,"readableHighWaterMark",!0):null;h===0&&(d={...d,highWaterMark:null,readableHighWaterMark:h,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((h,g)=>{if(h){d?d(h):this.destroy(h);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,h,g){throw new o("_transform()")},l.prototype._write=function(d,h,g){let p=this._readableState,b=this._writableState,y=p.length;this._transform(d,h,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===p.length||p.length<p.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),Es=fe((i,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Be();e.exports=o;var r=Ss();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)}}),Ti=fe((i,e)=>{le(),ue(),ce();var t=jt(),{ArrayIsArray:r,Promise:o,SymbolAsyncIterator:n,SymbolDispose:s}=Be(),a=It(),{once:l}=Xe(),c=Vt(),u=bt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:h,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:p,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ye(),{validateFunction:m,validateAbortSignal:k}=lr(),{isIterable:x,isReadable:v,isReadableNodeStream:S,isNodeStream:E,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:U}=gt(),T=globalThis.AbortController||sr().AbortController,F,L,D;function oe(re,we,K){let j=!1;re.on("close",()=>{j=!0});let ne=a(re,{readable:we,writable:K},z=>{j=!z});return{destroy:z=>{j||(j=!0,c.destroyer(re,z||new b("pipe")))},cleanup:ne}}function Y(re){return m(re[re.length-1],"streams[stream.length - 1]"),re.pop()}function W(re){if(x(re))return re;if(S(re))return ee(re);throw new h("val",["Readable","Iterable","AsyncIterable"],re)}async function*ee(re){L||(L=Tr()),yield*L.prototype[n].call(re)}async function $(re,we,K,{end:j}){let ne,z=null,G=se=>{if(se&&(ne=se),z){let N=z;z=null,N()}},Q=()=>new o((se,N)=>{ne?N(ne):z=()=>{ne?N(ne):se()}});we.on("drain",G);let be=a(we,{readable:!1},G);try{we.writableNeedDrain&&await Q();for await(let se of re)we.write(se)||await Q();j&&(we.end(),await Q()),K()}catch(se){K(ne!==se?d(ne,se):se)}finally{be(),we.off("drain",G)}}async function X(re,we,K,{end:j}){I(we)&&(we=we.writable);let ne=we.getWriter();try{for await(let z of re)await ne.ready,ne.write(z).catch(()=>{});await ne.ready,j&&await ne.close(),K()}catch(z){try{await ne.abort(z),K(z)}catch(G){K(G)}}}function M(...re){return J(re,l(Y(re)))}function J(re,we,K){if(re.length===1&&r(re[0])&&(re=re[0]),re.length<2)throw new p("streams");let j=new T,ne=j.signal,z=K?.signal,G=[];k(z,"options.signal");function Q(){pe(new w)}D=D||Xe().addAbortListener;let be;z&&(be=D(z,Q));let se,N,q=[],te=0;function he(ve){pe(ve,--te===0)}function pe(ve,ae){var Le;if(ve&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=ve),!(!se&&!ae)){for(;q.length;)q.shift()(se);(Le=be)===null||Le===void 0||Le[s](),j.abort(),ae&&(se||G.forEach(f=>f()),t.nextTick(we,se,N))}}let ye;for(let ve=0;ve<re.length;ve++){let ae=re[ve],Le=ve<re.length-1,f=ve>0,_=Le||K?.end!==!1,A=ve===re.length-1;if(E(ae)){let B=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(Z)};if(_){let{destroy:Z,cleanup:de}=oe(ae,Le,f);q.push(Z),v(ae)&&A&&G.push(de)}ae.on("error",B),v(ae)&&A&&G.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}),Le){if(!x(ye,!0))throw new g("AsyncIterable",`transform[${ve-1}]`,ye)}else{var me;F||(F=Es());let B=new F({objectMode:!0}),Z=(me=ye)===null||me===void 0?void 0:me.then;if(typeof Z=="function")te++,Z.call(ye,V=>{N=V,V!=null&&B.write(V),_&&B.end(),t.nextTick(he)},V=>{B.destroy(V),t.nextTick(he,V)});else if(x(ye,!0))te++,$(ye,B,he,{end:_});else if(O(ye)||I(ye)){let V=ye.readable||ye;te++,$(V,B,he,{end:_})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:_e}=oe(ye,!1,!0);q.push(de),A&&G.push(_e)}}else if(E(ae)){if(S(ye)){te+=2;let B=ge(ye,ae,he,{end:_});v(ae)&&A&&G.push(B)}else if(I(ye)||O(ye)){let B=ye.readable||ye;te++,$(B,ae,he,{end:_})}else if(x(ye))te++,$(ye,ae,he,{end:_});else throw new h("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(P(ae)){if(S(ye))te++,X(W(ye),ae,he,{end:_});else if(O(ye)||x(ye))te++,X(ye,ae,he,{end:_});else if(I(ye))te++,X(ye.readable,ae,he,{end:_});else throw new h("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(Q),ye}function ge(re,we,K,{end:j}){let ne=!1;if(we.on("close",()=>{ne||K(new y)}),re.pipe(we,{end:!1}),j){let z=function(){ne=!0,we.end()};U(re)?t.nextTick(z):re.once("end",z)}else K();return a(re,{readable:!0,writable:!1},z=>{let G=re._readableState;z&&z.code==="ERR_STREAM_PREMATURE_CLOSE"&&G&&G.ended&&!G.errored&&!G.errorEmitted?re.once("end",K).once("error",K):K(z)}),a(we,{readable:!1,writable:!0},K)}e.exports={pipelineImpl:J,pipeline:M}}),As=fe((i,e)=>{le(),ue(),ce();var{pipeline:t}=Ti(),r=bt(),{destroyer:o}=Vt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=gt(),{AbortError:h,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:p}}=Ye(),b=It();e.exports=function(...y){if(y.length===0)throw new p("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,k,x,v,S;function E(T){let F=v;v=null,F?F(T):T?S.destroy(T):!U&&!O&&S.destroy()}let I=y[0],P=t(y,E),O=!!(a(I)||u(I)||c(I)),U=!!(s(P)||d(P)||c(P));if(S=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:U}),O){if(n(I))S._write=function(F,L,D){I.write(F,L)?D():m=D},S._final=function(F){I.end(),k=F},I.on("drain",function(){if(m){let F=m;m=null,F()}});else if(l(I)){let F=(c(I)?I.writable:I).getWriter();S._write=async function(L,D,oe){try{await F.ready,F.write(L).catch(()=>{}),oe()}catch(Y){oe(Y)}},S._final=async function(L){try{await F.ready,F.close().catch(()=>{}),k=L}catch(D){L(D)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let F=k;k=null,F()}})}if(U){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:F,done:L}=await T.read();if(!S.push(F))return;if(L){S.push(null);return}}catch{return}}}}return S._destroy=function(T,F){!T&&v!==null&&(T=new h),x=null,m=null,k=null,v===null?F(T):(v=F,n(P)&&o(P,T))},S}}),du=fe((i,e)=>{le(),ue(),ce();var t=globalThis.AbortController||sr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ye(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=lr(),d=Be().Symbol("kWeak"),h=Be().Symbol("kResistStopPropagation"),{finished:g}=It(),p=As(),{addAbortSignalNoValidate:b}=Ar(),{isWritable:y,isNodeStream:w}=gt(),{deprecate:m}=Xe(),{ArrayPrototypePush:k,Boolean:x,MathFloor:v,Number:S,NumberIsNaN:E,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:U,Symbol:T}=Be(),F=T("kEmpty"),L=T("kEof");function D(z,G){if(G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),w(z)&&!y(z))throw new r("stream",z,"must be writable");let Q=p(this,z);return G!=null&&G.signal&&b(G.signal,Q),Q}function oe(z,G){if(typeof z!="function")throw new o("fn",["Function","AsyncFunction"],z);G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal");let Q=1;G?.concurrency!=null&&(Q=v(G.concurrency));let be=Q-1;return G?.highWaterMark!=null&&(be=v(G.highWaterMark)),c(Q,"options.concurrency",1),c(be,"options.highWaterMark",0),be+=Q,(async function*(){let se=Xe().AbortSignalAny([G?.signal].filter(x)),N=this,q=[],te={signal:se},he,pe,ye=!1,H=0;function me(){ye=!0,ve()}function ve(){H-=1,ae()}function ae(){pe&&!ye&&H<Q&&q.length<be&&(pe(),pe=null)}async function Le(){try{for await(let f of N){if(ye)return;if(se.aborted)throw new a;try{if(f=z(f,te),f===F)continue;f=O(f)}catch(_){f=P(_)}H+=1,U(f,ve,me),q.push(f),he&&(he(),he=null),!ye&&(q.length>=be||H>=Q)&&await new I(_=>{pe=_})}q.push(L)}catch(f){let _=P(f);U(_,ve,me),q.push(_)}finally{ye=!0,he&&(he(),he=null)}}Le();try{for(;;){for(;q.length>0;){let f=await q[0];if(f===L)return;if(se.aborted)throw new a;f!==F&&(yield f),q.shift(),ae()}await new I(f=>{he=f})}}finally{ye=!0,pe&&(pe(),pe=null)}}).call(this)}function Y(z=void 0){return z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal"),(async function*(){let G=0;for await(let be of this){var Q;if(z!=null&&(Q=z.signal)!==null&&Q!==void 0&&Q.aborted)throw new a({cause:z.signal.reason});yield[G++,be]}}).call(this)}async function W(z,G=void 0){for await(let Q of M.call(this,z,G))return!0;return!1}async function ee(z,G=void 0){if(typeof z!="function")throw new o("fn",["Function","AsyncFunction"],z);return!await W.call(this,async(...Q)=>!await z(...Q),G)}async function $(z,G){for await(let Q of M.call(this,z,G))return Q}async function X(z,G){if(typeof z!="function")throw new o("fn",["Function","AsyncFunction"],z);async function Q(be,se){return await z(be,se),F}for await(let be of oe.call(this,Q,G));}function M(z,G){if(typeof z!="function")throw new o("fn",["Function","AsyncFunction"],z);async function Q(be,se){return await z(be,se)?be:F}return oe.call(this,Q,G)}var J=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function ge(z,G,Q){var be;if(typeof z!="function")throw new o("reducer",["Function","AsyncFunction"],z);Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal");let se=arguments.length>1;if(Q!=null&&(be=Q.signal)!==null&&be!==void 0&&be.aborted){let pe=new a(void 0,{cause:Q.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(pe)),pe}let N=new t,q=N.signal;if(Q!=null&&Q.signal){let pe={once:!0,[d]:this,[h]:!0};Q.signal.addEventListener("abort",()=>N.abort(),pe)}let te=!1;try{for await(let pe of this){var he;if(te=!0,Q!=null&&(he=Q.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?G=await z(G,pe,{signal:q}):(G=pe,se=!0)}if(!te&&!se)throw new J}finally{N.abort()}return G}async function re(z){z!=null&&u(z,"options"),z?.signal!=null&&l(z.signal,"options.signal");let G=[];for await(let be of this){var Q;if(z!=null&&(Q=z.signal)!==null&&Q!==void 0&&Q.aborted)throw new a(void 0,{cause:z.signal.reason});k(G,be)}return G}function we(z,G){let Q=oe.call(this,z,G);return(async function*(){for await(let be of Q)yield*be}).call(this)}function K(z){if(z=S(z),E(z))return 0;if(z<0)throw new s("number",">= 0",z);return z}function j(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new a;for await(let se of this){var be;if(G!=null&&(be=G.signal)!==null&&be!==void 0&&be.aborted)throw new a;z--<=0&&(yield se)}}).call(this)}function ne(z,G=void 0){return G!=null&&u(G,"options"),G?.signal!=null&&l(G.signal,"options.signal"),z=K(z),(async function*(){var Q;if(G!=null&&(Q=G.signal)!==null&&Q!==void 0&&Q.aborted)throw new a;for await(let se of this){var be;if(G!=null&&(be=G.signal)!==null&&be!==void 0&&be.aborted)throw new a;if(z-- >0&&(yield se),z<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(Y,"readable.asIndexedPairs will be removed in a future version."),drop:j,filter:M,flatMap:we,map:oe,take:ne,compose:D},e.exports.promiseReturningOperators={every:ee,forEach:X,reduce:ge,toArray:re,some:W,find:$}}),Is=fe((i,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Be(),{isIterable:o,isNodeStream:n,isWebStream:s}=gt(),{pipelineImpl:a}=Ti(),{finished:l}=It();Ts();function c(...u){return new r((d,h)=>{let g,p,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!o(b)&&!s(b)){let y=t(u);g=y.signal,p=y.end}a(u,(y,w)=>{y?h(y):d(w)},{signal:g,end:p})})}e.exports={finished:l,pipeline:c}}),Ts=fe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),{ObjectDefineProperty:r,ObjectKeys:o,ReflectApply:n}=Be(),{promisify:{custom:s}}=Xe(),{streamReturningOperators:a,promiseReturningOperators:l}=du(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ye(),u=As(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:h}=Ir(),{pipeline:g}=Ti(),{destroyer:p}=Vt(),b=It(),y=Is(),w=gt(),m=e.exports=Ai().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=Tr();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=Ii(),m.Duplex=bt(),m.Transform=Ss(),m.PassThrough=Es(),m.pipeline=g;var{addAbortSignal:k}=Ar();m.addAbortSignal=k,m.finished=b,m.destroy=p,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=h,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)}}),Dt=fe((i,e)=>{le(),ue(),ce();var t=Ts(),r=Is(),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}),hu=fe((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}}}),pu=fe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),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,h=d,g=c&&s||0,p=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(h<=this._bufs[u[0]].length-p)return c?this._bufs[u[0]].copy(n,s,p,p+h):this._bufs[u[0]].slice(p,p+h);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-p;if(h>y)this._bufs[b].copy(n,g,p),g+=y;else{this._bufs[b].copy(n,g,p,p+h),g+=y;break}h-=y,p&&(p=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 h=d.indexOf(n,u);if(h!==-1)return this._reverseOffset([c,h]);u=d.length-n.length+1}else{let h=this._reverseOffset([c,u]);if(this._match(h,n))return h;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}),fu=fe((i,e)=>{le(),ue(),ce();var t=Dt().Duplex,r=hu(),o=pu();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}),mu=fe((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}),Cs=fe((i,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(He(),je(qe));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"}}),gu=fe((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(h,g){g=g||{};var p=typeof h;if(p==="string"&&h.length>0)return l(h);if(p==="number"&&isFinite(h))return g.long?u(h):c(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function l(h){if(h=String(h),!(h.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(h);if(g){var p=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return p*a;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*n;case"hours":case"hour":case"hrs":case"hr":case"h":return p*o;case"minutes":case"minute":case"mins":case"min":case"m":return p*r;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(h){var g=Math.abs(h);return g>=n?Math.round(h/n)+"d":g>=o?Math.round(h/o)+"h":g>=r?Math.round(h/r)+"m":g>=t?Math.round(h/t)+"s":h+"ms"}function u(h){var g=Math.abs(h);return g>=n?d(h,g,n,"day"):g>=o?d(h,g,o,"hour"):g>=r?d(h,g,r,"minute"):g>=t?d(h,g,t,"second"):h+" ms"}function d(h,g,p,b){var y=g>=p*1.5;return Math.round(h/p)+" "+b+(y?"s":"")}}),bu=fe((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=gu(),n.destroy=h,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function o(g){let p=0;for(let b=0;b<g.length;b++)p=(p<<5)-p+g.charCodeAt(b),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=o;function n(g){let p,b=null,y,w;function m(...k){if(!m.enabled)return;let x=m,v=Number(new Date),S=v-(p||v);x.diff=S,x.prev=p,x.curr=v,p=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";E++;let O=n.formatters[P];if(typeof O=="function"){let U=k[E];I=O.call(x,U),k.splice(E,1),E--}return I}),n.formatArgs.call(x,k),(x.log||n.log).apply(x,k)}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:k=>{b=k}}),typeof n.init=="function"&&n.init(m),m}function s(g,p){let b=n(this.namespace+(typeof p>"u"?":":p)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let p=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of p)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,p){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<p.length&&(p[y]===g[b]||p[y]==="*"))p[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<p.length&&p[y]==="*";)y++;return y===p.length}function c(){let g=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),g}function u(g){for(let p of n.skips)if(l(g,p))return!1;for(let p of n.names)if(l(g,p))return!0;return!1}function d(g){return g instanceof Error?g.stack||g.message:g}function h(){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}),yt=fe((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,h=>{h!=="%%"&&(u++,h==="%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 De<"u"&&"env"in De&&(l=De.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=bu()(i);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),yu=fe((i,e)=>{le(),ue(),ce();var t=fu(),{EventEmitter:r}=(Rt(),je(At)),o=mu(),n=Cs(),s=yt()("mqtt-packet:parser"),a=class Wo extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Wo?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Wo().parser(c)}_resetState(){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,h=n.requiredHeaderFlags[u];return h!=null&&d!==h?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,h,g={},p=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(p.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(p.protocolVersion=this._list.readUInt8(this._pos),p.protocolVersion>=128&&(p.bridgeMode=!0,p.protocolVersion=p.protocolVersion-128),p.protocolVersion!==3&&p.protocolVersion!==4&&p.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)p.will={},p.will.retain=y,p.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(p.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,p.keepalive=this._parseNum(),p.keepalive===-1)return this._emitError(new Error("Packet too short"));if(p.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(p.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(p.clientId=m,s("_parseConnect: packet.clientId: %s",p.clientId),g.will){if(p.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(p.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(p.will.topic=c,s("_parseConnect: packet.will.topic: %s",p.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));p.will.payload=u,s("_parseConnect: packet.will.paylaod: %s",p.will.payload)}if(g.username){if(h=this._parseString(),h===null)return this._emitError(new Error("Cannot parse username"));p.username=h,s("_parseConnect: packet.username: %s",p.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));p.password=d}return this.settings=p,s("_parseConnect: complete"),p}_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,h,g,p,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(h=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,h>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,p=(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:h},this.settings.protocolVersion===5?(y.nl=b,y.rap=p,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 h=this._list.toString("utf8",this._pos,d);return this._pos+=u,s("_parseString: result: %s",h),h}_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,h=1,g=0,p=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=h*(b&n.VARBYTEINT_MASK),h*=128,(b&n.VARBYTEINT_FIN_MASK)===0){p=!0;break}if(this._list.length<=d)break}return!p&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),p?c?p={bytes:d,value:g}:p=g:p=!1,s("_parseVarByteNum: result: %o",p),p}_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 h=this._parseByte();if(!h)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[h];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let p=this._parseByType(n.propertiesTypes[g]);if(d[g][p.name])if(Array.isArray(d[g][p.name]))d[g][p.name].push(p.value);else{let b=d[g][p.name];d[g][p.name]=[b],d[g][p.name].push(p.value)}else d[g][p.name]=p.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}),vu=fe((i,e)=>{le(),ue(),ce();var{Buffer:t}=(He(),je(qe)),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,h=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,h++);while(u>0&&h<4);return u>0&&(h=0),n?g.subarray(0,h):g.slice(0,h)}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}}),wu=fe((i,e)=>{le(),ue(),ce(),typeof De>"u"||!De.version||De.version.indexOf("v0.")===0||De.version.indexOf("v1.")===0&&De.version.indexOf("v1.8.")!==0?e.exports={nextTick:t}:e.exports=De;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 De.nextTick(r);case 2:return De.nextTick(function(){r.call(null,o)});case 3:return De.nextTick(function(){r.call(null,o,n)});case 4:return De.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 De.nextTick(function(){r.apply(null,l)})}}}),Ps=fe((i,e)=>{le(),ue(),ce();var t=Cs(),{Buffer:r}=(He(),je(qe)),o=r.allocUnsafe(0),n=r.from([0]),s=vu(),a=wu().nextTick,l=yt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,h=s.genBufVariableByteInt,g=s.generate4ByteBuffer,p=Y,b=!0;function y(K,j,ne){switch(l("generate called"),j.cork&&(j.cork(),a(w,j)),b&&(b=!1,d()),l("generate: packet.cmd: %s",K.cmd),K.cmd){case"connect":return m(K,j);case"connack":return k(K,j,ne);case"publish":return x(K,j,ne);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(K,j,ne);case"subscribe":return S(K,j,ne);case"suback":return E(K,j,ne);case"unsubscribe":return I(K,j,ne);case"unsuback":return P(K,j,ne);case"pingreq":case"pingresp":return O(K,j);case"disconnect":return U(K,j,ne);case"auth":return T(K,j,ne);default:return j.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return p===Y},set(K){K?((!c||Object.keys(c).length===0)&&(b=!0),p=Y):(b=!1,p=W)}});function w(K){K.uncork()}function m(K,j,ne){let z=K||{},G=z.protocolId||"MQTT",Q=z.protocolVersion||4,be=z.will,se=z.clean,N=z.keepalive||0,q=z.clientId||"",te=z.username,he=z.password,pe=z.properties;se===void 0&&(se=!0);let ye=0;if(typeof G!="string"&&!r.isBuffer(G))return j.destroy(new Error("Invalid protocolId")),!1;if(ye+=G.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 N!="number"||N<0||N>65535||N%1!==0)return j.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,me;if(Q===5){if(H=X(j,pe),!H)return!1;ye+=H.length}if(be){if(typeof be!="object")return j.destroy(new Error("Invalid will")),!1;if(!be.topic||typeof be.topic!="string")return j.destroy(new Error("Invalid will topic")),!1;if(ye+=r.byteLength(be.topic)+2,ye+=2,be.payload)if(be.payload.length>=0)typeof be.payload=="string"?ye+=r.byteLength(be.payload):ye+=be.payload.length;else return j.destroy(new Error("Invalid will payload")),!1;if(me={},Q===5){if(me=X(j,be.properties),!me)return!1;ye+=me.length}}let ve=!1;if(te!=null)if(we(te))ve=!0,ye+=r.byteLength(te)+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),L(j,ye),$(j,G),z.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|=te!=null?t.USERNAME_MASK:0,ae|=he!=null?t.PASSWORD_MASK:0,ae|=be&&be.retain?t.WILL_RETAIN_MASK:0,ae|=be&&be.qos?be.qos<<t.WILL_QOS_SHIFT:0,ae|=be?t.WILL_FLAG_MASK:0,ae|=se?t.CLEAN_SESSION_MASK:0,j.write(r.from([ae])),p(j,N),Q===5&&H.write(),$(j,q),be&&(Q===5&&me.write(),D(j,be.topic),$(j,be.payload)),te!=null&&$(j,te),he!=null&&$(j,he),!0}function k(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=z===5?G.reasonCode:G.returnCode,be=G.properties,se=2;if(typeof Q!="number")return j.destroy(new Error("Invalid return code")),!1;let N=null;if(z===5){if(N=X(j,be),!N)return!1;se+=N.length}return j.write(t.CONNACK_HEADER),L(j,se),j.write(G.sessionPresent?t.SESSIONPRESENT_HEADER:n),j.write(r.from([Q])),N?.write(),!0}function x(K,j,ne){l("publish: packet: %o",K);let z=ne?ne.protocolVersion:4,G=K||{},Q=G.qos||0,be=G.retain?t.RETAIN_MASK:0,se=G.topic,N=G.payload||o,q=G.messageId,te=G.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(N)?he+=N.length:he+=r.byteLength(N),Q&&typeof q!="number")return j.destroy(new Error("Invalid messageId")),!1;Q&&(he+=2);let pe=null;if(z===5){if(pe=X(j,te),!pe)return!1;he+=pe.length}return j.write(t.PUBLISH_HEADER[Q][G.dup?1:0][be?1:0]),L(j,he),p(j,re(se)),j.write(se),Q>0&&p(j,q),pe?.write(),l("publish: payload: %o",N),j.write(N)}function v(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.cmd||"puback",be=G.messageId,se=G.dup&&Q==="pubrel"?t.DUP_MASK:0,N=0,q=G.reasonCode,te=G.properties,he=z===5?3:2;if(Q==="pubrel"&&(N=1),typeof be!="number")return j.destroy(new Error("Invalid messageId")),!1;let pe=null;if(z===5&&typeof te=="object"){if(pe=M(j,te,ne,he),!pe)return!1;he+=pe.length}return j.write(t.ACKS[Q][N][se][0]),he===3&&(he+=q!==0?1:-1),L(j,he),p(j,be),z===5&&he!==2&&j.write(r.from([q])),pe!==null?pe.write():he===4&&j.write(r.from([0])),!0}function S(K,j,ne){l("subscribe: packet: ");let z=ne?ne.protocolVersion:4,G=K||{},Q=G.dup?t.DUP_MASK:0,be=G.messageId,se=G.subscriptions,N=G.properties,q=0;if(typeof be!="number")return j.destroy(new Error("Invalid messageId")),!1;q+=2;let te=null;if(z===5){if(te=X(j,N),!te)return!1;q+=te.length}if(typeof se=="object"&&se.length)for(let pe=0;pe<se.length;pe+=1){let ye=se[pe].topic,H=se[pe].qos;if(typeof ye!="string")return j.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return j.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(z===5){if(typeof(se[pe].nl||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[pe].rap||!1)!="boolean")return j.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let me=se[pe].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]),L(j,q),p(j,be),te!==null&&te.write();let he=!0;for(let pe of se){let ye=pe.topic,H=pe.qos,me=+pe.nl,ve=+pe.rap,ae=pe.rh,Le;D(j,ye),Le=t.SUBSCRIBE_OPTIONS_QOS[H],z===5&&(Le|=me?t.SUBSCRIBE_OPTIONS_NL:0,Le|=ve?t.SUBSCRIBE_OPTIONS_RAP:0,Le|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=j.write(r.from([Le]))}return he}function E(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.messageId,be=G.granted,se=G.properties,N=0;if(typeof Q!="number")return j.destroy(new Error("Invalid messageId")),!1;if(N+=2,typeof be=="object"&&be.length)for(let te=0;te<be.length;te+=1){if(typeof be[te]!="number")return j.destroy(new Error("Invalid qos vector")),!1;N+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let q=null;if(z===5){if(q=M(j,se,ne,N),!q)return!1;N+=q.length}return j.write(t.SUBACK_HEADER),L(j,N),p(j,Q),q!==null&&q.write(),j.write(r.from(be))}function I(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.messageId,be=G.dup?t.DUP_MASK:0,se=G.unsubscriptions,N=G.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 pe=0;pe<se.length;pe+=1){if(typeof se[pe]!="string")return j.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[pe])+2}else return j.destroy(new Error("Invalid unsubscriptions")),!1;let te=null;if(z===5){if(te=X(j,N),!te)return!1;q+=te.length}j.write(t.UNSUBSCRIBE_HEADER[1][be?1:0][0]),L(j,q),p(j,Q),te!==null&&te.write();let he=!0;for(let pe=0;pe<se.length;pe++)he=D(j,se[pe]);return he}function P(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.messageId,be=G.dup?t.DUP_MASK:0,se=G.granted,N=G.properties,q=G.cmd,te=0,he=2;if(typeof Q!="number")return j.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 j.destroy(new Error("Invalid qos vector")),!1;he+=1}else return j.destroy(new Error("Invalid qos vector")),!1;let pe=null;if(z===5){if(pe=M(j,N,ne,he),!pe)return!1;he+=pe.length}return j.write(t.ACKS[q][te][be][0]),L(j,he),p(j,Q),pe!==null&&pe.write(),z===5&&j.write(r.from(se)),!0}function O(K,j,ne){return j.write(t.EMPTY[K.cmd])}function U(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.reasonCode,be=G.properties,se=z===5?1:0,N=null;if(z===5){if(N=M(j,be,ne,se),!N)return!1;se+=N.length}return j.write(r.from([t.codes.disconnect<<4])),L(j,se),z===5&&j.write(r.from([Q])),N!==null&&N.write(),!0}function T(K,j,ne){let z=ne?ne.protocolVersion:4,G=K||{},Q=G.reasonCode,be=G.properties,se=z===5?1:0;z!==5&&j.destroy(new Error("Invalid mqtt version for auth packet"));let N=M(j,be,ne,se);return N?(se+=N.length,j.write(r.from([t.codes.auth<<4])),L(j,se),j.write(r.from([Q])),N!==null&&N.write(),!0):!1}var F={};function L(K,j){if(j>t.VARBYTEINT_MAX)return K.destroy(new Error(`Invalid variable byte integer: ${j}`)),!1;let ne=F[j];return ne||(ne=h(j),j<16384&&(F[j]=ne)),l("writeVarByteInt: writing to stream: %o",ne),K.write(ne)}function D(K,j){let ne=r.byteLength(j);return p(K,ne),l("writeString: %s",j),K.write(j,"utf8")}function oe(K,j,ne){D(K,j),D(K,ne)}function Y(K,j){return l("writeNumberCached: number: %d",j),l("writeNumberCached: %o",c[j]),K.write(c[j])}function W(K,j){let ne=u(j);return l("writeNumberGenerated: %o",ne),K.write(ne)}function ee(K,j){let ne=g(j);return l("write4ByteNumber: %o",ne),K.write(ne)}function $(K,j){typeof j=="string"?D(K,j):j?(p(K,j.length),K.write(j)):p(K,0)}function X(K,j){if(typeof j!="object"||j.length!=null)return{length:1,write(){ge(K,{},0)}};let ne=0;function z(G,Q){let be=t.propertiesTypes[G],se=0;switch(be){case"byte":{if(typeof Q!="boolean")return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=2;break}case"int8":{if(typeof Q!="number"||Q<0||Q>255)return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=2;break}case"binary":{if(Q&&Q===null)return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=1+r.byteLength(Q)+2;break}case"int16":{if(typeof Q!="number"||Q<0||Q>65535)return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=3;break}case"int32":{if(typeof Q!="number"||Q<0||Q>4294967295)return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=5;break}case"var":{if(typeof Q!="number"||Q<0||Q>268435455)return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=1+r.byteLength(h(Q));break}case"string":{if(typeof Q!="string")return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=3+r.byteLength(Q.toString());break}case"pair":{if(typeof Q!="object")return K.destroy(new Error(`Invalid ${G}: ${Q}`)),!1;se+=Object.getOwnPropertyNames(Q).reduce((N,q)=>{let te=Q[q];return Array.isArray(te)?N+=te.reduce((he,pe)=>(he+=3+r.byteLength(q.toString())+2+r.byteLength(pe.toString()),he),0):N+=3+r.byteLength(q.toString())+2+r.byteLength(Q[q].toString()),N},0);break}default:return K.destroy(new Error(`Invalid property ${G}: ${Q}`)),!1}return se}if(j)for(let G in j){let Q=0,be=0,se=j[G];if(se!==void 0){if(Array.isArray(se))for(let N=0;N<se.length;N++){if(be=z(G,se[N]),!be)return!1;Q+=be}else{if(be=z(G,se),!be)return!1;Q=be}if(!Q)return!1;ne+=Q}}return{length:r.byteLength(h(ne))+ne,write(){ge(K,j,ne)}}}function M(K,j,ne,z){let G=["reasonString","userProperties"],Q=ne&&ne.properties&&ne.properties.maximumPacketSize?ne.properties.maximumPacketSize:0,be=X(K,j);if(Q)for(;z+be.length>Q;){let se=G.shift();if(se&&j[se])delete j[se],be=X(K,j);else return!1}return be}function J(K,j,ne){switch(t.propertiesTypes[j]){case"byte":{K.write(r.from([t.properties[j]])),K.write(r.from([+ne]));break}case"int8":{K.write(r.from([t.properties[j]])),K.write(r.from([ne]));break}case"binary":{K.write(r.from([t.properties[j]])),$(K,ne);break}case"int16":{K.write(r.from([t.properties[j]])),p(K,ne);break}case"int32":{K.write(r.from([t.properties[j]])),ee(K,ne);break}case"var":{K.write(r.from([t.properties[j]])),L(K,ne);break}case"string":{K.write(r.from([t.properties[j]])),D(K,ne);break}case"pair":{Object.getOwnPropertyNames(ne).forEach(z=>{let G=ne[z];Array.isArray(G)?G.forEach(Q=>{K.write(r.from([t.properties[j]])),oe(K,z.toString(),Q.toString())}):(K.write(r.from([t.properties[j]])),oe(K,z.toString(),G.toString()))});break}default:return K.destroy(new Error(`Invalid property ${j} value: ${ne}`)),!1}}function ge(K,j,ne){L(K,ne);for(let z in j)if(Object.prototype.hasOwnProperty.call(j,z)&&j[z]!=null){let G=j[z];if(Array.isArray(G))for(let Q=0;Q<G.length;Q++)J(K,z,G[Q]);else J(K,z,G)}}function re(K){return K?K instanceof r?K.length:r.byteLength(K):0}function we(K){return typeof K=="string"||K instanceof r}e.exports=y}),ku=fe((i,e)=>{le(),ue(),ce();var t=Ps(),{EventEmitter:r}=(Rt(),je(At)),{Buffer:o}=(He(),je(qe));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 h=o.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(h,u),u+=l[d]):(h.write(c[d],u),u+=l[d]);return h}destroy(a){a&&this.emit("error",a)}};e.exports=n}),_u=fe(i=>{le(),ue(),ce(),i.parser=yu().parser,i.generate=ku(),i.writeToStream=Ps()}),xu=fe((i,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Er?Er.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,h)=>new Map(l(Array.from(d),h))),s.set(Set,(d,h)=>new Set(l(Array.from(d),h))),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,h){let g=Object.keys(d),p=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?p[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?p[y]=a(w,h):ArrayBuffer.isView(w)?p[y]=t(w):p[y]=h(w)}return p}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 h={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let p=d[g];typeof p!="object"||p===null?h[g]=p:p.constructor!==Object&&(a=s.get(p.constructor))?h[g]=a(p,c):ArrayBuffer.isView(p)?h[g]=t(p):h[g]=c(p)}return h}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 h={};for(let g in d){let p=d[g];typeof p!="object"||p===null?h[g]=p:p.constructor!==Object&&(a=s.get(p.constructor))?h[g]=a(p,u):ArrayBuffer.isView(p)?h[g]=t(p):h[g]=u(p)}return h}}function o(n){let s=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,p)=>new Map(u(Array.from(g),p))),l.set(Set,(g,p)=>new Set(u(Array.from(g),p))),n.constructorHandlers)for(let g of n.constructorHandlers)l.set(g[0],g[1]);let c=null;return n.proto?h:d;function u(g,p){let b=Object.keys(g),y=new Array(b.length);for(let w=0;w<b.length;w++){let m=b[w],k=g[m];if(typeof k!="object"||k===null)y[m]=k;else if(k.constructor!==Object&&(c=l.get(k.constructor)))y[m]=c(k,p);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let x=s.indexOf(k);x!==-1?y[m]=a[x]:y[m]=p(k)}}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 p={};s.push(g),a.push(p);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)p[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))p[b]=c(y,d);else if(ArrayBuffer.isView(y))p[b]=t(y);else{let w=s.indexOf(y);w!==-1?p[b]=a[w]:p[b]=d(y)}}return s.pop(),a.pop(),p}function h(g){if(typeof g!="object"||g===null)return g;if(Array.isArray(g))return u(g,h);if(g.constructor!==Object&&(c=l.get(g.constructor)))return c(g,h);let p={};s.push(g),a.push(p);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)p[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))p[b]=c(y,h);else if(ArrayBuffer.isView(y))p[b]=t(y);else{let w=s.indexOf(y);w!==-1?p[b]=a[w]:p[b]=h(y)}}return s.pop(),a.pop(),p}}}),Su=fe((i,e)=>{le(),ue(),ce(),e.exports=xu()()}),Os=fe(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}}),Ls=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Dt(),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}),Eu=fe(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 h=r.topicAliasRecv.getTopicByAlias(d);if(h)s=h,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,h)=>{if(typeof d=="number"&&(h=d,d=null),d)return r.emit("error",d);if(e.indexOf(h)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));h?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:h},n):r.incomingStore.put(o,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,o,(d,h)=>{if(typeof d=="number"&&(h=d,d=null),d)return r.emit("error",d);if(e.indexOf(h)===-1)return r.emit("error",new Error("Wrong reason code for puback"));h||r.emit("message",s,a,o),r.handleMessage(o,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:h},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}),Au=fe((i,e)=>{e.exports={version:"5.15.0"}}),Kt=fe(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 Oc extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Oc.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};i.ErrorWithReasonCode=e;var t=class Lc extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,Lc.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 De?.nextTick=="function"?De.nextTick:o=>{setTimeout(o,0)},i.MQTTJS_VERSION=Au().version}),Cr=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=void 0;var e=Kt();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 h=u[d];if((h&128)!==0){c=new Error(`Subscribe error: ${i.ReasonCodes[h]}`),c.code=h;let g=r.messageIdToTopic[n];g&&g.forEach(p=>{delete r._resubscribeTopics[p]})}}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}),Iu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Kt(),t=Cr(),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}),Tu=fe(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 De=="object"&&De?De:{},o=(g,p,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,p,b,y):console.error(`[${b}] ${p}: ${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(){p()}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",p=()=>{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",p))}}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 wr{heap;length;static#l=!1;static create(p){let b=c(p);if(!b)return[];wr.#l=!0;let y=new wr(p,b);return wr.#l=!1,y}constructor(p,b){if(!wr.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(p),this.length=0}push(p){this.heap[this.length++]=p}pop(){return this.heap[--this.length]}},h=class Mc{#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;#p;#k;#A;#u;static unsafeExposeInternals(p){return{starts:p.#w,ttls:p.#p,sizes:p.#v,keyMap:p.#n,keyList:p.#r,valList:p.#e,next:p.#c,prev:p.#h,get head(){return p.#a},get tail(){return p.#o},free:p.#y,isBackgroundFetch:b=>p.#t(b),backgroundFetch:(b,y,w,m)=>p.#N(b,y,w,m),moveToTail:b=>p.#C(b),indexes:b=>p.#_(b),rindexes:b=>p.#x(b),isStale:b=>p.#f(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(p){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:x,allowStale:v,dispose:S,disposeAfter:E,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:U=0,sizeCalculation:T,fetchMethod:F,memoMethod:L,noDeleteOnFetchRejection:D,noDeleteOnStaleGet:oe,allowStaleOnFetchRejection:Y,allowStaleOnFetchAbort:W,ignoreFetchAbort:ee}=p;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let $=b?c(b):Array;if(!$)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=O,this.maxEntrySize=U||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(L!==void 0&&typeof L!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=L,F!==void 0&&typeof F!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#P=F,this.#A=!!F,this.#n=new Map,this.#r=new Array(b).fill(void 0),this.#e=new Array(b).fill(void 0),this.#c=new $(b),this.#h=new $(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.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!D,this.allowStaleOnFetchRejection=!!Y,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!ee,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.#F()}if(this.allowStale=!!v,this.noDeleteOnStaleGet=!!oe,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!x,this.ttlResolution=l(w)||w===0?w:1,this.ttlAutopurge=!!m,this.ttl=y||0,this.ttl){if(!l(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}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,Mc))}}getRemainingTTL(p){return this.#n.has(p)?1/0:0}#R(){let p=new u(this.#l),b=new u(this.#l);this.#p=p,this.#w=b,this.#j=(m,k,x=e.now())=>{if(b[m]=k!==0?x:0,p[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#f(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=p[m]!==0?e.now():0},this.#E=(m,k)=>{if(p[k]){let x=p[k],v=b[k];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 k=setTimeout(()=>y=0,this.ttlResolution);k.unref&&k.unref()}return m};this.getRemainingTTL=m=>{let k=this.#n.get(m);if(k===void 0)return 0;let x=p[k],v=b[k];if(!x||!v)return 1/0;let S=(y||w())-v;return x-S},this.#f=m=>{let k=b[m],x=p[m];return!!x&&!!k&&(y||w())-k>x}}#I=()=>{};#E=()=>{};#j=()=>{};#f=()=>!1;#F(){let p=new u(this.#l);this.#b=0,this.#v=p,this.#T=b=>{this.#b-=p[b],p[b]=0},this.#D=(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.#L=(b,y,w)=>{if(p[b]=y,this.#d){let m=this.#d-p[b];for(;this.#b>m;)this.#M(!0)}this.#b+=p[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=p=>{};#L=(p,b,y)=>{};#D=(p,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:p=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#$(b)||((p||!this.#f(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#x({allowStale:p=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#$(b)||((p||!this.#f(b))&&(yield b),b===this.#o));)b=this.#c[b]}#$(p){return p!==void 0&&this.#n.get(this.#r[p])===p}*entries(){for(let p of this.#_())this.#e[p]!==void 0&&this.#r[p]!==void 0&&!this.#t(this.#e[p])&&(yield[this.#r[p],this.#e[p]])}*rentries(){for(let p of this.#x())this.#e[p]!==void 0&&this.#r[p]!==void 0&&!this.#t(this.#e[p])&&(yield[this.#r[p],this.#e[p]])}*keys(){for(let p of this.#_()){let b=this.#r[p];b!==void 0&&!this.#t(this.#e[p])&&(yield b)}}*rkeys(){for(let p of this.#x()){let b=this.#r[p];b!==void 0&&!this.#t(this.#e[p])&&(yield b)}}*values(){for(let p of this.#_())this.#e[p]!==void 0&&!this.#t(this.#e[p])&&(yield this.#e[p])}*rvalues(){for(let p of this.#x())this.#e[p]!==void 0&&!this.#t(this.#e[p])&&(yield this.#e[p])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(p,b={}){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&p(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(p,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&p.call(b,m,this.#r[y],this)}}rforEach(p,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&p.call(b,m,this.#r[y],this)}}purgeStale(){let p=!1;for(let b of this.#x({allowStale:!0}))this.#f(b)&&(this.#S(this.#r[b],"expire"),p=!0);return p}info(p){let b=this.#n.get(p);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.#p&&this.#w){let k=this.#p[b],x=this.#w[b];if(k&&x){let v=k-(e.now()-x);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let p=[];for(let b of this.#_({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 k={value:m};if(this.#p&&this.#w){k.ttl=this.#p[b];let x=e.now()-this.#w[b];k.start=Math.floor(Date.now()-x)}this.#v&&(k.size=this.#v[b]),p.unshift([y,k])}return p}load(p){this.clear();for(let[b,y]of p){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(p,b,y={}){if(b===void 0)return this.delete(p),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:x=this.sizeCalculation,status:v}=y,{noUpdateTTL:S=this.noUpdateTTL}=y,E=this.#D(p,b,y.size||0,x);if(this.maxEntrySize&&E>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(p,"set"),this;let I=this.#i===0?void 0:this.#n.get(p);if(I===void 0)I=this.#i===0?this.#o:this.#y.length!==0?this.#y.pop():this.#i===this.#l?this.#M(!1):this.#i,this.#r[I]=p,this.#e[I]=b,this.#n.set(p,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#L(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&&!k&&(this.#k&&this.#m?.(O,p,"set"),this.#u&&this.#s?.push([O,p,"set"]))}else k||(this.#k&&this.#m?.(P,p,"set"),this.#u&&this.#s?.push([P,p,"set"]));if(this.#T(I),this.#L(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.#p&&this.#R(),this.#p&&(S||this.#j(I,w,m),v&&this.#E(v,I)),!k&&this.#u&&this.#s){let P=this.#s,O;for(;O=P?.shift();)this.#g?.(...O)}return this}pop(){try{for(;this.#i;){let p=this.#e[this.#a];if(this.#M(!0),this.#t(p)){if(p.__staleWhileFetching)return p.__staleWhileFetching}else if(p!==void 0)return p}}finally{if(this.#u&&this.#s){let p=this.#s,b;for(;b=p?.shift();)this.#g?.(...b)}}}#M(p){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.#k||this.#u)&&(this.#k&&this.#m?.(w,y,"evict"),this.#u&&this.#s?.push([w,y,"evict"])),this.#T(b),p&&(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(p,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(p);if(m!==void 0){let k=this.#e[m];if(this.#t(k)&&k.__staleWhileFetching===void 0)return!1;if(this.#f(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(p,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(p);if(w===void 0||!y&&this.#f(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#N(p,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:x}=y;x?.addEventListener("abort",()=>k.abort(x.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},S=(T,F=!1)=>{let{aborted:L}=k.signal,D=y.ignoreFetchAbort&&T!==void 0;if(y.status&&(L&&!F?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,D&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),L&&!D&&!F)return I(k.signal.reason);let oe=O;return this.#e[b]===O&&(T===void 0?oe.__staleWhileFetching?this.#e[b]=oe.__staleWhileFetching:this.#S(p,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(p,T,v.options))),T},E=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:F}=k.signal,L=F&&y.allowStaleOnFetchAbort,D=L||y.allowStaleOnFetchRejection,oe=D||y.noDeleteOnFetchRejection,Y=O;if(this.#e[b]===O&&(!oe||Y.__staleWhileFetching===void 0?this.#S(p,"fetch"):L||(this.#e[b]=Y.__staleWhileFetching)),D)return y.status&&Y.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),Y.__staleWhileFetching;if(Y.__returned===Y)throw T},P=(T,F)=>{let L=this.#P?.(p,m,v);L&&L instanceof Promise&&L.then(D=>T(D===void 0?void 0:D),F),k.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),U=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(p,U,{...v.options,status:void 0}),b=this.#n.get(p)):this.#e[b]=U,U}#t(p){if(!this.#A)return!1;let b=p;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(p,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=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:U=this.allowStaleOnFetchAbort,context:T,forceRefresh:F=!1,status:L,signal:D}=b;if(!this.#A)return L&&(L.fetch="get"),this.get(p,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:L});let oe={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:x,size:v,sizeCalculation:S,noUpdateTTL:E,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:U,ignoreFetchAbort:O,status:L,signal:D},Y=this.#n.get(p);if(Y===void 0){L&&(L.fetch="miss");let W=this.#N(p,Y,oe,T);return W.__returned=W}else{let W=this.#e[Y];if(this.#t(W)){let M=y&&W.__staleWhileFetching!==void 0;return L&&(L.fetch="inflight",M&&(L.returnedStale=!0)),M?W.__staleWhileFetching:W.__returned=W}let ee=this.#f(Y);if(!F&&!ee)return L&&(L.fetch="hit"),this.#C(Y),w&&this.#I(Y),L&&this.#E(L,Y),W;let $=this.#N(p,Y,oe,T),X=$.__staleWhileFetching!==void 0&&y;return L&&(L.fetch=ee?"stale":"refresh",X&&ee&&(L.returnedStale=!0)),X?$.__staleWhileFetching:$.__returned=$}}async forceFetch(p,b={}){let y=await this.fetch(p,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(p,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,x=this.get(p,k);if(!m&&x!==void 0)return x;let v=y(p,x,{options:k,context:w});return this.set(p,v,k),v}get(p,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,x=this.#n.get(p);if(x!==void 0){let v=this.#e[x],S=this.#t(v);return k&&this.#E(k,x),this.#f(x)?(k&&(k.get="stale"),S?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(p,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),S?v.__staleWhileFetching:(this.#C(x),w&&this.#I(x),v))}else k&&(k.get="miss")}#U(p,b){this.#h[b]=p,this.#c[p]=b}#C(p){p!==this.#o&&(p===this.#a?this.#a=this.#c[p]:this.#U(this.#h[p],this.#c[p]),this.#U(this.#o,p),this.#o=p)}delete(p){return this.#S(p,"delete")}#S(p,b){let y=!1;if(this.#i!==0){let w=this.#n.get(p);if(w!==void 0)if(y=!0,this.#i===1)this.#B(b);else{this.#T(w);let m=this.#e[w];if(this.#t(m)?m.__abortController.abort(new Error("deleted")):(this.#k||this.#u)&&(this.#k&&this.#m?.(m,p,b),this.#u&&this.#s?.push([m,p,b])),this.#n.delete(p),this.#r[w]=void 0,this.#e[w]=void 0,w===this.#o)this.#o=this.#h[w];else if(w===this.#a)this.#a=this.#c[w];else{let k=this.#h[w];this.#c[k]=this.#c[w];let x=this.#c[w];this.#h[x]=this.#h[w]}this.#i--,this.#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.#B("delete")}#B(p){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.#k&&this.#m?.(y,w,p),this.#u&&this.#s?.push([y,w,p])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#p&&this.#w&&(this.#p.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=h}),vt=fe(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}),Cu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=vt(),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}),Pu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=vt(),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}),Ou=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=vt(),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}),Ci=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=vt(),t=class extends e.Container{},r=t;i.default=r}),wt=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Ms=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.RandomIterator=void 0;var e=vt(),t=wt(),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}),Lu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Ci()),t=Ms();function r(a){return a&&a.t?a:{default:a}}var o=class Nc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new Nc(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}),Mu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Ci()),t=vt(),r=wt();function o(l){return l&&l.t?l:{default:l}}var n=class Rc extends t.ContainerIterator{constructor(c,u,d,h){super(h),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 Rc(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 h=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=h,h.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}),Nu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=r(Ci()),t=Ms();function r(a){return a&&a.t?a:{default:a}}var o=class jc extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new jc(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 h=0;h<this.P;++h)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(h){d.pushBack(h)})}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}),Ru=fe(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}),Ns=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ru(),t=vt(),r=wt(),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 h=d.tt;for(;h!==this.h;)h.rt+=1,h=h.tt;let g=this.he(d);if(g){let{parentNode:p,grandParent:b,curNode:y}=g;p.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 h=this.h.W,g=this.v(h.u,s);if(g===0){h.l=a;return}else if(g<0)h.W=new this.re(s,a),h.W.tt=h,c=h.W,this.h.W=c;else{if(l!==void 0){let p=l.o;if(p!==this.h){let b=this.v(p.u,s);if(b===0){p.l=a;return}else if(b>0){let y=p.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):(p.U=c,c.tt=p))}}}if(c===void 0)for(c=this.Y;;){let p=this.v(c.u,s);if(p>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(p<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}),Rs=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=vt(),t=wt(),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}),ju=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Ns()),t=o(Rs()),r=wt();function o(l){return l&&l.t?l:{default:l}}var n=class Dc extends t.default{constructor(c,u,d,h){super(c,u,h),this.container=d}get pointer(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o.u}copy(){return new Dc(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(h){d.insert(h)})}*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}),Du=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=o(Ns()),t=o(Rs()),r=wt();function o(l){return l&&l.t?l:{default:l}}var n=class $c extends t.default{constructor(c,u,d,h){super(c,u,h),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,h){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=h,!0}})}copy(){return new $c(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(h){d.setElement(h[0],h[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}),js=fe(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"}}),Ds=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.HashContainerIterator=i.HashContainer=void 0;var e=vt(),t=o(js()),r=wt();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}),$u=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ds(),t=wt(),r=class Uc 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 Uc(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}),Uu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"t",{value:!0}),i.default=void 0;var e=Ds(),t=o(js()),r=wt();function o(l){return l&&l.t?l:{default:l}}var n=class Bc extends e.HashContainerIterator{constructor(c,u,d,h){super(c,u,h),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,h){if(d!=="1")throw new TypeError("props must be 1");return c.o.l=h,!0}})}copy(){return new Bc(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}),Bu=fe(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(Cu()),t=d(Pu()),r=d(Ou()),o=d(Lu()),n=d(Mu()),s=d(Nu()),a=d(ju()),l=d(Du()),c=d($u()),u=d(Uu());function d(h){return h&&h.t?h:{default:h}}}),Fu=fe((i,e)=>{le(),ue(),ce();var t=Bu().OrderedSet,r=yt()("number-allocator:trace"),o=yt()("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 h=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(h,d))):this.ss.updateKeyByIterator(c,new n(h,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}),$s=fe((i,e)=>{le(),ue(),ce();var t=Fu();e.exports.NumberAllocator=t}),qu=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=Tu(),t=$s(),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}),Hu=fe(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=Cr(),r=e(qu()),o=Kt(),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}),Wu=fe(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}),zu=fe(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(Eu()),r=e(Iu()),o=e(Hu()),n=e(Cr()),s=e(Wu()),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}),Us=fe(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}),Vu=fe(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}),Ku=fe(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((Rt(),je(At))),r=Kt(),o=class{};i.TypedEventEmitter=o,(0,r.applyMixin)(o,t.default)}),Pr=fe((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}),Gu=fe((i,e)=>{le(),ue(),ce();var t=Pr().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}),Yu=fe((i,e)=>{le(),ue(),ce();var t=Pr().default,r=Gu();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}),Ju=fe((i,e)=>{le(),ue(),ce();var t=Yu();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}),Qu=fe((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}),Xu=fe((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,h=!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){h=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(h)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),Zu=fe((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}),ed=fe((i,e)=>{le(),ue(),ce();var t=Zu();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}),td=fe((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}),rd=fe((i,e)=>{le(),ue(),ce();var t=Qu(),r=Xu(),o=ed(),n=td();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}),Bs=fe((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(p){var b=g(p);return p.add(b),b}},o=function(g){return function(p,b){return g.set(p,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,p){return function(b){var y=p.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),h=r(d);t.addUniqueNumber=h,t.generateUniqueNumber=d})}),nd=fe((i,e)=>{le(),ue(),ce();function t(o,n,s,a,l,c,u){try{var d=o[c](u),h=d.value}catch(g){return void s(g)}d.done?n(h):Promise.resolve(h).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(h){t(c,a,l,u,d,"next",h)}function d(h){t(c,a,l,u,d,"throw",h)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),Fs=fe((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}),qs=fe((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 h(g,p){t(l,g,function(b){return this._invoke(g,p,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(h("next",0),h("throw",1),h("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}),Hs=fe((i,e)=>{le(),ue(),ce();var t=qs();function r(){var o,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,k,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,U,T,F=0,L=P||[],D=!1,oe={p:0,n:0,v:o,a:Y,f:Y.bind(o,4),d:function(W,ee){return O=W,U=0,T=o,oe.n=ee,u}};function Y(W,ee){for(U=W,T=ee,n=0;!D&&F&&!$&&n<L.length;n++){var $,X=L[n],M=oe.p,J=X[2];W>3?($=J===ee)&&(T=X[(U=X[4])?5:(U=3,3)],X[4]=X[5]=o):X[0]<=M&&(($=W<2&&M<X[1])?(U=0,oe.v=ee,oe.n=X[1]):M<J&&($=W<3||X[0]>ee||ee>J)&&(X[4]=W,X[5]=ee,oe.n=J,U=0))}if($||W>1)return u;throw D=!0,ee}return function(W,ee,$){if(F>1)throw TypeError("Generator is already running");for(D&&ee===1&&Y(ee,$),U=ee,T=$;(n=U<2?o:T)||!D;){O||(U?U<3?(U>1&&(oe.n=-1),Y(U,T)):oe.n=T:oe.v=T);try{if(F=2,O){if(U||(W="next"),n=O[W]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,U<2&&(U=0)}else U===1&&(n=O.return)&&n.call(O),U<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),U=1);O=o}else if((n=(D=oe.n<0)?T:E.call(I,oe))!==u)break}catch(X){O=o,U=1,T=X}finally{F=1}}return{value:n,done:D}}})(w,k,x),!0),S}var u={};function d(){}function h(){}function g(){}n=Object.getPrototypeOf;var p=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(p);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return h.prototype=g,t(b,"constructor",g),t(g,"constructor",h),h.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}),Ws=fe((i,e)=>{le(),ue(),ce();var t=Fs(),r=qs();function o(n,s){function a(c,u,d,h){try{var g=n[c](u),p=g.value;return p instanceof t?s.resolve(p.v).then(function(b){a("next",b,d,h)},function(b){a("throw",b,d,h)}):s.resolve(p).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,h)})}catch(b){h(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 h(){return new s(function(g,p){a(c,d,g,p)})}return l=l?l.then(h,h):h()},!0)}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}),zs=fe((i,e)=>{le(),ue(),ce();var t=Hs(),r=Ws();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}),id=fe((i,e)=>{le(),ue(),ce();var t=zs();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}),od=fe((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}),sd=fe((i,e)=>{le(),ue(),ce();var t=Pr().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}),ad=fe((i,e)=>{le(),ue(),ce();var t=Fs(),r=Hs(),o=id(),n=zs(),s=Ws(),a=od(),l=sd();function c(){var u=r(),d=u.m(c),h=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===h||(w.displayName||w.name)==="GeneratorFunction")}var p={throw:1,return:2,break:3,continue:3};function b(y){var w,m;return function(k){w||(w={stop:function(){return m(k.a,2)},catch:function(){return k.v},abrupt:function(x,v){return m(k.a,p[x],v)},delegateYield:function(x,v,S){return w.resultName=v,m(k.d,l(x),S)},finish:function(x){return m(k.f,x)}},m=function(x,v,S){k.p=w.prev,k.n=w.next;try{return x(v,S)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return y.call(this,w)}finally{k.p=w.prev,k.n=w.next}}}return(e.exports=c=function(){return{wrap:function(y,w,m,k){return u.w(b(y),w,m,k&&k.reverse())},isGeneratorFunction:g,mark:u.m,awrap:function(y,w){return new t(y,w)},AsyncIterator:s,async:function(y,w,m,k,x){return(g(w)?n:o)(b(y),w,m,k,x)},keys:a,values:l}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}),ld=fe((i,e)=>{le(),ue(),ce();var t=ad()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),cd=fe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Ju(),rd(),Bs(),nd(),ld()):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,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function d(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%2?u(Object(x),!0).forEach(function(v){r(m,v,x[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(x)):u(Object(x)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(x,v))})}return m}var h=function(m){return d(d({},m),{},{connect:function(k){var x=k.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(k){var x=k.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(k){var x=k.call;return function(){return x("isSupported")}}})};function g(m,k){var x=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),x.push.apply(x,v)}return x}function p(m){for(var k=1;k<arguments.length;k++){var x=arguments[k]!=null?arguments[k]:{};k%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 k=new Map;return b.set(m,k),k},w=function(m){var k=h(m);return function(x){var v=y(x);x.addEventListener("message",function(L){var D=L.data,oe=D.id;if(oe!==null&&v.has(oe)){var Y=v.get(oe),W=Y.reject,ee=Y.resolve;v.delete(oe),D.error===void 0?ee(D.result):W(new Error(D.error.message))}}),l(x)&&x.start();for(var S=function(L){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(Y,W){var ee=n.generateUniqueNumber(v);v.set(ee,{reject:W,resolve:Y}),D===null?x.postMessage({id:ee,method:L},oe):x.postMessage({id:ee,method:L,params:D},oe)})},E=function(L,D){var oe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];x.postMessage({id:null,method:L,params:D},oe)},I={},P=0,O=Object.entries(k);P<O.length;P++){var U=o(O[P],2),T=U[0],F=U[1];I=p(p({},I),{},r({},T,F({call:S,notify:E})))}return p({},I)}};t.createBroker=w})}),ud=fe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,Pr(),cd(),Bs()):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(h){r(s.get(h))==="symbol"&&(s.set(h,null),d("clear",{timerId:h,timerType:"interval"}).then(function(){s.delete(h)}))}},clearTimeout:function(u){var d=u.call;return function(h){r(a.get(h))==="symbol"&&(a.set(h,null),d("clear",{timerId:h,timerType:"timeout"}).then(function(){a.delete(h)}))}},setInterval:function(u){var d=u.call;return function(h){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,p=arguments.length,b=new Array(p>2?p-2:0),y=2;y<p;y++)b[y-2]=arguments[y];var w=Symbol(),m=n.generateUniqueNumber(s);s.set(m,w);var k=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&&(h.apply(void 0,b),s.get(m)===w&&k())})};return k(),m}},setTimeout:function(u){var d=u.call;return function(h){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,p=arguments.length,b=new Array(p>2?p-2:0),y=2;y<p;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 k=a.get(m);if(k===void 0)throw new Error("The timer is in an undefined state.");k===w&&(a.delete(m),h.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),dd=fe((i,e)=>{le(),ue(),ce(),(function(t,r){typeof i=="object"&&typeof e<"u"?r(i,ud()):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,h){var g=null;return function(){if(g!==null)return g;var p=new Blob([h],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(p);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})}),Or=fe(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&&De?.versions?!Object.prototype.hasOwnProperty.call(De.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}),hd=fe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(c,u,d,h){h===void 0&&(h=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,h,g)}:function(c,u,d,h){h===void 0&&(h=d),c[h]=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 h=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(h[h.length]=g);return h},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var h=c(u),g=0;g<h.length;g++)h[g]!=="default"&&e(d,u,h[g]);return t(d,u),d}})();Object.defineProperty(i,"__esModule",{value:!0});var o=dd(),n=r(Or()),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}),Vs=fe(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(hd()),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}),Pi=fe(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(_u()),s=Dt(),a=o(Su()),l=o(yt()),c=r(Os()),u=o(Ls()),d=o(zu()),h=o(Us()),g=o(Vu()),p=Kt(),b=Ku(),y=o(Vs()),w=r(Or()),m=globalThis.setImmediate||((...v)=>{let S=v.shift();(0,p.nextTick)(()=>{S(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},x=class zo extends b.TypedEventEmitter{static VERSION=p.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 k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=E[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",zo.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:zo.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 h.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 U=null;if(!O){this._resubscribe();return}U=O.packet,this.log("deliver :: call _sendPacket for %o",U);let T=!0;U.messageId&&U.messageId!==0&&(this.messageIdProvider.register(U.messageId)||(T=!1)),T?this._sendPacket(U,F=>{O.cb&&O.cb(F),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",U.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",L=>{this.log("parser :: on packet push to packets array."),P.push(L)});let O=()=>{this.log("work :: getting next packet in queue");let L=P.shift();if(L)this.log("work :: packet pulled from queue"),(0,d.default)(this,L,U);else{this.log("work :: no packets in queue");let D=I;I=null,this.log("work :: done flag is %s",!!D),D&&D()}},U=()=>{if(P.length)(0,p.nextTick)(O);else{let L=I;I=null,L()}};S._write=(L,D,oe)=>{I=oe,this.log("writable stream :: parsing buffer"),E.parse(L),O()};let T=L=>{this.log("streamErrorHandler :: error",L.message),L.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",L)):this.noop(L)};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 F={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&&(F.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(F.properties||(F.properties={}),this.topicAliasRecv&&(F.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(F),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 L={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(L)}}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:U,retain:T,dup:F,properties:L,cbStorePut:D}=I;if(this._checkDisconnecting(P))return this;let oe=()=>{let Y=0;if((U===1||U===2)&&(Y=this._nextId(),Y===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:S,payload:E,qos:U,retain:T,messageId:Y,dup:F};switch(O.protocolVersion===5&&(W.properties=L),this.log("publish :: qos",U),U){case 1:case 2:this.outgoing[W.messageId]={volatile:!1,cb:P||this.noop},this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,void 0,D);break;default:this.log("MqttClient:publish: packet cmd: %s",W.cmd),this._sendPacket(W,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,(U,T)=>{U?O(U):P(T)})})}subscribe(S,E,I){let P=this.options.protocolVersion;typeof E=="function"&&(I=E),I=I||this.noop;let O=!1,U=[];typeof S=="string"?(S=[S],U=S):Array.isArray(S)?U=S:typeof S=="object"&&(O=S.resubscribe,delete S.resubscribe,U=Object.keys(S));let T=c.validateTopics(U);if(T!==null)return m(I,new Error(`Invalid topic ${T}`)),this;if(this._checkDisconnecting(I))return this.log("subscribe: discconecting true"),this;let F={qos:0};P===5&&(F.nl=!1,F.rap=!1,F.rh=0),E={...F,...E};let{properties:L}=E,D=[],oe=(ee,$)=>{if($=$||E,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,ee)||this._resubscribeTopics[ee].qos<$.qos||O){let X={topic:ee,qos:$.qos};P===5&&(X.nl=$.nl,X.rap=$.rap,X.rh=$.rh,X.properties=L),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(ee=>{this.log("subscribe: array topic %s",ee),oe(ee)}):Object.keys(S).forEach(ee=>{this.log("subscribe: object topic %s, %o",ee,S[ee]),oe(ee,S[ee])}),!D.length)return I(null,[]),this;let Y=(ee,$)=>{let X={cmd:"subscribe",subscriptions:ee,messageId:$};if(L&&(X.properties=L),this.options.resubscribe){this.log("subscribe :: resubscribe true");let J=[];ee.forEach(ge=>{if(this.options.reconnectPeriod>0){let re={qos:ge.qos};P===5&&(re.nl=ge.nl||!1,re.rap=ge.rap||!1,re.rh=ge.rh||0,re.properties=ge.properties),this._resubscribeTopics[ge.topic]=re,J.push(ge.topic)}}),this.messageIdToTopic[X.messageId]=J}let M=new Promise((J,ge)=>{this.outgoing[X.messageId]={volatile:!0,cb(re,we){if(!re){let{granted:K}=we;for(let j=0;j<K.length;j+=1)ee[j].qos=K[j]}re?ge(new p.ErrorWithSubackPacket(re.message,we)):J(we)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(X),M},W=()=>{let ee=this.options.subscribeBatchSize??D.length,$=[];for(let X=0;X<D.length;X+=ee){let M=D.slice(X,X+ee),J=this._nextId();if(J===null)return this.log("No messageId left"),!1;$.push(Y(M,J))}return Promise.all($).then(X=>{I(null,D,X.at(-1))}).catch(X=>{I(X,D,X.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,P)=>{this.subscribe(S,E,(O,U)=>{O?P(O):I(U)})})}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 U=this._nextId();if(U===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:U,unsubscriptions:[]};return typeof S=="string"?T.unsubscriptions=[S]:Array.isArray(S)&&(T.unsubscriptions=S),this.options.resubscribe&&T.unsubscriptions.forEach(F=>{delete this._resubscribeTopics[F]}),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,U)=>{O?P(O):I(U)})})}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(U=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let F=U||T;this.log("end :: closeStores: invoking callback with args"),I(F)}})}),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,p.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,U=>{if(U)return E&&E(U);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 U=this._removeTopicAliasAndRecoverTopicName(P);if(U)return E&&E(U)}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,U=>{if(U)return E&&E(U);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 U=()=>{if(!I)return;let T=I.read(1),F;if(!T){I.once("readable",U);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){U();return}!this.disconnecting&&!this.reconnectTimer?(F=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb(L,D){F&&F(L,D),U()}},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 F in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[F]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",S)):E()}),U()};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}),pd=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=$s(),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 fd(){if(Oi)return Lr;Oi=!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,h={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,p=Math.floor,b=String.fromCharCode;function y(O){throw new RangeError(h[O])}function w(O,U){let T=[],F=O.length;for(;F--;)T[F]=U(O[F]);return T}function m(O,U){let T=O.split("@"),F="";T.length>1&&(F=T[0]+"@",O=T[1]),O=O.replace(d,".");let L=O.split("."),D=w(L,U).join(".");return F+D}function k(O){let U=[],T=0,F=O.length;for(;T<F;){let L=O.charCodeAt(T++);if(L>=55296&&L<=56319&&T<F){let D=O.charCodeAt(T++);(D&64512)==56320?U.push(((L&1023)<<10)+(D&1023)+65536):(U.push(L),T--)}else U.push(L)}return U}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,U){return O+22+75*(O<26)-((U!=0)<<5)},E=function(O,U,T){let F=0;for(O=T?p(O/n):O>>1,O+=p(O/U);O>g*r>>1;F+=e)O=p(O/g);return p(F+(g+1)*O/(O+o))},I=function(O){let U=[],T=O.length,F=0,L=a,D=s,oe=O.lastIndexOf(l);oe<0&&(oe=0);for(let Y=0;Y<oe;++Y)O.charCodeAt(Y)>=128&&y("not-basic"),U.push(O.charCodeAt(Y));for(let Y=oe>0?oe+1:0;Y<T;){let W=F;for(let $=1,X=e;;X+=e){Y>=T&&y("invalid-input");let M=v(O.charCodeAt(Y++));M>=e&&y("invalid-input"),M>p((i-F)/$)&&y("overflow"),F+=M*$;let J=X<=D?t:X>=D+r?r:X-D;if(M<J)break;let ge=e-J;$>p(i/ge)&&y("overflow"),$*=ge}let ee=U.length+1;D=E(F-W,ee,W==0),p(F/ee)>i-L&&y("overflow"),L+=p(F/ee),F%=ee,U.splice(F++,0,L)}return String.fromCodePoint(...U)},P=function(O){let U=[];O=k(O);let T=O.length,F=a,L=0,D=s;for(let W of O)W<128&&U.push(b(W));let oe=U.length,Y=oe;for(oe&&U.push(l);Y<T;){let W=i;for(let $ of O)$>=F&&$<W&&(W=$);let ee=Y+1;W-F>p((i-L)/ee)&&y("overflow"),L+=(W-F)*ee,F=W;for(let $ of O)if($<F&&++L>i&&y("overflow"),$===F){let X=L;for(let M=e;;M+=e){let J=M<=D?t:M>=D+r?r:M-D;if(X<J)break;let ge=X-J,re=e-J;U.push(b(S(J+ge%re,0))),X=p(ge/re)}U.push(b(S(X,0))),D=E(L,ee,Y===oe),L=0,++Y}++L,++F}return U.join("")};return Lr={version:"2.3.1",ucs2:{decode:k,encode:x},decode:I,encode:P,toASCII:function(O){return m(O,function(U){return u.test(U)?"xn--"+P(U):U})},toUnicode:function(O){return m(O,function(U){return c.test(U)?I(U.slice(4).toLowerCase()):U})}},Lr}var Lr,Oi,Tt,md=Qe(()=>{le(),ue(),ce(),Lr={},Oi=!1,Tt=fd(),Tt.decode,Tt.encode,Tt.toASCII,Tt.toUnicode,Tt.ucs2,Tt.version});function gd(){return Ri||(Ri=!0,Ni=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}),Ni}function bd(){return Di||(Di=!0,ji=Error),ji}function yd(){return Ui||(Ui=!0,$i=EvalError),$i}function vd(){return Fi||(Fi=!0,Bi=RangeError),Bi}function wd(){return Hi||(Hi=!0,qi=ReferenceError),qi}function Ks(){return zi||(zi=!0,Wi=SyntaxError),Wi}function cr(){return Ki||(Ki=!0,Vi=TypeError),Vi}function kd(){return Yi||(Yi=!0,Gi=URIError),Gi}function _d(){if(Ji)return Mr;Ji=!0;var i=typeof Symbol<"u"&&Symbol,e=gd();return Mr=function(){return typeof i!="function"||typeof Symbol!="function"||typeof i("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Mr}function xd(){if(Qi)return Nr;Qi=!0;var i={__proto__:null,foo:{}},e=Object;return Nr=function(){return{__proto__:i}.foo===i.foo&&!(i instanceof e)},Nr}function Sd(){if(Xi)return Rr;Xi=!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 Rr=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))},h=t(0,l.length-c.length),g=[],p=0;p<h;p++)g[p]="$"+p;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},Rr}function Li(){if(Zi)return jr;Zi=!0;var i=Sd();return jr=Function.prototype.bind||i,jr}function Ed(){if(eo)return Dr;eo=!0;var i=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Li();return Dr=t.call(i,e),Dr}function Gt(){if(to)return $r;to=!0;var i,e=bd(),t=yd(),r=vd(),o=wd(),n=Ks(),s=cr(),a=kd(),l=Function,c=function(Y){try{return l('"use strict"; return ('+Y+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new s},h=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=_d()(),p=xd()(),b=Object.getPrototypeOf||(p?function(Y){return Y.__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%":h,"%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(Y){var k=b(b(Y));m["%Error.prototype%"]=k}var x=function Y(W){var ee;if(W==="%AsyncFunction%")ee=c("async function () {}");else if(W==="%GeneratorFunction%")ee=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")ee=c("async function* () {}");else if(W==="%AsyncGenerator%"){var $=Y("%AsyncGeneratorFunction%");$&&(ee=$.prototype)}else if(W==="%AsyncIteratorPrototype%"){var X=Y("%AsyncGenerator%");X&&b&&(ee=b(X.prototype))}return m[W]=ee,ee},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=Li(),E=Ed(),I=S.call(Function.call,Array.prototype.concat),P=S.call(Function.apply,Array.prototype.splice),O=S.call(Function.call,String.prototype.replace),U=S.call(Function.call,String.prototype.slice),T=S.call(Function.call,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,L=/\\(\\)?/g,D=function(Y){var W=U(Y,0,1),ee=U(Y,-1);if(W==="%"&&ee!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(ee==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var $=[];return O(Y,F,function(X,M,J,ge){$[$.length]=J?O(ge,L,"$1"):M||X}),$},oe=function(Y,W){var ee=Y,$;if(E(v,ee)&&($=v[ee],ee="%"+$[0]+"%"),E(m,ee)){var X=m[ee];if(X===y&&(X=x(ee)),typeof X>"u"&&!W)throw new s("intrinsic "+Y+" exists, but is not available. Please file an issue!");return{alias:$,name:ee,value:X}}throw new n("intrinsic "+Y+" does not exist!")};return $r=function(Y,W){if(typeof Y!="string"||Y.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(/^%?[^%]*%?$/,Y)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ee=D(Y),$=ee.length>0?ee[0]:"",X=oe("%"+$+"%",W),M=X.name,J=X.value,ge=!1,re=X.alias;re&&($=re[0],P(ee,I([0,1],re)));for(var we=1,K=!0;we<ee.length;we+=1){var j=ee[we],ne=U(j,0,1),z=U(j,-1);if((ne==='"'||ne==="'"||ne==="`"||z==='"'||z==="'"||z==="`")&&ne!==z)throw new n("property names with quotes must have matching quotes");if((j==="constructor"||!K)&&(ge=!0),$+="."+j,M="%"+$+"%",E(m,M))J=m[M];else if(J!=null){if(!(j in J)){if(!W)throw new s("base intrinsic for "+Y+" exists, but the property is not available.");return}if(u&&we+1>=ee.length){var G=u(J,j);K=!!G,K&&"get"in G&&!("originalValue"in G.get)?J=G.get:J=J[j]}else K=E(J,j),J=J[j];K&&!ge&&(m[M]=J)}}return J},$r}function Mi(){if(ro)return Ur;ro=!0;var i=Gt(),e=i("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Ur=e,Ur}function Gs(){if(no)return Br;no=!0;var i=Gt(),e=i("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Br=e,Br}function Ad(){if(io)return Fr;io=!0;var i=Mi(),e=Ks(),t=cr(),r=Gs();return Fr=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.")},Fr}function Id(){if(oo)return qr;oo=!0;var i=Mi(),e=function(){return!!i};return e.hasArrayLengthDefineBug=function(){if(!i)return null;try{return i([],"length",{value:1}).length!==1}catch{return!0}},qr=e,qr}function Td(){if(so)return Hr;so=!0;var i=Gt(),e=Ad(),t=Id()(),r=Gs(),o=cr(),n=i("%Math.floor%");return Hr=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},Hr}function Cd(){if(ao)return Yt;ao=!0;var i=Li(),e=Gt(),t=Td(),r=cr(),o=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||i.call(n,o),a=Mi(),l=e("%Math.max%");Yt=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(Yt,"apply",{value:c}):Yt.apply=c,Yt}function Pd(){if(lo)return Wr;lo=!0;var i=Gt(),e=Cd(),t=e(i("String.prototype.indexOf"));return Wr=function(r,o){var n=i(r,!!o);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},Wr}var Ni,Ri,ji,Di,$i,Ui,Bi,Fi,qi,Hi,Wi,zi,Vi,Ki,Gi,Yi,Mr,Ji,Nr,Qi,Rr,Xi,jr,Zi,Dr,eo,$r,to,Ur,ro,Br,no,Fr,io,qr,oo,Hr,so,Yt,ao,Wr,lo,Od=Qe(()=>{le(),ue(),ce(),Ni={},Ri=!1,ji={},Di=!1,$i={},Ui=!1,Bi={},Fi=!1,qi={},Hi=!1,Wi={},zi=!1,Vi={},Ki=!1,Gi={},Yi=!1,Mr={},Ji=!1,Nr={},Qi=!1,Rr={},Xi=!1,jr={},Zi=!1,Dr={},eo=!1,$r={},to=!1,Ur={},ro=!1,Br={},no=!1,Fr={},io=!1,qr={},oo=!1,Hr={},so=!1,Yt={},ao=!1,Wr={},lo=!1});function co(i){throw new Error("Node.js process "+i+" is not supported by JSPM core outside of Node.js")}function Ld(){!$t||!Ut||($t=!1,Ut.length?st=Ut.concat(st):ur=-1,st.length&&Ys())}function Ys(){if(!$t){var i=setTimeout(Ld,0);$t=!0;for(var e=st.length;e;){for(Ut=st,st=[];++ur<e;)Ut&&Ut[ur].run();ur=-1,e=st.length}Ut=null,$t=!1,clearTimeout(i)}}function Md(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];st.push(new Js(i,e)),st.length===1&&!$t&&setTimeout(Ys,0)}function Js(i,e){this.fun=i,this.array=e}function ze(){}function Nd(i){co("_linkedBinding")}function Rd(i){co("dlopen")}function jd(){return[]}function Dd(){return[]}function $d(i,e){if(!i)throw new Error(e||"assertion error")}function Ud(){return!1}function Bd(){return kt.now()/1e3}function uo(i){var e=Math.floor((Date.now()-kt.now())*.001),t=kt.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+=Vr)),[r,o]}function Ct(){return po}function Fd(i){return[]}var st,$t,Ut,ur,Qs,Xs,Zs,ea,ta,ra,na,ia,oa,sa,aa,la,ca,ua,da,ha,pa,fa,ma,ga,ba,zr,ya,va,wa,ka,_a,xa,Sa,Ea,Aa,Ia,Ta,Ca,Pa,Oa,La,Ma,Na,Ra,ja,Da,$a,Ua,Ba,Fa,qa,kt,ho,Vr,Ha,Wa,za,Va,Ka,Ga,Ya,Ja,Qa,Xa,Za,po,el=Qe(()=>{le(),ue(),ce(),st=[],$t=!1,ur=-1,Js.prototype.run=function(){this.fun.apply(null,this.array)},Qs="browser",Xs="x64",Zs="browser",ea={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},ta=["/usr/bin/node"],ra=[],na="v16.8.0",ia={},oa=function(i,e){console.warn((e?e+": ":"")+i)},sa=function(i){co("binding")},aa=function(i){return 0},la=function(){return"/"},ca=function(i){},ua={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},da=ze,ha=[],pa={},fa=!1,ma={},ga=ze,ba=ze,zr=function(){return{}},ya=zr,va=zr,wa=ze,ka=ze,_a=ze,xa={},Sa={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Ea=ze,Aa=ze,Ia=ze,Ta=ze,Ca=ze,Pa=ze,Oa=ze,La=void 0,Ma=void 0,Na=void 0,Ra=ze,ja=2,Da=1,$a="/bin/usr/node",Ua=9229,Ba="node",Fa=[],qa=ze,kt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},kt.now===void 0&&(ho=Date.now(),kt.timing&&kt.timing.navigationStart&&(ho=kt.timing.navigationStart),kt.now=()=>Date.now()-ho),Vr=1e9,uo.bigint=function(i){var e=uo(i);return typeof BigInt>"u"?e[0]*Vr+e[1]:BigInt(e[0]*Vr)+BigInt(e[1])},Ha=10,Wa={},za=0,Va=Ct,Ka=Ct,Ga=Ct,Ya=Ct,Ja=Ct,Qa=ze,Xa=Ct,Za=Ct,po={version:na,versions:ia,arch:Xs,platform:Zs,release:ua,_rawDebug:da,moduleLoadList:ha,binding:sa,_linkedBinding:Nd,_events:Wa,_eventsCount:za,_maxListeners:Ha,on:Ct,addListener:Va,once:Ka,off:Ga,removeListener:Ya,removeAllListeners:Ja,emit:Qa,prependListener:Xa,prependOnceListener:Za,listeners:Fd,domain:pa,_exiting:fa,config:ma,dlopen:Rd,uptime:Bd,_getActiveRequests:jd,_getActiveHandles:Dd,reallyExit:ga,_kill:ba,cpuUsage:zr,resourceUsage:ya,memoryUsage:va,kill:wa,exit:ka,openStdin:_a,allowedNodeEnvironmentFlags:xa,assert:$d,features:Sa,_fatalExceptions:Ea,setUncaughtExceptionCaptureCallback:Aa,hasUncaughtExceptionCaptureCallback:Ud,emitWarning:oa,nextTick:Md,_tickCallback:Ia,_debugProcess:Ta,_debugEnd:Ca,_startProfilerIdleNotifier:Pa,_stopProfilerIdleNotifier:Oa,stdout:La,stdin:Na,stderr:Ma,abort:Ra,umask:aa,chdir:ca,cwd:la,env:ea,title:Qs,argv:ta,execArgv:ra,pid:ja,ppid:Da,execPath:$a,debugPort:Ua,hrtime:uo,argv0:Ba,_preload_modules:Fa,setSourceMapsEnabled:qa}});function qd(){if(fo)return Kr;fo=!0;var i=po;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,h=0;h<=n.length;++h){if(h<n.length)d=n.charCodeAt(h);else{if(d===47)break;d=47}if(d===47){if(!(c===h-1||u===1))if(c!==h-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=h,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=h,u=0;continue}}s&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,h):a=n.slice(c+1,h),l=h-c-1;c=h,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,h=d-u,g=c<h?c:h,p=-1,b=0;b<=g;++b){if(b===g){if(h>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?p=b:b===0&&(p=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(p=b)}var m="";for(b=a+p+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+p):(u+=p,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,h=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else h===-1&&(c=!1,h=u+1),d>=0&&(g===s.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=h))}return a===l?l=h: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 h=n.charCodeAt(d);if(h===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),h===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,h=-1,g=!0,p=n.length-1,b=0;p>=c;--p){if(a=n.charCodeAt(p),a===47){if(!g){d=p+1;break}continue}h===-1&&(g=!1,h=p+1),a===46?u===-1?u=p:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||h===-1||b===0||b===1&&u===h-1&&u===d+1?h!==-1&&(d===0&&l?s.base=s.name=n.slice(1,h):s.base=s.name=n.slice(d,h)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,h)):(s.name=n.slice(d,u),s.base=n.slice(d,h)),s.ext=n.slice(u,h)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return o.posix=o,Kr=o,Kr}var Kr,fo,mo,Hd=Qe(()=>{le(),ue(),ce(),el(),Kr={},fo=!1,mo=qd()}),tl={};Ht(tl,{URL:()=>hl,Url:()=>al,default:()=>Ve,fileURLToPath:()=>nl,format:()=>ll,parse:()=>dl,pathToFileURL:()=>il,resolve:()=>cl,resolveObject:()=>ul});function Wd(){if(bo)return Gr;bo=!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,h=typeof WeakRef=="function"&&WeakRef.prototype,g=h?WeakRef.prototype.deref:null,p=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=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,U=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,F=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,L=typeof Symbol=="function"&&typeof Symbol.iterator=="object",D=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===L||!0)?Symbol.toStringTag:null,oe=Object.prototype.propertyIsEnumerable,Y=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(V){return V.__proto__}:null);function W(V,ie){if(V===1/0||V===-1/0||V!==V||V&&V>-1e3&&V<1e3||S.call(/e/,ie))return ie;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof V=="number"){var Te=V<0?-O(-V):O(V);if(Te!==V){var Oe=String(Te),Ne=m.call(ie,Oe.length+1);return k.call(Oe,Ie,"$&_")+"."+k.call(k.call(Ne,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(ie,Ie,"$&_")}var ee=ol,$=ee.custom,X=G($)?$:null;Gr=function V(ie,Ie,Te,Oe){var Ne=Ie||{};if(se(Ne,"quoteStyle")&&Ne.quoteStyle!=="single"&&Ne.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(se(Ne,"maxStringLength")&&(typeof Ne.maxStringLength=="number"?Ne.maxStringLength<0&&Ne.maxStringLength!==1/0:Ne.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var at=se(Ne,"customInspect")?Ne.customInspect:!0;if(typeof at!="boolean"&&at!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(se(Ne,"indent")&&Ne.indent!==null&&Ne.indent!==" "&&!(parseInt(Ne.indent,10)===Ne.indent&&Ne.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(se(Ne,"numericSeparator")&&typeof Ne.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var lt=Ne.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,Ne);if(typeof ie=="number"){if(ie===0)return 1/0/ie>0?"0":"-0";var Ge=String(ie);return lt?W(ie,Ge):Ge}if(typeof ie=="bigint"){var ct=String(ie)+"n";return lt?W(ie,ct):ct}var tr=typeof Ne.depth>"u"?5:Ne.depth;if(typeof Te>"u"&&(Te=0),Te>=tr&&tr>0&&typeof ie=="object")return ge(ie)?"[Array]":"[Object]";var ut=Z(Ne,Te);if(typeof Oe>"u")Oe=[];else if(te(Oe,ie)>=0)return"[Circular]";function et(dt,Lt,qt){if(Lt&&(Oe=P.call(Oe),Oe.push(Lt)),qt){var ht={depth:Ne.depth};return se(Ne,"quoteStyle")&&(ht.quoteStyle=Ne.quoteStyle),V(dt,ht,Te+1,Oe)}return V(dt,Ne,Te+1,Oe)}if(typeof ie=="function"&&!we(ie)){var un=q(ie),rr=_e(ie,et);return"[Function"+(un?": "+un:" (anonymous)")+"]"+(rr.length>0?" { "+I.call(rr,", ")+" }":"")}if(G(ie)){var gr=L?k.call(String(ie),/^(Symbol\(.*\))_[^)]*$/,"$1"):F.call(ie);return typeof ie=="object"&&!L?f(gr):gr}if(ve(ie)){for(var C="<"+v.call(String(ie.nodeName)),R=ie.attributes||[],ke=0;ke<R.length;ke++)C+=" "+R[ke].name+"="+M(J(R[ke].value),"double",Ne);return C+=">",ie.childNodes&&ie.childNodes.length&&(C+="..."),C+="</"+v.call(String(ie.nodeName))+">",C}if(ge(ie)){if(ie.length===0)return"[]";var Se=_e(ie,et);return ut&&!B(Se)?"["+de(Se,ut)+"]":"[ "+I.call(Se,", ")+" ]"}if(K(ie)){var Ae=_e(ie,et);return!("cause"in Error.prototype)&&"cause"in ie&&!oe.call(ie,"cause")?"{ ["+String(ie)+"] "+I.call(E.call("[cause]: "+et(ie.cause),Ae),", ")+" }":Ae.length===0?"["+String(ie)+"]":"{ ["+String(ie)+"] "+I.call(Ae,", ")+" }"}if(typeof ie=="object"&&at){if(X&&typeof ie[X]=="function"&&ee)return ee(ie,{depth:tr-Te});if(at!=="symbol"&&typeof ie.inspect=="function")return ie.inspect()}if(he(ie)){var Fe=[];return r&&r.call(ie,function(dt,Lt){Fe.push(et(Lt,ie,!0)+" => "+et(dt,ie))}),A("Map",t.call(ie),Fe,ut)}if(H(ie)){var Je=[];return a&&a.call(ie,function(dt){Je.push(et(dt,ie))}),A("Set",s.call(ie),Je,ut)}if(pe(ie))return _("WeakMap");if(me(ie))return _("WeakSet");if(ye(ie))return _("WeakRef");if(ne(ie))return f(et(Number(ie)));if(Q(ie))return f(et(U.call(ie)));if(z(ie))return f(p.call(ie));if(j(ie))return f(et(String(ie)));if(typeof window<"u"&&ie===window)return"{ [object Window] }";if(typeof globalThis<"u"&&ie===globalThis||typeof Yr<"u"&&ie===Yr)return"{ [object globalThis] }";if(!re(ie)&&!we(ie)){var it=_e(ie,et),br=Y?Y(ie)===Object.prototype:ie instanceof Object||ie.constructor===Object,yr=ie instanceof Object?"":"null prototype",vr=!br&&D&&Object(ie)===ie&&D in ie?m.call(N(ie),8,-1):yr?"Object":"",dn=br||typeof ie.constructor!="function"?"":ie.constructor.name?ie.constructor.name+" ":"",Ft=dn+(vr||yr?"["+I.call(E.call([],vr||[],yr||[]),": ")+"] ":"");return it.length===0?Ft+"{}":ut?Ft+"{"+de(it,ut)+"}":Ft+"{ "+I.call(it,", ")+" }"}return String(ie)};function M(V,ie,Ie){var Te=(Ie.quoteStyle||ie)==="double"?'"':"'";return Te+V+Te}function J(V){return k.call(String(V),/"/g,""")}function ge(V){return N(V)==="[object Array]"&&(!D||!(typeof V=="object"&&D in V))}function re(V){return N(V)==="[object Date]"&&(!D||!(typeof V=="object"&&D in V))}function we(V){return N(V)==="[object RegExp]"&&(!D||!(typeof V=="object"&&D in V))}function K(V){return N(V)==="[object Error]"&&(!D||!(typeof V=="object"&&D in V))}function j(V){return N(V)==="[object String]"&&(!D||!(typeof V=="object"&&D in V))}function ne(V){return N(V)==="[object Number]"&&(!D||!(typeof V=="object"&&D in V))}function z(V){return N(V)==="[object Boolean]"&&(!D||!(typeof V=="object"&&D in V))}function G(V){if(L)return V&&typeof V=="object"&&V instanceof Symbol;if(typeof V=="symbol")return!0;if(!V||typeof V!="object"||!F)return!1;try{return F.call(V),!0}catch{}return!1}function Q(V){if(!V||typeof V!="object"||!U)return!1;try{return U.call(V),!0}catch{}return!1}var be=Object.prototype.hasOwnProperty||function(V){return V in(this||Yr)};function se(V,ie){return be.call(V,ie)}function N(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 te(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 pe(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 Oe=k.call(k.call(V,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Le);return M(Oe,"single",ie)}function Le(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 f(V){return"Object("+V+")"}function _(V){return V+" { ? }"}function A(V,ie,Ie,Te){var Oe=Te?de(Ie,Te):I.call(Ie,", ");return V+" ("+ie+") {"+Oe+"}"}function B(V){for(var ie=0;ie<V.length;ie++)if(te(V[ie],`
|
|
4
4
|
`)>=0)return!1;return!0}function Z(V,ie){var Ie;if(V.indent===" ")Ie=" ";else if(typeof V.indent=="number"&&V.indent>0)Ie=I.call(Array(V.indent+1)," ");else return null;return{base:Ie,prev:I.call(Array(ie+1),Ie)}}function de(V,ie){if(V.length===0)return"";var Ie=`
|
|
5
5
|
`+ie.prev+ie.base;return Ie+I.call(V,","+Ie)+`
|
|
6
|
-
`+ie.prev}function _e(V,ie){var Ie=ge(V),Te=[];if(Ie){Te.length=V.length;for(var Pe=0;Pe<V.length;Pe++)Te[Pe]=se(V,Pe)?ie(V[Pe],V):""}var Le=typeof T=="function"?T(V):[],ot;if(M){ot={};for(var st=0;st<Le.length;st++)ot["$"+Le[st]]=Le[st]}for(var Ge in V)se(V,Ge)&&(Ie&&String(Number(Ge))===Ge&&Ge<V.length||M&&ot["$"+Ge]instanceof Symbol||(x.call(/[^\w$]/,Ge)?Te.push(ie(Ge,V)+": "+ie(V[Ge],V)):Te.push(Ge+": "+ie(V[Ge],V))));if(typeof T=="function")for(var at=0;at<Le.length;at++)oe.call(V,Le[at])&&Te.push("["+ie(Le[at])+"]: "+ie(V[Le[at]],V));return Te}return Wr}function Nd(){if(fo)return Vr;fo=!0;var i=Vt(),e=wd(),t=Rd(),r=sr(),s=i("%WeakMap%",!0),n=i("%Map%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,w){for(var m=b,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=b.next,b.next=k,k},g=function(b,w){var m=p(b,w);return m&&m.value},f=function(b,w,m){var k=p(b,w);k?k.value=m:b.next={key:w,next:b.next,value:m}},y=function(b,w){return!!p(b,w)};return Vr=function(){var b,w,m,k={assert:function(S){if(!k.has(S))throw new r("Side channel does not contain "+t(S))},get:function(S){if(s&&S&&(typeof S=="object"||typeof S=="function")){if(b)return o(b,S)}else if(n){if(w)return c(w,S)}else if(m)return g(m,S)},has:function(S){if(s&&S&&(typeof S=="object"||typeof S=="function")){if(b)return l(b,S)}else if(n){if(w)return d(w,S)}else if(m)return y(m,S);return!1},set:function(S,v){s&&S&&(typeof S=="object"||typeof S=="function")?(b||(b=new s),a(b,S,v)):n?(w||(w=new n),u(w,S,v)):(m||(m={key:{},next:null}),f(m,S,v))}};return k},Vr}function uo(){if(po)return Gr;po=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Gr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Gr}function Ya(){if(mo)return Kr;mo=!0;var i=uo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],w=0;w<256;++w)b.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return b})(),s=function(b){for(;b.length>1;){var w=b.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],S=0;S<m.length;++S)typeof m[S]<"u"&&k.push(m[S]);w.obj[w.prop]=k}}},n=function(b,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<b.length;++k)typeof b[k]<"u"&&(m[k]=b[k]);return m},o=function b(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var S=w;return t(w)&&!t(m)&&(S=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,x){if(e.call(w,x)){var E=w[x];E&&typeof E=="object"&&v&&typeof v=="object"?w[x]=b(E,v,k):w.push(v)}else w[x]=v}),w):Object.keys(m).reduce(function(v,x){var E=m[x];return e.call(v,x)?v[x]=b(v[x],E,k):v[x]=E,v},S)},a=function(b,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},b)},l=function(b,w,m){var k=b.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(b,w,m,k,S){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",E=0;E<v.length;E+=c){for(var I=v.length>=c?v.slice(E,E+c):v,P=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||S===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]}x+=P.join("")}return x},d=function(b){for(var w=[{obj:{o:b},prop:"o"}],m=[],k=0;k<w.length;++k)for(var S=w[k],v=S.obj[S.prop],x=Object.keys(v),E=0;E<x.length;++E){var I=x[E],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return s(w),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},g=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,w){return[].concat(b,w)},y=function(b,w){if(t(b)){for(var m=[],k=0;k<b.length;k+=1)m.push(w(b[k]));return m}return w(b)};return Kr={arrayToObject:n,assign:a,combine:f,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:y,merge:o},Kr}function jd(){if(go)return Yr;go=!0;var i=Nd(),e=Ya(),t=uo(),r=Object.prototype.hasOwnProperty,s={brackets:function(y){return y+"[]"},comma:"comma",indices:function(y,b){return y+"["+b+"]"},repeat:function(y){return y}},n=Array.isArray,o=Array.prototype.push,a=function(y,b){o.apply(y,n(b)?b:[b])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(y){return l.call(y)},skipNulls:!1,strictNullHandling:!1},d=function(y){return typeof y=="string"||typeof y=="number"||typeof y=="boolean"||typeof y=="symbol"||typeof y=="bigint"},p={},g=function y(b,w,m,k,S,v,x,E,I,P,O,B,T,$,M,U,oe,Y){for(var W=b,ee=Y,D=0,X=!1;(ee=ee.get(p))!==void 0&&!X;){var L=ee.get(b);if(D+=1,typeof L<"u"){if(L===D)throw new RangeError("Cyclic object value");X=!0}typeof ee.get(p)>"u"&&(D=0)}if(typeof P=="function"?W=P(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 J=U?w:I(w,u.encoder,oe,"key",$);return[M(J)+"="+M(I(W,u.encoder,oe,"value",$))]}return[M(w)+"="+M(String(W))]}var ge=[];if(typeof W>"u")return ge;var re;if(m==="comma"&&n(W))U&&I&&(W=e.maybeMap(W,I)),re=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))re=P;else{var we=Object.keys(W);re=O?we.sort(O):we}var G=E?w.replace(/\./g,"%2E"):w,j=k&&n(W)&&W.length===1?G+"[]":G;if(S&&n(W)&&W.length===0)return j+"[]";for(var ne=0;ne<re.length;++ne){var z=re[ne],K=typeof z=="object"&&typeof z.value<"u"?z.value:W[z];if(!(x&&K===null)){var Q=B&&E?z.replace(/\./g,"%2E"):z,ye=n(W)?typeof m=="function"?m(j,Q):j:j+(B?"."+Q:"["+Q+"]");Y.set(b,D);var se=i();se.set(p,Y),a(ge,y(K,ye,m,k,S,v,x,E,m==="comma"&&U&&n(W)?null:I,P,O,B,T,$,M,U,oe,se))}}return ge},f=function(y){if(!y)return u;if(typeof y.allowEmptyArrays<"u"&&typeof y.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof y.encodeDotInKeys<"u"&&typeof y.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(y.encoder!==null&&typeof y.encoder<"u"&&typeof y.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=y.charset||u.charset;if(typeof y.charset<"u"&&y.charset!=="utf-8"&&y.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof y.format<"u"){if(!r.call(t.formatters,y.format))throw new TypeError("Unknown format option provided.");w=y.format}var m=t.formatters[w],k=u.filter;(typeof y.filter=="function"||n(y.filter))&&(k=y.filter);var S;if(y.arrayFormat in s?S=y.arrayFormat:"indices"in y?S=y.indices?"indices":"repeat":S=u.arrayFormat,"commaRoundTrip"in y&&typeof y.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof y.allowDots>"u"?y.encodeDotInKeys===!0?!0:u.allowDots:!!y.allowDots;return{addQueryPrefix:typeof y.addQueryPrefix=="boolean"?y.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof y.allowEmptyArrays=="boolean"?!!y.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:S,charset:b,charsetSentinel:typeof y.charsetSentinel=="boolean"?y.charsetSentinel:u.charsetSentinel,commaRoundTrip:y.commaRoundTrip,delimiter:typeof y.delimiter>"u"?u.delimiter:y.delimiter,encode:typeof y.encode=="boolean"?y.encode:u.encode,encodeDotInKeys:typeof y.encodeDotInKeys=="boolean"?y.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof y.encoder=="function"?y.encoder:u.encoder,encodeValuesOnly:typeof y.encodeValuesOnly=="boolean"?y.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof y.serializeDate=="function"?y.serializeDate:u.serializeDate,skipNulls:typeof y.skipNulls=="boolean"?y.skipNulls:u.skipNulls,sort:typeof y.sort=="function"?y.sort:null,strictNullHandling:typeof y.strictNullHandling=="boolean"?y.strictNullHandling:u.strictNullHandling}};return Yr=function(y,b){var w=y,m=f(b),k,S;typeof m.filter=="function"?(S=m.filter,w=S("",w)):n(m.filter)&&(S=m.filter,k=S);var v=[];if(typeof w!="object"||w===null)return"";var x=s[m.arrayFormat],E=x==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=i(),P=0;P<k.length;++P){var O=k[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,x,E,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var 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:""},Yr}function Ud(){if(yo)return Jr;yo=!0;var i=Ya(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:i.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},s=function(p){return p.replace(/&#(\d+);/g,function(g,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var f={__proto__:null},y=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;y=y.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=g.parameterLimit===1/0?void 0:g.parameterLimit,w=y.split(g.delimiter,b),m=-1,k,S=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?S="utf-8":w[k]===o&&(S="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],x=v.indexOf("]="),E=x===-1?v.indexOf("="):x+1,I,P;E===-1?(I=g.decoder(v,r.decoder,S,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,E),r.decoder,S,"key"),P=i.maybeMap(n(v.slice(E+1),g),function(B){return g.decoder(B,r.decoder,S,"value")})),P&&g.interpretNumericEntities&&S==="iso-8859-1"&&(P=s(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,y){for(var b=y?g:n(g,f),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var S=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=f.decodeDotInKeys?S.replace(/%2E/g,"."):S,x=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(x)&&k!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,g,f,y){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=f.depth>0&&w.exec(b),S=k?b.slice(0,k.index):b,v=[];if(S){if(!f.plainObjects&&e.call(Object.prototype,S)&&!f.allowPrototypes)return;v.push(S)}for(var x=0;f.depth>0&&(k=m.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(k[1])}if(k){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(k.index)+"]")}return c(v,g,f,y)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var y=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:y,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||i.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Jr=function(p,g){var f=d(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var y=typeof p=="string"?l(p,f):p,b=f.plainObjects?Object.create(null):{},w=Object.keys(y),m=0;m<w.length;++m){var k=w[m],S=u(k,y[k],f,typeof p=="string");b=i.merge(b,S,f)}return f.allowSparse===!0?b:i.compact(b)},Jr}function Dd(){if(bo)return Qr;bo=!0;var i=jd(),e=Ud(),t=uo();return Qr={formats:t,parse:e,stringify:i},Qr}function Bd(){if(vo)return Tt;vo=!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]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
-
`," "],
|
|
8
|
-
`)&&(e=e.replace(fl,"%0A")),e.includes("\r")&&(e=e.replace(pl,"%0D")),e.includes(" ")&&(e=e.replace(ml,"%09")),r.pathname=e,r}var Xa,Wr,ho,zr,Vr,fo,Gr,po,Kr,mo,Yr,go,Jr,yo,Qr,bo,Tt,vo,ze,Za,el,tl,rl,nl,il,ol,sl,al,ll,cl,Xr,ul,dl,hl,fl,pl,ml,qd=Je(()=>{le(),ue(),ce(),od(),kd(),Ld(),Ga(),Xa=Object.freeze(Object.create(null)),Wr={},ho=!1,zr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Vr={},fo=!1,Gr={},po=!1,Kr={},mo=!1,Yr={},go=!1,Jr={},yo=!1,Qr={},bo=!1,Tt={},vo=!1,ze=Bd(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Za=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Qa,ze.fileURLToPath=Ja,el=ze.Url,tl=ze.format,rl=ze.resolve,nl=ze.resolveObject,il=ze.parse,ol=ze.URL,sl=92,al=47,ll=97,cl=122,Xr=Za==="win32",ul=/\//g,dl=/%/g,hl=/\\/g,fl=/\n/g,pl=/\r/g,ml=/\t/g}),Hd=pe((i,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),wo=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=Nt(),t=(qe(),Ne($e));function r(n,o){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",o)}var s=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,o,a){super({objectMode:!0}),this.proxy=o,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,o,a){this.isSocketOpen?this.writeToProxy(n,o,a):this.writeQueue.push({chunk:n,encoding:o,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,o){this.writeQueue=[],this.proxy.destroy(),o(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,o,a){this.proxy.write(n,o)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:o,cb:a}=this.writeQueue.shift();this.writeToProxy(n,o,a)}}};i.BufferedDuplex=s}),Zr=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(i,"__esModule",{value:!0}),i.streamBuilder=i.browserStreamBuilder=void 0;var t=(qe(),Ne($e)),r=e(Hd()),s=e(gt()),n=Nt(),o=e(Ir()),a=wo(),l=(0,s.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!o.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function p(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let S=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${S}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[S],k):v=new r.default(m,[S],k.wsOptions),v}function f(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",S=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(S,[k],m):v=new WebSocket(S,[k]),v.binaryType="arraybuffer",v}var y=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let S=u(k,w),v=g(w,S,k),x=r.default.createWebSocketStream(v,k.wsOptions);return x.url=S,v.on("close",()=>{x.destroy()}),x};i.streamBuilder=y;var b=(w,m)=>{l("browserStreamBuilder");let k,S=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,E=f(w,m),I=O(m,U,oe);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{E.close()});let P=typeof E.addEventListener<"u";E.readyState===E.OPEN?(k=I,k.socket=E):(k=new a.BufferedDuplex(m,I,E),P?E.addEventListener("open",B):E.onopen=B),P?(E.addEventListener("close",T),E.addEventListener("error",$),E.addEventListener("message",M)):(E.onclose=T,E.onerror=$,E.onmessage=M);function O(Y,W,ee){let D=new n.Transform({objectMode:Y.objectMode});return D._write=W,D._flush=ee,D}function B(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function $(Y){l("WebSocket onError",Y);let W=new Error("WebSocket error");W.event=Y,k.destroy(W)}async function M(Y){if(!I||!I.readable||!I.writable)return;let{data:W}=Y;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function U(Y,W,ee){if(E.bufferedAmount>S){setTimeout(U,v,Y,W,ee);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{E.send(Y)}catch(D){return ee(D)}ee()}function oe(Y){E.close(),Y()}return k};i.browserStreamBuilder=b}),ko={};$t(ko,{Server:()=>De,Socket:()=>De,Stream:()=>De,_createServerHandle:()=>De,_normalizeArgs:()=>De,_setSimultaneousAccepts:()=>De,connect:()=>De,createConnection:()=>De,createServer:()=>De,default:()=>gl,isIP:()=>De,isIPv4:()=>De,isIPv6:()=>De});function De(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var gl,yl=Je(()=>{le(),ue(),ce(),gl={_createServerHandle:De,_normalizeArgs:De,_setSimultaneousAccepts:De,connect:De,createConnection:De,createServer:De,isIP:De,isIPv4:De,isIPv6:De,Server:De,Socket:De,Stream:De}}),bl=pe((i,e)=>{le(),ue(),ce(),e.exports={}}),vl=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(i,"__esModule",{value:!0});var t=e((yl(),Ne(ko))),r=e(gt()),s=e(bl()),n=(0,r.default)("mqttjs:tcp"),o=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,s.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};i.default=o}),wl={};$t(wl,{default:()=>kl});var kl,Wd=Je(()=>{le(),ue(),ce(),kl={}}),_l=pe(i=>{le(),ue(),ce();var e=i&&i.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(i,"__esModule",{value:!0});var t=(Wd(),Ne(wl)),r=e((yl(),Ne(ko))),s=e(gt()),n=e(bl()),o=(0,s.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,o("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};i.default=l}),Sl=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Nt(),r=wo(),s,n,o;function a(){let p=new t.Transform;return p._write=(g,f,y)=>{s.send({data:g.buffer,success(){y()},fail(b){y(new Error(b))}})},p._flush=g=>{s.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",y=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(y=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(y=p.transformWsUrl(y,p,g)),y}function u(){s.onOpen(()=>{o.socketReady()}),s.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),s.onClose(()=>{o.emit("close"),o.end(),o.destroy()}),s.onError(p=>{let g=new Error(p.errMsg);o.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let y=c(g,p);s=wx.connectSocket({url:y,protocols:[f]}),n=a(),o=new r.BufferedDuplex(g,n,s),o._destroy=(w,m)=>{s.close({success(){m&&m(w)}})};let b=o.destroy;return o.destroy=(w,m)=>(o.destroy=b,setTimeout(()=>{s.close({fail(){o._destroy(w,m)}})},0),o),u(),o};i.default=d}),xl=pe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(qe(),Ne($e)),t=Nt(),r=wo(),s,n,o,a=!1;function l(){let g=new t.Transform;return g._write=(f,y,b)=>{s.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},g._flush=f=>{s.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let y=g.protocol==="alis"?"wss":"ws",b=`${y}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(b=`${y}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(b=g.transformWsUrl(b,g,f)),b}function d(){a||(a=!0,s.onSocketOpen(()=>{o.socketReady()}),s.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(g.data)}}),s.onSocketClose(()=>{o.end(),o.destroy()}),s.onSocketError(g=>{o.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let y=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let b=u(f,g);return s=f.my,s.connectSocket({url:b,protocols:y}),n=l(),o=new r.BufferedDuplex(f,n,s),d(),o};i.default=p}),zd=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((qd(),Ne(Ka))),s=e(Ei()),n=e(Ir());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var o=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;d.username=g,d.password=f}else d.username=d.auth}function c(d,p){if(o("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let y=r.default.parse(d,!0),b={};if(y.port!=null&&(b.port=Number(y.port)),b.host=y.hostname,b.query=y.query,b.auth=y.auth,b.protocol=y.protocol,b.path=y.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof je<"u"&&(p.socksProxy=je.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=Zr().streamBuilder,a.wss=Zr().streamBuilder,a.mqtt=vl().default,a.tcp=vl().default,a.ssl=_l().default,a.tls=a.ssl,a.mqtts=_l().default):(a.ws=Zr().browserStreamBuilder,a.wss=Zr().browserStreamBuilder,a.wx=Sl().default,a.wxs=Sl().default,a.ali=xl().default,a.alis=xl().default)),!a[p.protocol]){let y=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,w)=>y&&w%2===0?!1:typeof a[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(y){return p.servers&&((!y._reconnectCount||y._reconnectCount===p.servers.length)&&(y._reconnectCount=0),p.host=p.servers[y._reconnectCount].host,p.port=p.servers[y._reconnectCount].port,p.protocol=p.servers[y._reconnectCount].protocol?p.servers[y._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,y._reconnectCount++),o("calling streambuilder for",p.protocol),a[p.protocol](y,p)}let f=new s.default(g,p);return f.on("error",()=>{}),f}function u(d,p,g=!0){return new Promise((f,y)=>{let b=c(d,p),w={connect:k=>{m(),f(b)},end:()=>{m(),f(b)},error:k=>{m(),b.end(),y(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{b.off(k,w[k])})}Object.keys(w).forEach(k=>{b.on(k,w[k])})})}i.default=c}),El=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,f,y,b){b===void 0&&(b=y);var w=Object.getOwnPropertyDescriptor(f,y);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[y]}}),Object.defineProperty(g,b,w)}:function(g,f,y,b){b===void 0&&(b=y),g[b]=f[y]}),t=i&&i.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=i&&i.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(y){var b=[];for(var w in y)Object.prototype.hasOwnProperty.call(y,w)&&(b[b.length]=w);return b},g(f)};return function(f){if(f&&f.__esModule)return f;var y={};if(f!=null)for(var b=g(f),w=0;w<b.length;w++)b[w]!=="default"&&e(y,f,b[w]);return t(y,f),y}})(),s=i&&i.__exportStar||function(g,f){for(var y in g)y!=="default"&&!Object.prototype.hasOwnProperty.call(f,y)&&e(f,g,y)},n=i&&i.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(i,"__esModule",{value:!0}),i.ReasonCodes=i.KeepaliveManager=i.UniqueMessageIdProvider=i.DefaultMessageIdProvider=i.Store=i.MqttClient=i.connectAsync=i.connect=i.Client=void 0;var o=n(Ei());i.MqttClient=o.default;var a=n(Ms());i.DefaultMessageIdProvider=a.default;var l=n(nd());i.UniqueMessageIdProvider=l.default;var c=n(Es());i.Store=c.default;var u=r(zd());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Bs());i.KeepaliveManager=d.default,i.Client=o.default,s(Ei(),i),s(zt(),i),s(xs(),i);var p=Er();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Vd=pe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(o,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(o,c,u)}:function(o,a,l,c){c===void 0&&(c=l),o[c]=a[l]}),t=i&&i.__setModuleDefault||(Object.create?function(o,a){Object.defineProperty(o,"default",{enumerable:!0,value:a})}:function(o,a){o.default=a}),r=i&&i.__importStar||(function(){var o=function(a){return o=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},o(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=o(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),s=i&&i.__exportStar||function(o,a){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,o,l)};Object.defineProperty(i,"__esModule",{value:!0});var n=r(El());i.default=n,s(El(),i)});const Gd=Vd();const Kd={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}/#"},Yd=300,Jd={templateId:"7",type:"link",isDeepLink:!0},Qd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Al{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...Kd,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,s={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(s.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,o)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>o(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=Gd.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[s,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[s]=`${n.slice(0,200)}…(${n.length})`:r[s]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const s=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,s)}publishFileMessage(e,t){if(!this.client)return;const r={...Jd,...this.config.fileTemplate??{},...Xd(t)},s={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},o=this.buildOutgoingEnvelope(e,{text:JSON.stringify(s),type:"html",attributes:n,metadata:s.metadata});this.publishEnvelope(e,o)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Yd){if(!this.client)return;const s=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(s,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const s=[...this.subscribedTopics];this.subscribedTopics.clear(),s.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let s=null;try{s=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!s)return;this.debugLog("RECV",{topic:e,sender:s.sender,type:s.type,contentType:s.metadata?.contentType,templateId:s.metadata?.templateId,messageId:s.message_id,text:typeof s.text=="string"?s.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof s.status=="number"?s.status:Number(s.status??0),p={conversationId:c,messageId:u,status:d,raw:s};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(s,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const o=e.match(this.inboundRegex),a=o?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof s.message_id=="string"?s.message_id:void 0,kind:o?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(s,l))}buildOutgoingEnvelope(e,t){const r={...Qd,...this.config.messageDefaults??{}},s=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),o={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:s,senderFullname:s,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:o}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(s,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(s,n)=>{const o={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=o[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Xd(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function Il(i,e){return(i.sender??"").toString()===e}function Tl(i,e){const t=(i.sender??"").toString(),r=e.systemSenders??["metadata","system"],s=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(s)?"assistant":r.includes(t)?"system":"agent":"system"}function _o(i){const e={raw:i},t=i.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof i.text=="string"&&i.text.trim().startsWith("{"))try{const s=i.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(s);typeof n.message=="string"&&(e.innerMessage=n.message);const o=n.metadata;o&&typeof o=="object"&&(typeof o.contentType=="string"&&(e.contentType=o.contentType),typeof o.templateId=="string"&&(e.templateId=o.templateId),o.payload!==void 0&&(e.payload=o.payload))}catch{}const r=i.attributes;if(r&&typeof r=="object"){const s=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&s&&typeof s.contentType=="string"&&(e.contentType=s.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&s&&typeof s.templateId=="string"&&(e.templateId=s.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&s&&s.payload!==void 0&&(e.payload=s.payload),e.payload===void 0&&s&&s.template!==void 0&&(e.payload=s.template)}return e}function Cl(i){const e=_o(i);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const s=r[0],n=s.action,o=n&&typeof n.url=="string"?n.url:void 0,a=typeof s.description=="string"?s.description:void 0,l=i.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!o&&!a?null:{fileName:a,fileUrl:o,cloudFileId:c,templateId:e.templateId}}function Pl(i,e,t){const r=Tl(i,t),s=_o(i),n=Cl(i);let o="";s.innerMessage?o=s.innerMessage:typeof i.text=="string"&&(i.text.trim().startsWith("{")?s.contentType!=="300"&&(o=i.text):o=i.text);const a=typeof i.message_id=="string"?i.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof i.timestamp=="number"?new Date(i.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof i.status=="number"?Zd(i.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:o,createdAt:l,status:u,metadata:{sender:i.sender,sender_fullname:i.sender_fullname??i.senderFullname,app_id:i.app_id,attributes:i.attributes}};return s.contentType&&(d.template={contentType:s.contentType,templateId:s.templateId,payload:s.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:s}}function Zd(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class Ol extends yr{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Ho(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Wo,this.conversationManager=new Yo(e.conversationId),this.usesAikaara()&&(this.connection=new qo(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Al({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const s=r?"connected":"disconnected";this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,s)=>this.handleTiledeskMessage(r,s))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),s=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;s&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const s=r.map(l=>Pl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=s.map(l=>l.message),o=this.messageStore.messages,a=[...n,...o.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of s){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const s=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",s),this.config.onMessage?.(s);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const s=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:s.fileName,fileUrl:s.url,cloudFileId:s.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(s,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const s=t.conversationId??r;if(!s)return;const n=this.config.tiledeskIdentity?.userId??"",{message:o,template:a}=Pl(e,s,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&o.role==="assistant")return;if(Il(e,n)){const u=this.messageStore.reconcileOptimistic(o);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(o);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:s,role:o.role==="tool"?"system":o.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",s=e.content||"";s?this.messageStore.updateStreaming(s):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,s=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),s&&(this.emit("stream:end",{messageId:s.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",s),this.config.onMessage?.(s));break}case"message_queued":{const r=this.messageStore.messages.findLast(s=>s.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class eh extends yr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Ml={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function th(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function rh(i,e,t){const r=th(i.name||"");if(r&&e&&e[r])return e[r];const s=i.type;return s&&s.trim().length>0?s:r&&Ml[r]?Ml[r]:t}function So(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function nh(i,e){const t=e.split(".");let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return"";return typeof r=="string"?r:""}function Ll(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const s=t.name||`upload-${Date.now()}`,n=rh(t,i.contentTypeMap,i.contentTypeFallback??"application/octet-stream"),o={fileName:s,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=i.authHeader?await i.authHeader():void 0,l={accept:"application/json",...i.extraHeaders??{},...a?{authorization:a}:{}};let c=i.signEndpoint.includes("{")?i.signEndpoint:`${i.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=So(c,o),d=await fetch(u,{method:i.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=nh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,y=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!y.ok){const w=await y.text().catch(()=>"");throw new Error(`S3 PUT failed: ${y.status} ${w.slice(0,200)}`)}if(i.registerEndpoint){const w=JSON.parse(So(JSON.stringify(i.registerBody??{}),o)),m=await fetch(i.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?So(i.viewerTemplate,o):g.split("?")[0],fileName:s,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function xo(i){return{async upload(e,t){const r=new FormData,s=i.fieldName??"file";r.append(s,e,e.name);const n=typeof i.extraFields=="function"?i.extraFields(t):i.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const o=typeof i.headers=="function"?await i.headers():i.headers??{},a=await fetch(i.endpoint,{method:i.method??"POST",body:r,headers:o,credentials:i.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(i.parseResponse)return i.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const ih="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Rl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??ih;return{async fetchMessages(s,n){const o=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(s)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=o.startsWith("http")?o:`${e}${o.startsWith("/")?o:`/${o}`}`,l={accept:"application/json","content-type":"application/json",...i.extraHeaders??{}};if(i.getToken){const p=await i.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(i.parseResponse&&u)return i.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const oh="^[A-Z]{4}[0-9]{5}[A-Z]$",sh="^\\S{12}$",Nl="^[A-Z]{4}0[A-Z0-9]{6}$",jl="^[0-9]{6}$",ah=[{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:oh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:sh,maxLength:12}]},{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:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:Nl,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:jl}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{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:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"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:jl},{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"},{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:Nl,maxLength:11}]}],submitLabel:"Save"}];function lh(i,e){const t=i||{},r={userId:et(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:_h()};r.us80cAmount=Se(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Se(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Se(t.us80dForParentsAmount),r.hasParentOverSixty=lr(t.hasParentOverSixty),r.preventiveHealthCheckUp=Se(t.preventiveHealthCheckUp),r.medicalExpenditure=Se(t.medicalExpenditure),r.savingBankInterest=Se(t.savingBankInterest),r.fdInterest=Se(t.fdInterest),r.dividend=Se(t.dividend),r.anyOtherIncome=Se(t.anyOtherIncome),r.familyPension=Se(t.familyPension),r.cryptoSellValue=Se(t.cryptoSellPrice),r.cryptoPurchaseAmount=Se(t.cryptoPurchasePrice),r.vdaPurchaseCost=Se(t.cryptoPurchasePrice);const s=(Se(t.bizReceiptsBank)??0)+(Se(t.bizReceiptsCash)??0),n=(Se(t.profReceiptsBank)??0)+(Se(t.profReceiptsCash)??0),o=Ee(t.bizName)!==void 0||s>0;r.businessName=Ee(o?t.bizName:t.profName),r.businessAnnualTurnOver=o?s||void 0:n||void 0,r.agricultureDetails=Dl(t),r.exemptIncomeAmount=Se(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),Se(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(Se(t.exemptIncome))}]),r.bankAccountNumber=Ee(t.bankAccountNumber),r.bankIfscCode=Ee(t.bankIfscCode),(Ee(t.bankAccountNumber)||Ee(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Ee(t.bankAccountNumber),bankIfscCode:Ee(t.bankIfscCode)}]);const a={description:Ee(t.immovableAssetDescription),flatNo:Ee(t.immovableAssetFlatNo),area:Ee(t.immovableAssetArea),pinCode:Ee(t.immovableAssetPincode),amount:Se(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=Eo(t.hpDetails,ch);l.length&&(r.hpDetails=l);const c=Eo(t.salaryDetails,uh);if(c.length){r.salaryIncome=c;const u=Eo(t.salaryDetails,p=>({grossSalary:Se(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=tn(t.salaryDetails)[0]??{};r.hraAmount=Se(d.hraReceived),r.leaveTravelAllowanceAmount=Se(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Se(d.leaveEncashment),r.anyOtherAllowanceAmount=Se(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return tt(r)}function ch(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:en(i.sanctionDate),totalLoanAmount:Se(i.totalLoanAmount),loanOutstandingAmount:Se(i.outstandingAmount),interest:Se(i.homeLoanInterest)},t=Object.entries(e).some(([r,s])=>r!=="loanType"&&s!==void 0);return{typeOfHouseProperty:Ee(i.typeOfHouseProperty),hasRentalIncome:i.typeOfHouseProperty==="LOP"?!0:lr(i.hasRentalIncome),homeLoanInterest:Se(i.homeLoanInterest),homeLoanPrinciple:Se(i.homeLoanPrinciple),housePropertyAddress:Ee(i.housePropertyAddress),housePropertyPincode:Ee(i.housePropertyPincode),rentalIncome:Se(i.rentalIncome),nameOfTenant:Ee(i.nameOfTenant),propertyTax:Se(i.propertyTax),hasCoOwnedProperty:lr(i.hasCoOwnedProperty),coOwnerName:Ee(i.coOwnerName),coOwnerPan:Ee(i.coOwnerPan),coOwnerShare:Ee(i.coOwnerShare),loanDetails:t?[e]:void 0}}function uh(i){return{grossSalaryIncome:Se(i.grossSalary),salary:Se(i.basicSalary),totalTdsDeposited:Se(i.totalTdsDeposited),employer:{employerName:Ee(i.employerName),employerTan:Ee(i.employerTan)},allowance:{hraAmount:Se(i.hraReceived),leaveTravelAllowanceAmount:Se(i.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Se(i.leaveEncashment),anyOtherAllowanceAmount:Se(i.anyOtherAllowance)}}}function dh(i,e){const t=[];for(const r of i){const s=Ee(r.employerName),n=Ee(r.employerTan),o=Se(r.grossSalary),a=Se(r.basicSalary),l=Se(r.totalTdsDeposited);s===void 0&&n===void 0&&o===void 0&&a===void 0&&l===void 0||t.push({grossSalary:o??0,basicSalary:a??0,employerName:s??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:et(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function hh(i,e){const t=Ee(i.aadhaarNumber),r=Ee(i.bankAccountNumber),s=Ee(i.bankIfscCode);return t===void 0&&r===void 0&&s===void 0?null:{userId:et(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:s}]}}function fh(i,e){return{userId:et(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Se(i.savingBankInterest)??0,fdInterest:Se(i.fdInterest)??0,dividend:Se(i.dividend)??0,anyOtherIncome:Se(i.anyOtherIncome)??0,familyPension:Se(i.familyPension)??0}}function ph(i,e){const t=Se(i.cryptoSellPrice),r=Se(i.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:et(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function mh(i,e){const t=(s,n,o,a)=>{const l=Ee(i[s]),c=Ee(i[n]),u=Se(i[o]),d=Se(i[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(s=>s!==null);return r.length?{userId:et(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function gh(i){return Ee(i.lenderName)!==void 0||Ee(i.loanAccountNumber)!==void 0||Se(i.totalLoanAmount)!==void 0||Se(i.outstandingAmount)!==void 0||Se(i.homeLoanInterest)!==void 0}function Ul(i){const e=Ee(i.typeOfHouseProperty)?.toUpperCase();return Se(i.rentalIncome)!==void 0||Ee(i.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function yh(i,e){const t=tn(i.hpDetails).filter(gh).map(r=>{const s=tt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:en(r.sanctionDate),totalLoanAmount:Se(r.totalLoanAmount),loanOutstandingAmount:Se(r.outstandingAmount),interest:Se(r.homeLoanInterest)});return tt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:Se(r.homeLoanInterest),homeLoanPrinciple:Se(r.homeLoanPrinciple),propertyTax:Se(r.propertyTax),eligible80EEAAmount:Se(r.eligible80EEAAmount),eligible80EEAmount:Se(r.eligible80EEAmount),hasCoOwnedProperty:lr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Ul(r),loanDetails:[s]})});return t.length?{userId:et(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function bh(i,e){const t=tn(i.hpDetails).filter(Ul).map(r=>tt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:Se(r.rentalIncome),propertyTax:Se(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:Se(r.homeLoanInterest)}));return t.length?{userId:et(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function vh(i,e){const t=i||{},r=g=>({userId:et(e.userId),assessmentYear:e.assessmentYear,deductions:tt(g)}),s=[],n=Se(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?s.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const o=Ee(t.us80ccd1bPanNo),a=Se(t.us80ccd1bAmount);a!==void 0&&s.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:o}));const l=Se(t.us80ccd2Amount);l!==void 0&&s.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:o}));const c=Se(t.us80eInterest);c!==void 0&&s.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:en(t.us80eLoanSanctionDate),totalLoanAmount:Se(t.us80eLoanAmount),loanOutstandingAmount:Se(t.us80eOutstandingLoan)}));const u=Se(t.us80eeInterest);u!==void 0&&s.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:en(t.us80eeLoanSanctionDate),totalLoanAmount:Se(t.us80eeLoanAmount),loanOutstandingAmount:Se(t.us80eeOutstandingLoan),vehicleRegistrationNumber:Ee(t.us80eeVehicleRegistrationNumber)}));const d=Se(t.us80dForSelfAndFamilyAmount);d!==void 0&&s.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=Se(t.us80dForParentsAmount);return p!==void 0&&s.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:lr(t.hasParentOverSixty)??!1})),s}function wh(i,e){const t=i||{},r=Se(t.us80gDonationInCash),s=Se(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&s===void 0&&n===void 0)return null;const o=(s??0)>0;return{userId:et(e.userId),assessmentYear:e.assessmentYear,donations80g:[tt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:s,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionReferenceNo:o?Ee(t.us80gTransactionRefNo):void 0,ifscCode:o?Ee(t.us80gIfscCode):void 0})]}}function Dl(i){const e=i||{},t=Se(e.agricultureIncome),r=Se(e.agricultureExpenditure),s=tt({landInAcre:Se(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(s).length>0;if(!(t===void 0&&r===void 0&&!n))return tt({income:t,expenditure:r??0,agricultureLandDetails:n?[s]:void 0})}function kh(i,e){const t=Dl(i);return t?{userId:et(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function et(i){if(i===void 0||i==="")return;const e=Number(i);return Number.isFinite(e)&&String(e)===String(i)?e:i}function Se(i){if(i==null||i==="")return;const e=typeof i=="number"?i:Number(i);return Number.isFinite(e)?e:void 0}function Ee(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function lr(i){return i===!0||i===!1?i:void 0}function _h(){const i=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}T${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${e(i.getMilliseconds(),3)}`}function en(i){const e=Ee(i);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function tn(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Eo(i,e){return tn(i).map(t=>tt(e(t))).filter(t=>t!==void 0)}function tt(i){if(Array.isArray(i)){const e=i.map(tt).filter(t=>t!==void 0);return e.length?e:void 0}if(i&&typeof i=="object"){const e={};for(const[t,r]of Object.entries(i)){const s=tt(r);s!==void 0&&(e[t]=s)}return Object.keys(e).length?e:void 0}return i}function Sh(i){const e=i&&typeof i=="object"?i:{},t={},r=Ue(e.employers),s=Ue(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(M=>{const U=Ao(M.salary),oe=Ao(M.perquisites),Y=Ao(M.profitsInLieuOfSalaryType),W=U+oe+Y,ee=Ih(M.allowance);return{employerName:Ce(M.employerName),employerTan:Ce(M.employerTAN),basicSalary:U||void 0,grossSalary:W||void 0,hraReceived:ee.hra,leaveTravelAllowance:ee.lta,leaveEncashment:ee.leaveEncashment,anyOtherAllowance:ee.other,totalTdsDeposited:Ah(M,s,r)??Re(M.totalTdsDeposited)}}));const n=Ue(e.houseProperties);n.length&&(t.hpDetails=n.map(M=>{const U=Ue(M.loanDetails),oe=U.length?U[0]:void 0,Y=Re(M.grossAnnualRentReceived),W=U.length?U.reduce((J,ge)=>J+(Re(ge.interest)??0),0):void 0,ee=Ue(M.tenant),D=Ue(M.coOwners),X=ee[0],L=D[0];return{typeOfHouseProperty:Ce(M.propertyType),loanTakenFrom:Ce(oe?.loanTakenFrom),lenderName:Ce(oe?.bankOrInstituteName),loanAccountNumber:Ce(oe?.loanAccountNo),sanctionDate:Bl(oe?.loanSanctionDate),totalLoanAmount:Re(oe?.totalLoanAmount),outstandingAmount:Re(oe?.loanOutstandingAmount),homeLoanInterest:W,homeLoanPrinciple:void 0,housePropertyAddress:Ce(M.address),housePropertyPincode:Ce(M.pinCode),rentalIncome:Y,nameOfTenant:Ce(X?.name),tenantPanNumber:Ce(X?.panNumber),eligible80EEAmount:Re(M.eligible80EEAmount),eligible80EEAAmount:Re(M.eligible80EEAAmount),propertyTax:Re(M.propertyTax),hasCoOwnedProperty:D.length>0,coOwnerName:Ce(L?.name),coOwnerPan:Ce(L?.panNumber),coOwnerShare:Re(L?.share)?.toString()}}));const o=Ue(e.deductionUS80CDetails),a=Ct(o.map(M=>Re(M.amount))),l=o.find(M=>Ce(M.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=Ue(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=Ue(e.deductionUS80DDetails),p=d.find(M=>Ce(M.policyFor)?.toUpperCase()==="DEPENDANT")??Ue(e.insurances).find(M=>Ce(M.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(M=>Ce(M.policyFor)?.toUpperCase()==="PARENTS")??Ue(e.insurances).find(M=>Ce(M.policyFor)?.toUpperCase()==="PARENTS"),f=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,y=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Re(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??f?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??f?.accountNo),t.us80dForParentsAmount=Re(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??y?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??y?.accountNo),t.hasParentOverSixty=Th(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=Ue(e.donations)[0];t.us80gDonationInCash=Re(w?.amountInCash??w?.donationInCash),t.us80gDonationOnline=Re(w?.amountOtherThanCash??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),t.us80gTransactionRefNo=Ce(w?.transactionReferenceNo??w?.transactionRefNo),t.us80gIfscCode=Ce(w?.ifscCode??w?.ifsCode);const k=Ue(e.houseProperties?.[0]?.loanDetails)[0];t.us80eLoanTakenFrom=void 0,t.us80eBankName=void 0,t.us80eLoanAccountNumber=void 0,t.us80eLoanSanctionDate=void 0,t.us80eLoanAmount=void 0,t.us80eeLoanTakenFrom=Ce(k?.loanTakenFrom),t.us80eeBankName=Ce(k?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(k?.loanAccountNo),t.us80eeLoanSanctionDate=Bl(k?.loanSanctionDate),t.us80eeLoanAmount=Re(k?.totalLoanAmount),t.us80eeOutstandingLoan=Re(k?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(k?.vehicleRegistrationNo);const S=Ue(e.insurances);t.preventiveHealthCheckUp=Ct(S.map(M=>Re(M.preventiveCheckUp))),t.medicalExpenditure=Ct(S.map(M=>Re(M.medicalExpenditure)));const v=Ue(e.incomes),x=M=>Ct(v.filter(U=>Ce(U.incomeType)===M).map(U=>Re(U.amount)));t.savingBankInterest=x("SAVING_INTEREST"),t.fdInterest=x("FD_RD_INTEREST"),t.anyOtherIncome=x("ANY_OTHER"),t.familyPension=x("FAMILY_PENSION"),t.dividend=Ct(Ue(e.dividendIncomes).map(M=>Re(M.income)));const E=e.business;if(E){const M=Ue(E.presumptiveIncomes),U=W=>{const ee=Ue(W.incomes),D=X=>Re(ee.find(L=>Ce(L.incomeType)===X)?.receipts)??0;return D("ANY_OTHER")>0?!0:D("BANK")>0||D("CASH")>0?!1:!!Ce(W.businessType)?.toUpperCase().includes("PROFESSION")},oe=W=>M.find(ee=>U(ee)===W),Y=(W,ee)=>{if(!W)return;const D=Ue(W.incomes),X=J=>Re(D.find(ge=>Ce(ge.incomeType)===J)?.receipts),L=X("BANK")||X("ANY_OTHER");t[ee.name]=Ce(W.businessType),t[ee.nature]=Ce(W.natureOfBusiness),t[ee.bank]=L||void 0,t[ee.cash]=X("CASH")||void 0,t[ee.net]=Ct(D.map(J=>Re(J.presumptiveIncome)))||void 0};Y(oe(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),Y(oe(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const I=Ue(e.capitalGain).filter(M=>Ce(M.assetType)?.toUpperCase()==="VDA").flatMap(M=>Ue(M.assetDetails));I.length&&(t.cryptoSellPrice=Ct(I.map(M=>Re(M.sellValue))),t.cryptoPurchasePrice=Ct(I.map(M=>Re(M.purchaseCost))));const P=e.agriculturalDetails,O=e.agriculturalIncome;t.agricultureIncome=Re(O?.netAgriculturalIncome)??Re(O?.grossAgriculturalReceipts)??Re(P?.income),t.agricultureExpenditure=Re(O?.expenditureIncurredOnAgriculture)??Re(P?.expenditure);const T=Ue(P?.agricultureLandDetails??P?.agriculturalLandDetails??e.agriculturalLandDetails)[0];T&&(t.agricultureLandInAcre=Re(T.landInAcre),t.agricultureLandDistrict=Ce(T.nameOfDistrict),t.agricultureLandPincode=Ce(T.pinCode),t.agricultureLandOwner=xh(T.owner),t.agricultureLandType=Eh(T.typeOfLand)),t.aadhaarNumber=Ce(e.aadharNumber);const $=Ue(e.bankDetails)[0];return $&&(t.bankAccountNumber=Ce($.accountNumber),t.bankIfscCode=Ce($.ifsCode)),Fl(t)}function xh(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 Eh(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 Bl(i){const e=Ce(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Ao(i){return Ue(i).reduce((e,t)=>e+(Re(t.taxableAmount)??0),0)}function Ah(i,e,t){if(!e.length)return;const r=Ce(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Re(n.totalTdsDeposited)}const s=Ce(i.employerName)?.trim().toLowerCase();if(s){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===s)return Re(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Re(e[0].totalTdsDeposited)}function Ih(i){const e=Ue(i);if(!e.length)return{};let t,r,s,n;for(const o of e){const a=Re(o.exemptAmount)??Re(o.allowanceAmount);switch(Ce(o.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":s=a;break;default:n=(n??0)+(Re(o.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:s,other:n}}function Ct(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function Ue(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Re(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Ce(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function Th(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 Fl(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(Array.isArray(r)?e[t]=r.map(s=>s&&typeof s=="object"?Fl(s):s):e[t]=r);return e}function Io(){if(typeof window>"u")return null;const i=window,e=i.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=i.__aikaara_descriptor__??{},r=Bh(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const s=Fh(e.slug),n=typeof s?.tenantJwt=="string"?s.tenantJwt:"",o=e.getChatJwt,a=async()=>n||await o(),l=(s&&s.userId!=null&&s.userId!==""?String(s.userId):qh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:$h(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Hh(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Ch(i){const e=await i.getToken(),t=i.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${i.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...i.headers}});if(!r.ok){const s=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${s.slice(0,200)}`)}return Sh(To(await r.json().catch(()=>({}))))}async function Ph(i,e){const t=await i.getToken(),r=i.userId,s={...lh(e,{userId:r,assessmentYear:i.assessmentYear,isRevised:i.isRevised}),sendSummary:!0},n=i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...i.headers};i.txbdyApiKey&&(o["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(s).join(", "));const a=await fetch(n,{method:"PUT",headers:o,body:JSON.stringify(s)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return To(await a.json().catch(()=>({})))}async function Oh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function Mh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function $l(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Lh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Rh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Nh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function jh(i,e){return wt(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Uh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Dh(i,e){return wt(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function wt(i,e,t){const s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await i.getToken()}`,...i.headers};i.txbdyApiKey&&(s["txbdy-api-key"]=i.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:s,body:JSON.stringify(t)});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${o.slice(0,200)}`)}return To(await n.json().catch(()=>({})))}function Bh(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 Fh(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 $h(i){const e={};if(!i)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,s]of Object.entries(i))!t.test(r)&&typeof s=="string"&&(e[r]=s);return e}function qh(i){if(!i)return;const e=i.userId??i.id??i.ext_uid??i.extUid;return e==null||e===""?void 0:String(e)}function To(i){if(i&&typeof i=="object"){const e=i;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Hh(){const i=new Date,e=i.getMonth()>=3?i.getFullYear():i.getFullYear()-1;return`${e}-${e+1}`}const Wh=["No, I have a concerns"];class zh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Ol(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.shouldOpenSmartEdit(t.text),s=this.client.config.templateActionAttributes??{},n=t.attributes?.action??{},o={...t.attributes,action:{...s,...n}};this.handleSend(t.text,o).then(()=>{r&&this.openSmartEdit()})})}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,r=Array.isArray(t)?t:Wh;if(!Array.isArray(r)||r.length===0)return!1;const s=o=>o.trim().toLowerCase(),n=s(e);return r.some(o=>typeof o=="string"&&s(o)===n)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:ah,data:{}});const t=Io();if(!(!t||!t.baseUrl))try{const r=await Ch(t);e.setData(r)}catch(r){console.warn("[smart-edit] fetch failed",r),this.errorBanner.show("Could not load your ITR details — starting from a blank form.",4e3)}}ensureSmartEditModal(){if(this.smartEditModal)return this.smartEditModal;const e=document.createElement("aikaara-smart-edit-modal");return document.body.appendChild(e),e.addEventListener("smart-edit-submit",(t=>{const r=t.detail;this.handleSectionSubmit(r.sectionId,r.record)})),e.addEventListener("smart-edit-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSectionSubmit(e,t){const r=Io();if(!r)return;const s={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],o=dh(n,s);o&&await Oh(r,o)}else if(e==="bank-details"){const n=hh(t,s);n&&await Mh(r,n)}else if(e==="other-sources")await $l(r,fh(t,s));else if(e==="business-profession"){const n=mh(t,s);n&&await Lh(r,n)}else if(e==="crypto-income"){const n=ph(t,s);n&&await Dh(r,n)}else if(e==="agricultural-income"){const n=kh(t,s);n&&await Rh(r,n)}else if(e==="deductions"){for(const o of vh(t,s))await Nh(r,o);const n=wh(t,s);n&&await $l(r,n)}else if(e==="house-property"){const n=yh(t,s);n&&await jh(r,n);const o=bh(t,s);o&&await Uh(r,o)}}catch(n){console.warn("[smart-edit] section save failed",e,n),this.errorBanner.show("Failed to save. Please try again.",4e3)}}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Io();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Ph(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||Dc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Fo,position:this.getAttribute("position")||this._config.position||Uc,width:Number(this.getAttribute("width"))||this._config.width||Lc,height:Number(this.getAttribute("height"))||this._config.height||Rc,fontFamily:this._config.fontFamily||jc,borderRadius:this._config.borderRadius??Nc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||$o,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,chatActions:this._config.chatActions,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Bc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,s){if(typeof document>"u")return;const n=document.documentElement,o=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};o("primary",e?.primary??t),o("primary-hover",e?.primaryHover),o("primary-contrast",e?.primaryContrast),o("surface",e?.surface),o("surface-muted",e?.surfaceMuted),o("border",e?.border),o("text",e?.text),o("text-muted",e?.textMuted),o("font",e?.font??s),o("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),o("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),o("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),o("user-bubble-bg",e?.userBubbleBg),o("user-bubble-text",e?.userBubbleText),o("bot-bubble-bg",e?.botBubbleBg),o("bot-bubble-text",e?.botBubbleText),o("modal-width",e?.modalWidth),o("modal-height",e?.modalHeight),o("modal-max-width",e?.modalMaxWidth),o("modal-max-height",e?.modalMaxHeight),o("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=s=>typeof s=="number"?`${s}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,s])=>s!==void 0&&s!=="").map(([s,n])=>`--aikaara-${s}: ${n};`).join(`
|
|
6
|
+
`+ie.prev}function _e(V,ie){var Ie=ge(V),Te=[];if(Ie){Te.length=V.length;for(var Oe=0;Oe<V.length;Oe++)Te[Oe]=se(V,Oe)?ie(V[Oe],V):""}var Ne=typeof T=="function"?T(V):[],at;if(L){at={};for(var lt=0;lt<Ne.length;lt++)at["$"+Ne[lt]]=Ne[lt]}for(var Ge in V)se(V,Ge)&&(Ie&&String(Number(Ge))===Ge&&Ge<V.length||L&&at["$"+Ge]instanceof Symbol||(S.call(/[^\w$]/,Ge)?Te.push(ie(Ge,V)+": "+ie(V[Ge],V)):Te.push(Ge+": "+ie(V[Ge],V))));if(typeof T=="function")for(var ct=0;ct<Ne.length;ct++)oe.call(V,Ne[ct])&&Te.push("["+ie(Ne[ct])+"]: "+ie(V[Ne[ct]],V));return Te}return Gr}function zd(){if(yo)return Jr;yo=!0;var i=Gt(),e=Pd(),t=Wd(),r=cr(),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),h=function(y,w){for(var m=y,k;(k=m.next)!==null;m=k)if(k.key===w)return m.next=k.next,k.next=y.next,y.next=k,k},g=function(y,w){var m=h(y,w);return m&&m.value},p=function(y,w,m){var k=h(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!h(y,w)};return Jr=function(){var y,w,m,k={assert:function(x){if(!k.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}),p(m,x,v))}};return k},Jr}function go(){if(vo)return Qr;vo=!0;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Qr={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Qr}function rl(){if(wo)return Xr;wo=!0;var i=go(),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 k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},s=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,S){if(e.call(w,S)){var E=w[S];E&&typeof E=="object"&&v&&typeof v=="object"?w[S]=y(E,v,k):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,k):v[S]=E,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,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 U=I.charCodeAt(O);if(U===45||U===46||U===95||U===126||U>=48&&U<=57||U>=65&&U<=90||U>=97&&U<=122||x===i.RFC1738&&(U===40||U===41)){P[P.length]=I.charAt(O);continue}if(U<128){P[P.length]=r[U];continue}if(U<2048){P[P.length]=r[192|U>>6]+r[128|U&63];continue}if(U<55296||U>=57344){P[P.length]=r[224|U>>12]+r[128|U>>6&63]+r[128|U&63];continue}O+=1,U=65536+((U&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|U>>18]+r[128|U>>12&63]+r[128|U>>6&63]+r[128|U&63]}S+=P.join("")}return S},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var x=w[k],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},h=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))},p=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],k=0;k<y.length;k+=1)m.push(w(y[k]));return m}return w(y)};return Xr={arrayToObject:n,assign:a,combine:p,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:h,maybeMap:b,merge:s},Xr}function Vd(){if(ko)return Zr;ko=!0;var i=zd(),e=rl(),t=go(),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"},h={},g=function b(y,w,m,k,x,v,S,E,I,P,O,U,T,F,L,D,oe,Y){for(var W=y,ee=Y,$=0,X=!1;(ee=ee.get(h))!==void 0&&!X;){var M=ee.get(y);if($+=1,typeof M<"u"){if(M===$)throw new RangeError("Cyclic object value");X=!0}typeof ee.get(h)>"u"&&($=0)}if(typeof P=="function"?W=P(w,W):W instanceof Date?W=T(W):m==="comma"&&n(W)&&(W=e.maybeMap(W,function(N){return N instanceof Date?T(N):N})),W===null){if(v)return I&&!D?I(w,u.encoder,oe,"key",F):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var J=D?w:I(w,u.encoder,oe,"key",F);return[L(J)+"="+L(I(W,u.encoder,oe,"value",F))]}return[L(w)+"="+L(String(W))]}var ge=[];if(typeof W>"u")return ge;var re;if(m==="comma"&&n(W))D&&I&&(W=e.maybeMap(W,I)),re=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))re=P;else{var we=Object.keys(W);re=O?we.sort(O):we}var K=E?w.replace(/\./g,"%2E"):w,j=k&&n(W)&&W.length===1?K+"[]":K;if(x&&n(W)&&W.length===0)return j+"[]";for(var ne=0;ne<re.length;++ne){var z=re[ne],G=typeof z=="object"&&typeof z.value<"u"?z.value:W[z];if(!(S&&G===null)){var Q=U&&E?z.replace(/\./g,"%2E"):z,be=n(W)?typeof m=="function"?m(j,Q):j:j+(U?"."+Q:"["+Q+"]");Y.set(y,$);var se=i();se.set(h,Y),a(ge,b(G,be,m,k,x,v,S,E,m==="comma"&&D&&n(W)?null:I,P,O,U,T,F,L,D,oe,se))}}return ge},p=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],k=u.filter;(typeof b.filter=="function"||n(b.filter))&&(k=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:k,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 Zr=function(b,y){var w=b,m=p(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var S=o[m.arrayFormat],E=S==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=i(),P=0;P<k.length;++P){var O=k[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 U=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&"),U.length>0?T+U:""},Zr}function Kd(){if(_o)return en;_o=!0;var i=rl(),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(h){return h.replace(/&#(\d+);/g,function(g,p){return String.fromCharCode(parseInt(p,10))})},n=function(h,g){return h&&typeof h=="string"&&g.comma&&h.indexOf(",")>-1?h.split(","):h},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(h,g){var p={__proto__:null},b=g.ignoreQueryPrefix?h.replace(/^\?/,""):h;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,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===s&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],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(U){return g.decoder(U,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(p,I);O&&g.duplicates==="combine"?p[I]=i.combine(p[I],P):(!O||g.duplicates==="last")&&(p[I]=P)}return p},c=function(h,g,p,b){for(var y=b?g:n(g,p),w=h.length-1;w>=0;--w){var m,k=h[w];if(k==="[]"&&p.parseArrays)m=p.allowEmptyArrays&&(y===""||p.strictNullHandling&&y===null)?[]:[].concat(y);else{m=p.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=p.decodeDotInKeys?x.replace(/%2E/g,"."):x,S=parseInt(v,10);!p.parseArrays&&v===""?m={0:y}:!isNaN(S)&&k!==v&&String(S)===v&&S>=0&&p.parseArrays&&S<=p.arrayLimit?(m=[],m[S]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(h,g,p,b){if(h){var y=p.allowDots?h.replace(/\.([^.[]+)/g,"[$1]"):h,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=p.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!p.plainObjects&&e.call(Object.prototype,x)&&!p.allowPrototypes)return;v.push(x)}for(var S=0;p.depth>0&&(k=m.exec(y))!==null&&S<p.depth;){if(S+=1,!p.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!p.allowPrototypes)return;v.push(k[1])}if(k){if(p.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+p.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,p,b)}},d=function(h){if(!h)return r;if(typeof h.allowEmptyArrays<"u"&&typeof h.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof h.decodeDotInKeys<"u"&&typeof h.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(h.decoder!==null&&typeof h.decoder<"u"&&typeof h.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof h.charset<"u"&&h.charset!=="utf-8"&&h.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof h.charset>"u"?r.charset:h.charset,p=typeof h.duplicates>"u"?r.duplicates:h.duplicates;if(p!=="combine"&&p!=="first"&&p!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof h.allowDots>"u"?h.decodeDotInKeys===!0?!0:r.allowDots:!!h.allowDots;return{allowDots:b,allowEmptyArrays:typeof h.allowEmptyArrays=="boolean"?!!h.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof h.allowPrototypes=="boolean"?h.allowPrototypes:r.allowPrototypes,allowSparse:typeof h.allowSparse=="boolean"?h.allowSparse:r.allowSparse,arrayLimit:typeof h.arrayLimit=="number"?h.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof h.charsetSentinel=="boolean"?h.charsetSentinel:r.charsetSentinel,comma:typeof h.comma=="boolean"?h.comma:r.comma,decodeDotInKeys:typeof h.decodeDotInKeys=="boolean"?h.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof h.decoder=="function"?h.decoder:r.decoder,delimiter:typeof h.delimiter=="string"||i.isRegExp(h.delimiter)?h.delimiter:r.delimiter,depth:typeof h.depth=="number"||h.depth===!1?+h.depth:r.depth,duplicates:p,ignoreQueryPrefix:h.ignoreQueryPrefix===!0,interpretNumericEntities:typeof h.interpretNumericEntities=="boolean"?h.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof h.parameterLimit=="number"?h.parameterLimit:r.parameterLimit,parseArrays:h.parseArrays!==!1,plainObjects:typeof h.plainObjects=="boolean"?h.plainObjects:r.plainObjects,strictDepth:typeof h.strictDepth=="boolean"?!!h.strictDepth:r.strictDepth,strictNullHandling:typeof h.strictNullHandling=="boolean"?h.strictNullHandling:r.strictNullHandling}};return en=function(h,g){var p=d(g);if(h===""||h===null||typeof h>"u")return p.plainObjects?Object.create(null):{};for(var b=typeof h=="string"?l(h,p):h,y=p.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],p,typeof h=="string");y=i.merge(y,x,p)}return p.allowSparse===!0?y:i.compact(y)},en}function Gd(){if(xo)return tn;xo=!0;var i=Vd(),e=Kd(),t=go();return tn={formats:t,parse:e,stringify:i},tn}function Yd(){if(So)return Pt;So=!0;var i=Tt;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}$/,h=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},p={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=Gd();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),U=/\\/g;O[0]=O[0].replace(U,"/"),v=O.join(P);var T=v;if(T=T.trim(),!E&&v.split("#").length===1){var F=o.exec(T);if(F)return this.path=T,this.href=T,this.pathname=F[1],F[2]?(this.search=F[2],S?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):S&&(this.search="",this.query={}),this}var L=t.exec(T);if(L){L=L[0];var D=L.toLowerCase();this.protocol=D,T=T.substr(L.length)}if(E||L||T.match(/^\/\/[^@/]+@[^@/]+/)){var oe=T.substr(0,2)==="//";oe&&!(L&&p[L])&&(T=T.substr(2),this.slashes=!0)}if(!p[L]&&(oe||L&&!b[L])){for(var Y=-1,W=0;W<c.length;W++){var ee=T.indexOf(c[W]);ee!==-1&&(Y===-1||ee<Y)&&(Y=ee)}var $,X;Y===-1?X=T.lastIndexOf("@"):X=T.lastIndexOf("@",Y),X!==-1&&($=T.slice(0,X),T=T.slice(X+1),this.auth=decodeURIComponent($)),Y=-1;for(var W=0;W<l.length;W++){var ee=T.indexOf(l[W]);ee!==-1&&(Y===-1||ee<Y)&&(Y=ee)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var J=this.hostname.split(/\./),W=0,ge=J.length;W<ge;W++){var re=J[W];if(re&&!re.match(d)){for(var we="",K=0,j=re.length;K<j;K++)re.charCodeAt(K)>127?we+="x":we+=re[K];if(!we.match(d)){var ne=J.slice(0,W),z=J.slice(W+1),G=re.match(h);G&&(ne.push(G[1]),z.unshift(G[2])),z.length&&(T="/"+z.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=i.toASCII(this.hostname));var Q=this.port?":"+this.port:"",be=this.hostname||"";this.host=be+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 W=0,ge=a.length;W<ge;W++){var se=a[W];if(T.indexOf(se)!==-1){var N=encodeURIComponent(se);N===se&&(N=escape(se)),T=T.split(se).join(N)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));var te=T.indexOf("?");if(te!==-1?(this.search=T.substr(te),this.query=T.substr(te+1),S&&(this.query=y.parse(this.query)),T=T.slice(0,te)):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 U=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),U&&U.charAt(0)!=="?"&&(U="?"+U),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),U=U.replace("#","%23"),S+P+E+U+I};function k(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 U=Object.keys(v),T=0;T<U.length;T++){var F=U[T];F!=="protocol"&&(E[F]=v[F])}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 L=Object.keys(v),D=0;D<L.length;D++){var oe=L[D];E[oe]=v[oe]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!p[v.protocol]){for(var ge=(v.pathname||"").split("/");ge.length&&!(v.host=ge.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),ge[0]!==""&&ge.unshift(""),ge.length<2&&ge.unshift(""),E.pathname=ge.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var Y=E.pathname||"",W=E.search||"";E.path=Y+W}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var ee=E.pathname&&E.pathname.charAt(0)==="/",$=v.host||v.pathname&&v.pathname.charAt(0)==="/",X=$||ee||E.host&&v.pathname,M=X,J=E.pathname&&E.pathname.split("/")||[],ge=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&&(ge[0]===""?ge[0]=v.host:ge.unshift(v.host)),v.host=null),X=X&&(ge[0]===""||J[0]==="")),$)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=ge;else if(ge.length)J||(J=[]),J.pop(),J=J.concat(ge),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 K=J.slice(-1)[0],j=(E.host||v.host||J.length>1)&&(K==="."||K==="..")||K==="",ne=0,z=J.length;z>=0;z--)K=J[z],K==="."?J.splice(z,1):K===".."?(J.splice(z,1),ne++):ne&&(J.splice(z,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 G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(re){E.hostname=G?"":J.length?J.shift():"",E.host=E.hostname;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return X=X||E.host&&J.length,X&&!G&&J.unshift(""),J.length>0?E.pathname=J.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,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)},Pt.parse=w,Pt.resolve=k,Pt.resolveObject=x,Pt.format=m,Pt.Url=e,Pt}function nl(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 rn?Jd(i):Qd(i)}function Jd(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(bl,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<ml||r>gl||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Qd(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 il(i){let e=mo.resolve(i),t=i.charCodeAt(i.length-1);(t===fl||rn&&t===pl)&&e[e.length-1]!==mo.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(yl,"%25")),!rn&&e.includes("\\")&&(e=e.replace(vl,"%5C")),e.includes(`
|
|
8
|
+
`)&&(e=e.replace(wl,"%0A")),e.includes("\r")&&(e=e.replace(kl,"%0D")),e.includes(" ")&&(e=e.replace(_l,"%09")),r.pathname=e,r}var ol,Gr,bo,Yr,Jr,yo,Qr,vo,Xr,wo,Zr,ko,en,_o,tn,xo,Pt,So,Ve,sl,al,ll,cl,ul,dl,hl,pl,fl,ml,gl,rn,bl,yl,vl,wl,kl,_l,Xd=Qe(()=>{le(),ue(),ce(),md(),Od(),Hd(),el(),ol=Object.freeze(Object.create(null)),Gr={},bo=!1,Yr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Jr={},yo=!1,Qr={},vo=!1,Xr={},wo=!1,Zr={},ko=!1,en={},_o=!1,tn={},xo=!1,Pt={},So=!1,Ve=Yd(),Ve.parse,Ve.resolve,Ve.resolveObject,Ve.format,Ve.Url,sl=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ve.URL=typeof URL<"u"?URL:null,Ve.pathToFileURL=il,Ve.fileURLToPath=nl,al=Ve.Url,ll=Ve.format,cl=Ve.resolve,ul=Ve.resolveObject,dl=Ve.parse,hl=Ve.URL,pl=92,fl=47,ml=97,gl=122,rn=sl==="win32",bl=/\//g,yl=/%/g,vl=/\\/g,wl=/\n/g,kl=/\r/g,_l=/\t/g}),Zd=fe((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")}}),Eo=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0}),i.BufferedDuplex=void 0,i.writev=r;var e=Dt(),t=(He(),je(qe));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}),nn=fe(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=(He(),je(qe)),r=e(Zd()),o=e(yt()),n=Dt(),s=e(Or()),a=Eo(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!s.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(k=>{Object.prototype.hasOwnProperty.call(w,k)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,k)&&(m.wsOptions[k]=w[k])}),m}function h(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function p(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),S=r.default.createWebSocketStream(v,k.wsOptions);return S.url=x,v.on("close",()=>{S.destroy()}),S};i.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=h(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,S=!m.objectMode,E=p(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?(k=I,k.socket=E):(k=new a.BufferedDuplex(m,I,E),P?E.addEventListener("open",U):E.onopen=U),P?(E.addEventListener("close",T),E.addEventListener("error",F),E.addEventListener("message",L)):(E.onclose=T,E.onerror=F,E.onmessage=L);function O(Y,W,ee){let $=new n.Transform({objectMode:Y.objectMode});return $._write=W,$._flush=ee,$}function U(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function F(Y){l("WebSocket onError",Y);let W=new Error("WebSocket error");W.event=Y,k.destroy(W)}async function L(Y){if(!I||!I.readable||!I.writable)return;let{data:W}=Y;W instanceof ArrayBuffer?W=t.Buffer.from(W):W instanceof Blob?W=t.Buffer.from(await new Response(W).arrayBuffer()):W=t.Buffer.from(W,"utf8"),I.push(W)}function D(Y,W,ee){if(E.bufferedAmount>x){setTimeout(D,v,Y,W,ee);return}S&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{E.send(Y)}catch($){return ee($)}ee()}function oe(Y){E.close(),Y()}return k};i.browserStreamBuilder=y}),Ao={};Ht(Ao,{Server:()=>Ue,Socket:()=>Ue,Stream:()=>Ue,_createServerHandle:()=>Ue,_normalizeArgs:()=>Ue,_setSimultaneousAccepts:()=>Ue,connect:()=>Ue,createConnection:()=>Ue,createServer:()=>Ue,default:()=>xl,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 xl,Sl=Qe(()=>{le(),ue(),ce(),xl={_createServerHandle:Ue,_normalizeArgs:Ue,_setSimultaneousAccepts:Ue,connect:Ue,createConnection:Ue,createServer:Ue,isIP:Ue,isIPv4:Ue,isIPv6:Ue,Server:Ue,Socket:Ue,Stream:Ue}}),El=fe((i,e)=>{le(),ue(),ce(),e.exports={}}),Al=fe(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((Sl(),je(Ao))),r=e(yt()),o=e(El()),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}),Il={};Ht(Il,{default:()=>Tl});var Tl,eh=Qe(()=>{le(),ue(),ce(),Tl={}}),Cl=fe(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=(eh(),je(Il)),r=e((Sl(),je(Ao))),o=e(yt()),n=e(El()),s=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:h,...g}=c;if(h!==void 0){let p=(0,n.default)(u,d,h,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:p})}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",h)});function h(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",h),d};i.default=l}),Pl=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=Dt(),r=Eo(),o,n,s;function a(){let h=new t.Transform;return h._write=(g,p,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},h._flush=g=>{o.close({success(){g()}})},h}function l(h){h.hostname||(h.hostname="localhost"),h.path||(h.path="/"),h.wsOptions||(h.wsOptions={})}function c(h,g){let p=h.protocol==="wxs"?"wss":"ws",b=`${p}://${h.hostname}${h.path}`;return h.port&&h.port!==80&&h.port!==443&&(b=`${p}://${h.hostname}:${h.port}${h.path}`),typeof h.transformWsUrl=="function"&&(b=h.transformWsUrl(b,h,g)),b}function u(){o.onOpen(()=>{s.socketReady()}),o.onMessage(h=>{let{data:g}=h;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(h=>{let g=new Error(h.errMsg);s.destroy(g)})}var d=(h,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let p=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,h);o=wx.connectSocket({url:b,protocols:[p]}),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}),Ol=fe(i=>{le(),ue(),ce(),Object.defineProperty(i,"__esModule",{value:!0});var e=(He(),je(qe)),t=Dt(),r=Eo(),o,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(p,b,y)=>{o.sendSocketMessage({data:p.buffer,success(){y()},fail(){y(new Error)}})},g._flush=p=>{o.closeSocket({success(){p()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,p){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,p)),y}function d(){a||(a=!0,o.onSocketOpen(()=>{s.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let p=e.Buffer.from(g.data,"base64");n.push(p)}else{let p=new FileReader;p.addEventListener("load",()=>{if(p.result instanceof ArrayBuffer){n.push(e.Buffer.from(p.result));return}n.push(e.Buffer.from(p.result,"utf-8"))}),p.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{s.end(),s.destroy()}),o.onSocketError(g=>{s.destroy(g)}))}var h=(g,p)=>{if(p.hostname=p.hostname||p.host,!p.hostname)throw new Error("Could not determine host. Specify host manually.");let b=p.protocolId==="MQIsdp"&&p.protocolVersion===3?"mqttv3.1":"mqtt";c(p);let y=u(p,g);return o=p.my,o.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(p,n,o),d(),s};i.default=h}),th=fe(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(yt()),r=e((Xd(),je(tl))),o=e(Pi()),n=e(Or());typeof De?.nextTick!="function"&&(De.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let h;if(d.auth)if(h=d.auth.match(/^(.+):(.+)$/),h){let[,g,p]=h;d.username=g,d.password=p}else d.username=d.auth}function c(d,h){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!h&&(h=d,d=""),h=h||{},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,h={...y,...h},!h.protocol)throw new Error("Missing protocol");h.protocol=h.protocol.replace(/:$/,"")}if(h.unixSocket=h.unixSocket||h.protocol?.includes("+unix"),h.unixSocket?h.protocol=h.protocol.replace("+unix",""):!h.protocol?.startsWith("ws")&&!h.protocol?.startsWith("wx")&&delete h.path,l(h),h.query&&typeof h.query.clientId=="string"&&(h.clientId=h.query.clientId),n.default||h.unixSocket?h.socksProxy=void 0:h.socksProxy===void 0&&typeof De<"u"&&(h.socksProxy=De.env.MQTTJS_SOCKS_PROXY),h.cert&&h.key)if(h.protocol){if(["mqtts","wss","wxs","alis"].indexOf(h.protocol)===-1)switch(h.protocol){case"mqtt":h.protocol="mqtts";break;case"ws":h.protocol="wss";break;case"wx":h.protocol="wxs";break;case"ali":h.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${h.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!h.forceNativeWebSocket?(a.ws=nn().streamBuilder,a.wss=nn().streamBuilder,a.mqtt=Al().default,a.tcp=Al().default,a.ssl=Cl().default,a.tls=a.ssl,a.mqtts=Cl().default):(a.ws=nn().browserStreamBuilder,a.wss=nn().browserStreamBuilder,a.wx=Pl().default,a.wxs=Pl().default,a.ali=Ol().default,a.alis=Ol().default)),!a[h.protocol]){let b=["mqtts","wss"].indexOf(h.protocol)!==-1;h.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(h.clean===!1&&!h.clientId)throw new Error("Missing clientId for unclean clients");h.protocol&&(h.defaultProtocol=h.protocol);function g(b){return h.servers&&((!b._reconnectCount||b._reconnectCount===h.servers.length)&&(b._reconnectCount=0),h.host=h.servers[b._reconnectCount].host,h.port=h.servers[b._reconnectCount].port,h.protocol=h.servers[b._reconnectCount].protocol?h.servers[b._reconnectCount].protocol:h.defaultProtocol,h.hostname=h.host,b._reconnectCount++),s("calling streambuilder for",h.protocol),a[h.protocol](b,h)}let p=new o.default(g,h);return p.on("error",()=>{}),p}function u(d,h,g=!0){return new Promise((p,b)=>{let y=c(d,h),w={connect:k=>{m(),p(y)},end:()=>{m(),p(y)},error:k=>{m(),y.end(),b(k)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(k=>{y.off(k,w[k])})}Object.keys(w).forEach(k=>{y.on(k,w[k])})})}i.default=c}),Ll=fe(i=>{le(),ue(),ce();var e=i&&i.__createBinding||(Object.create?function(g,p,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(p,b);(!w||("get"in w?!p.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return p[b]}}),Object.defineProperty(g,y,w)}:function(g,p,b,y){y===void 0&&(y=b),g[y]=p[b]}),t=i&&i.__setModuleDefault||(Object.create?function(g,p){Object.defineProperty(g,"default",{enumerable:!0,value:p})}:function(g,p){g.default=p}),r=i&&i.__importStar||(function(){var g=function(p){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(p)};return function(p){if(p&&p.__esModule)return p;var b={};if(p!=null)for(var y=g(p),w=0;w<y.length;w++)y[w]!=="default"&&e(b,p,y[w]);return t(b,p),b}})(),o=i&&i.__exportStar||function(g,p){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(p,b)&&e(p,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(Pi());i.MqttClient=s.default;var a=n(Us());i.DefaultMessageIdProvider=a.default;var l=n(pd());i.UniqueMessageIdProvider=l.default;var c=n(Ls());i.Store=c.default;var u=r(th());i.connect=u.default,Object.defineProperty(i,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Vs());i.KeepaliveManager=d.default,i.Client=s.default,o(Pi(),i),o(Kt(),i),o(Os(),i);var h=Cr();Object.defineProperty(i,"ReasonCodes",{enumerable:!0,get:function(){return h.ReasonCodes}})}),rh=fe(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(Ll());i.default=n,o(Ll(),i)});const nh=rh();const ih={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},oh=300,sh={templateId:"7",type:"link",isDeepLink:!0},ah={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ml{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;connectedAt=0;disposed=!1;reconnectTimer=null;lifecycleHandlersAttached=!1;onOnlineHandler=null;onVisibilityHandler=null;onPageShowHandler=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??this.freshClientId(),this.topics={...ih,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,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,h)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:h?.message}),l(()=>s(h??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=nh.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,h)=>{this.dispatchInbound(d,h)}),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={...sh,...this.config.fileTemplate??{},...lh(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=oh){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),h={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(h)),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={...ah,...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 lh(i){const e={};for(const[t,r]of Object.entries(i))r!==void 0&&(e[t]=r);return e}function Nl(i,e){return(i.sender??"").toString()===e}function Rl(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 Io(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 jl(i){const e=Io(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 Dl(i,e,t){const r=Rl(i,t),o=Io(i),n=jl(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"?ch(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 ch(i){return i<0?"error":i>=250?"read":i>=150?"delivered":"sent"}class $l extends kr{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 Jo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Qo,this.conversationManager=new rs(e.conversationId),this.usesAikaara()&&(this.connection=new Yo(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 Ml({...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=>Dl(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}=Dl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(Nl(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}}}class uh extends kr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Ul={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 dh(i){const e=i.lastIndexOf(".");return e<0||e===i.length-1?"":i.slice(e+1).toLowerCase()}function hh(i,e,t){const r=dh(i.name||"");if(r&&e&&e[r])return e[r];const o=i.type;return o&&o.trim().length>0?o:r&&Ul[r]?Ul[r]:t}function To(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ph(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 Bl(i){const e=i.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=hh(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=To(c,s),d=await fetch(u,{method:i.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const h=await d.json().catch(()=>({})),g=ph(h,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const p=i.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,i.s3HostRewrite):g,b=await fetch(p,{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(To(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 k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:i.viewerTemplate?To(i.viewerTemplate,s):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Co(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[h,g]of Object.entries(n))r.append(h,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 fh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Fl(i){const e=i.apiBase.replace(/\/$/,""),t=i.pageSize??200,r=i.pathTemplate??fh;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 h=await i.getToken();h&&(l.authorization=h)}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 mh="^[A-Z]{4}[0-9]{5}[A-Z]$",gh="^\\S{12}$",ql="^[A-Z]{4}0[A-Z0-9]{6}$",Hl="^[0-9]{6}$",bh=[{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:mh,uppercase:!0,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"rentalIncome",type:"number",label:"Rental Income",currency:"₹",min:0},{id:"propertyTax",type:"number",label:"Municipal Taxes",currency:"₹",min:0},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",fields:[{id:"lenderName",type:"text",label:"Bank / Institute Name"},{id:"sanctionDate",type:"date",label:"Loan Sanction Date",format:"DD/MM/YYYY"},{id:"loanAccountNumber",type:"text",label:"Loan Account No."},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"outstandingAmount",type:"number",label:"Outstanding Loan",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Interest Paid",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"Amount",currency:"₹",min:0,max:15e4},{id:"us80cSubType",type:"text",label:"Investment Type",placeholder:"e.g. LIC, PPF, ELSS, NSC"},{id:"us80cPolicyNumber",type:"text",label:"Policy Number"}]},{id:"section80ccd1b",type:"group",title:"Section 80CCD(1B)",fields:[{id:"us80ccd1bAmount",type:"number",label:"Amount",currency:"₹",min:0},{id:"us80ccd1bPanNo",type:"text",label:"PRAN No.",pattern:gh,maxLength:12}]},{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:"us80gDonationInCash",type:"number",label:"Donation In Cash",currency:"₹",min:0},{id:"us80gDonationOnline",type:"number",label:"Donation Through Online Mode",currency:"₹",min:0},{id:"us80gTransactionRefNo",type:"text",label:"Transaction Reference No.",required:!0,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:ql,maxLength:11,showWhen:{field:"us80gDonationOnline",gt:0}},{id:"us80gNameOfCharity",type:"text",label:"Name of Charity / Trust"},{id:"us80gCharityPan",type:"text",label:"Charity / Trust PAN",uppercase:!0},{id:"us80gTrustAddress",type:"text",label:"Trust / Charity Address"},{id:"us80gPincode",type:"text",label:"Pincode",maxLength:6,pattern:Hl}]},{id:"section80e",type:"group",title:"Section 80E — Education Loan Interest",fields:[{id:"us80eLoanTakenFrom",type:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{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:"hasParentOverSixty",type:"yes-no",label:"Parent Senior Citizen"},{id:"us80dForParentsAmount",type:"number",label:"Parents — Amount",currency:"₹",min:0,max:5e4},{id:"us80dForParentsPolicyCompany",type:"text",label:"Parents — Policy Company Name"},{id:"us80dForParentsPolicyNumber",type:"text",label:"Parents — Policy Number"}]}],submitLabel:"Save"},{id:"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:Hl},{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"},{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:ql,maxLength:11}]}],submitLabel:"Save"}];function yh(i,e){const t=i||{},r={userId:tt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Lh()};r.us80cAmount=xe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=xe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=xe(t.us80dForParentsAmount),r.hasParentOverSixty=dr(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.familyPension=xe(t.familyPension),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=zl(t),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=Po(t.hpDetails,vh);l.length&&(r.hpDetails=l);const c=Po(t.salaryDetails,wh);if(c.length){r.salaryIncome=c;const u=Po(t.salaryDetails,h=>({grossSalary:xe(h.grossSalary),employerName:Ee(h.employerName)}));u.length&&(r.salary=u);const d=sn(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 rt(r)}function vh(i){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(i.loanTakenFrom),bankOrInstituteName:Ee(i.lenderName),loanAccountNo:Ee(i.loanAccountNumber),loanSanctionDate:on(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:dr(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:dr(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),totalTdsDeposited:xe(i.totalTdsDeposited),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 kh(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 _h(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 Wl(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=sn(i.hpDetails).filter(Ah).map(r=>{const o=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:on(r.sanctionDate),totalLoanAmount:xe(r.totalLoanAmount),loanOutstandingAmount:xe(r.outstandingAmount),interest:xe(r.homeLoanInterest)});return rt({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:dr(r.hasCoOwnedProperty)??!1,hasRentalIncome:Wl(r),loanDetails:[o]})});return t.length?{userId:tt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Th(i,e){const t=sn(i.hpDetails).filter(Wl).map(r=>rt({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:rt(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:on(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:on(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 h=xe(t.us80dForParentsAmount);return h!==void 0&&o.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:h,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:dr(t.hasParentOverSixty)??!1})),o}function Ph(i,e){const t=i||{},r=xe(t.us80gDonationInCash),o=xe(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&o===void 0&&n===void 0)return null;const s=(o??0)>0;return{userId:tt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:o,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionReferenceNo:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function zl(i){const e=i||{},t=xe(e.agricultureIncome),r=xe(e.agricultureExpenditure),o=rt({landInAcre:xe(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(o).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[o]:void 0})}function Oh(i,e){const t=zl(i);return t?{userId:tt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}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 dr(i){return i===!0||i===!1?i:void 0}function Lh(){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 on(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 sn(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Po(i,e){return sn(i).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(i){if(Array.isArray(i)){const e=i.map(rt).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=rt(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return i}function Mh(i){const e=i&&typeof i=="object"?i:{},t={},r=$e(e.employers),o=$e(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(L=>{const D=Oo(L.salary),oe=Oo(L.perquisites),Y=Oo(L.profitsInLieuOfSalaryType),W=D+oe+Y,ee=Dh(L.allowance);return{employerName:Pe(L.employerName),employerTan:Pe(L.employerTAN),basicSalary:D||void 0,grossSalary:W||void 0,hraReceived:ee.hra,leaveTravelAllowance:ee.lta,leaveEncashment:ee.leaveEncashment,anyOtherAllowance:ee.other,totalTdsDeposited:jh(L,o,r)??Re(L.totalTdsDeposited)}}));const n=$e(e.houseProperties);n.length&&(t.hpDetails=n.map(L=>{const D=$e(L.loanDetails),oe=D.length?D[0]:void 0,Y=Re(L.grossAnnualRentReceived),W=D.length?D.reduce((J,ge)=>J+(Re(ge.interest)??0),0):void 0,ee=$e(L.tenant),$=$e(L.coOwners),X=ee[0],M=$[0];return{typeOfHouseProperty:Pe(L.propertyType),loanTakenFrom:Pe(oe?.loanTakenFrom),lenderName:Pe(oe?.bankOrInstituteName),loanAccountNumber:Pe(oe?.loanAccountNo),sanctionDate:Vl(oe?.loanSanctionDate),totalLoanAmount:Re(oe?.totalLoanAmount),outstandingAmount:Re(oe?.loanOutstandingAmount),homeLoanInterest:W,homeLoanPrinciple:void 0,housePropertyAddress:Pe(L.address),housePropertyPincode:Pe(L.pinCode),rentalIncome:Y,nameOfTenant:Pe(X?.name),tenantPanNumber:Pe(X?.panNumber),eligible80EEAmount:Re(L.eligible80EEAmount),eligible80EEAAmount:Re(L.eligible80EEAAmount),propertyTax:Re(L.propertyTax),hasCoOwnedProperty:$.length>0,coOwnerName:Pe(M?.name),coOwnerPan:Pe(M?.panNumber),coOwnerShare:Re(M?.share)?.toString()}}));const s=$e(e.deductionUS80CDetails),a=Ot(s.map(L=>Re(L.amount))),l=s.find(L=>Pe(L.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Pe(l?.identificationNo);const c=$e(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Pe(u?.subType??c?.investmentType);const d=$e(e.deductionUS80DDetails),h=d.find(L=>Pe(L.policyFor)?.toUpperCase()==="DEPENDANT")??$e(e.insurances).find(L=>Pe(L.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(L=>Pe(L.policyFor)?.toUpperCase()==="PARENTS")??$e(e.insurances).find(L=>Pe(L.policyFor)?.toUpperCase()==="PARENTS"),p=Array.isArray(h?.bifurcation)?h.bifurcation[0]:void 0,b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Re(h?.healthInsuranceAmount??h?.premium),t.us80dForSelfAndFamilyPolicyCompany=Pe(h?.insurerName??p?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Pe(h?.policyNo??p?.accountNo),t.us80dForParentsAmount=Re(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Pe(g?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Pe(g?.policyNo??b?.accountNo),t.hasParentOverSixty=$h(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Pe(e.pranNumber),t.us80ccd2Amount=void 0;const w=$e(e.donations)[0];t.us80gDonationInCash=Re(w?.amountInCash??w?.donationInCash),t.us80gDonationOnline=Re(w?.amountOtherThanCash??w?.amount??w?.donationAmount),t.us80gNameOfCharity=Pe(w?.nameOfCharity??w?.donorName??w?.trustName),t.us80gCharityPan=Pe(w?.panNumber??w?.charityPan),t.us80gTrustAddress=Pe(w?.address??w?.charityAddress),t.us80gPincode=Pe(w?.pinCode??w?.pincode),t.us80gTransactionRefNo=Pe(w?.transactionReferenceNo??w?.transactionRefNo),t.us80gIfscCode=Pe(w?.ifscCode??w?.ifsCode);const k=$e(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=Pe(k?.loanTakenFrom),t.us80eeBankName=Pe(k?.bankOrInstituteName),t.us80eeLoanAccountNumber=Pe(k?.loanAccountNo),t.us80eeLoanSanctionDate=Vl(k?.loanSanctionDate),t.us80eeLoanAmount=Re(k?.totalLoanAmount),t.us80eeOutstandingLoan=Re(k?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Pe(k?.vehicleRegistrationNo);const x=$e(e.insurances);t.preventiveHealthCheckUp=Ot(x.map(L=>Re(L.preventiveCheckUp))),t.medicalExpenditure=Ot(x.map(L=>Re(L.medicalExpenditure)));const v=$e(e.incomes),S=L=>Ot(v.filter(D=>Pe(D.incomeType)===L).map(D=>Re(D.amount)));t.savingBankInterest=S("SAVING_INTEREST"),t.fdInterest=S("FD_RD_INTEREST"),t.anyOtherIncome=S("ANY_OTHER"),t.familyPension=S("FAMILY_PENSION"),t.dividend=Ot($e(e.dividendIncomes).map(L=>Re(L.income)));const E=e.business;if(E){const L=$e(E.presumptiveIncomes),D=W=>{const ee=$e(W.incomes),$=X=>Re(ee.find(M=>Pe(M.incomeType)===X)?.receipts)??0;return $("ANY_OTHER")>0?!0:$("BANK")>0||$("CASH")>0?!1:!!Pe(W.businessType)?.toUpperCase().includes("PROFESSION")},oe=W=>L.find(ee=>D(ee)===W),Y=(W,ee)=>{if(!W)return;const $=$e(W.incomes),X=J=>Re($.find(ge=>Pe(ge.incomeType)===J)?.receipts),M=X("BANK")||X("ANY_OTHER");t[ee.name]=Pe(W.businessType),t[ee.nature]=Pe(W.natureOfBusiness),t[ee.bank]=M||void 0,t[ee.cash]=X("CASH")||void 0,t[ee.net]=Ot($.map(J=>Re(J.presumptiveIncome)))||void 0};Y(oe(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),Y(oe(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const I=$e(e.capitalGain).filter(L=>Pe(L.assetType)?.toUpperCase()==="VDA").flatMap(L=>$e(L.assetDetails));I.length&&(t.cryptoSellPrice=Ot(I.map(L=>Re(L.sellValue))),t.cryptoPurchasePrice=Ot(I.map(L=>Re(L.purchaseCost))));const P=e.agriculturalDetails,O=e.agriculturalIncome;t.agricultureIncome=Re(O?.netAgriculturalIncome)??Re(O?.grossAgriculturalReceipts)??Re(P?.income),t.agricultureExpenditure=Re(O?.expenditureIncurredOnAgriculture)??Re(P?.expenditure);const T=$e(P?.agricultureLandDetails??P?.agriculturalLandDetails??e.agriculturalLandDetails)[0];T&&(t.agricultureLandInAcre=Re(T.landInAcre),t.agricultureLandDistrict=Pe(T.nameOfDistrict),t.agricultureLandPincode=Pe(T.pinCode),t.agricultureLandOwner=Nh(T.owner),t.agricultureLandType=Rh(T.typeOfLand)),t.aadhaarNumber=Pe(e.aadharNumber);const F=$e(e.bankDetails)[0];return F&&(t.bankAccountNumber=Pe(F.accountNumber),t.bankIfscCode=Pe(F.ifsCode)),Kl(t)}function Nh(i){const e=Pe(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 Rh(i){const e=Pe(i)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function Vl(i){const e=Pe(i);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Oo(i){return $e(i).reduce((e,t)=>e+(Re(t.taxableAmount)??0),0)}function jh(i,e,t){if(!e.length)return;const r=Pe(i.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Pe(n.deductorTAN)?.trim().toUpperCase()===r)return Re(n.totalTdsDeposited)}const o=Pe(i.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Pe(n.deductorName)?.trim().toLowerCase()===o)return Re(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Re(e[0].totalTdsDeposited)}function Dh(i){const e=$e(i);if(!e.length)return{};let t,r,o,n;for(const s of e){const a=Re(s.exemptAmount)??Re(s.allowanceAmount);switch(Pe(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)+(Re(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Ot(i){let e=0,t=!1;for(const r of i)r!=null&&(e+=r,t=!0);return t?e:void 0}function $e(i){return Array.isArray(i)?i.filter(e=>e&&typeof e=="object"):[]}function Re(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))return Number(i)}function Pe(i){if(i==null)return;const e=String(i).trim();return e===""?void 0:e}function $h(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 Kl(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"?Kl(o):o):e[t]=r);return e}function Lo(){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 Uh(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 Mh(Mo(await r.json().catch(()=>({}))))}async function Bh(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 Fh(i,e){return _t(i,`${i.baseUrl}/itr/v1/automation/salary`,e)}async function qh(i,e){return _t(i,`${i.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Gl(i,e){return _t(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Hh(i,e){return _t(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Wh(i,e){return _t(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function zh(i,e){return _t(i,`${i.baseUrl}/itr/v1/automation/deductions`,e)}async function Vh(i,e){return _t(i,i.submitUrl||`${i.baseUrl}/itr/v1/automation/data`,e)}async function Kh(i,e){return _t(i,`${i.baseUrl}/itr/v1/automation/hp-income`,e)}async function Gh(i,e){return _t(i,`${i.baseUrl}/itr/v1/automation/vda`,e)}async function _t(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}`}const ep=["No, I have a concerns"];class tp{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new $l(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;const r=this.shouldOpenSmartEdit(t.text),o=this.client.config.templateActionAttributes??{},n=t.attributes?.action??{},s={...t.attributes,action:{...o,...n}};this.handleSend(t.text,s).then(()=>{r&&this.openSmartEdit()})})}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,r=Array.isArray(t)?t:ep;if(!Array.isArray(r)||r.length===0)return!1;const o=s=>s.trim().toLowerCase(),n=o(e);return r.some(s=>typeof s=="string"&&o(s)===n)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:bh,data:{}});const t=Lo();if(!(!t||!t.baseUrl))try{const r=await Uh(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=Lo();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=kh(n,o);s&&await Fh(r,s)}else if(e==="bank-details"){const n=_h(t,o);n&&await qh(r,n)}else if(e==="other-sources")await Gl(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 Gl(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=Lo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Bh(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 Yl 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||Gc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Ko,position:this.getAttribute("position")||this._config.position||Kc,width:Number(this.getAttribute("width"))||this._config.width||Hc,height:Number(this.getAttribute("height"))||this._config.height||Wc,fontFamily:this._config.fontFamily||Vc,borderRadius:this._config.borderRadius??zc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Go,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||Yc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,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;
|
|
@@ -30,7 +30,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
30
30
|
bottom: calc(var(--aikaara-bubble-size) + 16px);
|
|
31
31
|
${e.position==="bottom-left"?"left":"right"}: 0;
|
|
32
32
|
transition: opacity 200ms ease, transform 200ms ease;
|
|
33
|
-
`,
|
|
33
|
+
`,s=`
|
|
34
34
|
width: 100%;
|
|
35
35
|
flex: 1 1 auto;
|
|
36
36
|
min-height: 0;
|
|
@@ -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||Ko)};
|
|
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 {
|
|
@@ -68,7 +68,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
68
68
|
display: flex;
|
|
69
69
|
flex-direction: column;
|
|
70
70
|
overflow: hidden;
|
|
71
|
-
${t?
|
|
71
|
+
${t?s:n}
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
.aikaara-panel[hidden] {
|
|
@@ -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||Go}"
|
|
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 tp(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 Jl 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 rp=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class Ql extends HTMLElement{shadow;actions=rp;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>
|
|
@@ -304,7 +304,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
304
304
|
<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="19" r="1.6"/></svg>
|
|
305
305
|
</button>
|
|
306
306
|
<div class="menu" role="menu">
|
|
307
|
-
${
|
|
307
|
+
${s}
|
|
308
308
|
</div>
|
|
309
309
|
</div>`:""}
|
|
310
310
|
<button class="icon-btn close-btn" aria-label="Close chat" type="button">
|
|
@@ -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 np=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,ip=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,op={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function sp(i){return i.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>op[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 Jt(i){if(np.test(i))return i;const e=ip.test(i)?sp(i):i;let t=ap(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 ap(i){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return i.replace(/[&<>"']/g,t=>e[t])}const lp=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"]),cp={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 Qt(i){const e=document.createElement("template");return e.innerHTML=i,Xl(e.content),e.innerHTML}function Xl(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(!lp.has(o)){const a=document.createTextNode(r.textContent||"");i.replaceChild(a,t);continue}const n=cp[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")}Xl(t)}}function Zl(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 up(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 ec 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=>tc(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">${
|
|
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">${Qt(Jt(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=dp(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=Qt(Jt(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 h=document.createElement("aikaara-system-pill");h.setAttribute("text",e.content),d.appendChild(h),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=Qt(Jt(e.content))):(o.innerHTML=Qt(Jt(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 h=e.externalId??e.id;h&&d.setAttribute("message-id",h),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 h of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const p={elements:[{description:h.fileName,action:{url:h.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(p,""),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 h=document.createElement("span");h.classList.add("status-tick"),e.status==="read"&&h.classList.add("read"),h.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(h)}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 up(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=>tc(e,g.match)),o=r?.target??"iframe";if(o==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(o==="popup"){Zl(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=hp(e),l=rc(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(No(r.fetch.body,a)));let h=null;try{const g=await fetch(l,d);g.ok&&(h=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,s,g=>{const p=r.props??{setData:h};for(const[y,w]of Object.entries(p)){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 dp(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 tc(i,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(i)}function hp(i){try{const e=new URL(i),t={};return e.searchParams.forEach((r,o)=>{t[o]=r}),t}catch{return{}}}function rc(i,e){return i.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function No(i,e){if(typeof i=="string")return rc(i,e);if(Array.isArray(i))return i.map(t=>No(t,e));if(i&&typeof i=="object"){const t={};for(const[r,o]of Object.entries(i))t[r]=No(o,e);return t}return i}class nc 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||"":Qt(Jt(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 {
|
|
@@ -542,8 +542,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
542
542
|
<div class="content">${l}</div>
|
|
543
543
|
${n?`<aikaara-template-renderer
|
|
544
544
|
content-type="${n}"
|
|
545
|
-
template-id="${
|
|
546
|
-
inner-message="${
|
|
545
|
+
template-id="${s}"
|
|
546
|
+
inner-message="${ic(a)}"
|
|
547
547
|
></aikaara-template-renderer>`:""}
|
|
548
548
|
${this.renderAttachments()}
|
|
549
549
|
</div>
|
|
@@ -552,20 +552,20 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
552
552
|
${r}${c?`<span class="status">${u}</span>`:""}
|
|
553
553
|
</div>
|
|
554
554
|
`:""}
|
|
555
|
-
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",
|
|
556
|
-
📎 ${
|
|
557
|
-
</a>`).join("")}</div>`:""}}function
|
|
555
|
+
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",h=>{this.dispatchEvent(new CustomEvent("message-action",{detail:h.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${ic(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
|
+
📎 ${pp(t.fileName)}
|
|
557
|
+
</a>`).join("")}</div>`:""}}function ic(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function pp(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"/>
|
|
567
567
|
</svg>
|
|
568
|
-
</button>`,c=
|
|
568
|
+
</button>`,c=s?"border-radius: var(--aikaara-button-radius, 8px);":"border-radius: 50%;";this.shadow.innerHTML=`
|
|
569
569
|
<style>
|
|
570
570
|
.input-container {
|
|
571
571
|
display: flex;
|
|
@@ -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=
|
|
718
|
+
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Qt(Jt(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
|
|
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 Ro=new Map;function cc(i){const e=Ro.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",()=>{Ro.delete(i),o(new Error(`Failed to load ${i}`))},{once:!0}),document.head.appendChild(s)});return Ro.set(i,t),t}function fp(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 mp={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>$f).then(({registerAikaaraPaymentLink:i})=>i())},gp={"service-picker":"aikaara-service-picker","service-details":"aikaara-service-details","price-breakdown":"aikaara-price-breakdown","slot-picker":"aikaara-slot-picker","call-upload":"aikaara-call-upload","call-confirmation":"aikaara-call-confirmation"};function bp(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 yp 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=kp(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?bp(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=mp[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(()=>fp(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=t?gp[t.replace(/_/g,"-").toLowerCase()]:void 0;if(r){this.mountScheduleWidget(r,e);return}const o=e.data;if(o){if(t==="text"){const n=document.createElement("aikaara-text-input");n.setPayload(o),this.appendChild(n);return}if(t==="checkbox"||t==="radio"||t==="button"){const n=document.createElement("aikaara-option-list");n.setPayload({name:o.name??"",title:o.title,options:o.options??[],type:t}),this.appendChild(n);return}if(t==="submit"){const n=document.createElement("aikaara-submit-action"),s=this.getAttribute("message-id")??void 0;n.setPayload({name:o.name??"Submit",action:o.action??{message:o.name??"Submit"},messageId:s}),this.appendChild(n);return}t==="modal"&&this.mountModal({message:o.message??"",okLabel:o.okLabel,cancelLabel:o.cancelLabel,action:o.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>qf).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:wp(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountScheduleWidget(e,t){const r=document.createElement(e),n={...t.data??t};if(delete n.type,!n.messageId){const s=this.getAttribute("message-id");s&&(n.messageId=s)}r.setPayload?.(n),this.appendChild(r)}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const vp=new Set(["type","url","name","openLinkInNewTab","orderId"]);function wp(i){const e={};for(const[t,r]of Object.entries(i))vp.has(t)||(e[t]=r);return e}function kp(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 _p extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
|
|
761
761
|
<style>
|
|
762
762
|
:host {
|
|
763
763
|
display: flex;
|
|
@@ -782,9 +782,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
782
782
|
color: var(--aikaara-text-secondary, #9ca3af);
|
|
783
783
|
}
|
|
784
784
|
</style>
|
|
785
|
-
<span class="pill">${
|
|
786
|
-
${t?`<span class="sub">${
|
|
787
|
-
`}}function
|
|
785
|
+
<span class="pill">${uc(e)}</span>
|
|
786
|
+
${t?`<span class="sub">${uc(t)}</span>`:""}
|
|
787
|
+
`}}function uc(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class xp 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 {
|
|
@@ -819,15 +819,15 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
819
819
|
.row[aria-checked="true"] .check { opacity: 1; }
|
|
820
820
|
.text { flex: 1; }
|
|
821
821
|
</style>
|
|
822
|
-
<div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}" data-value="${
|
|
822
|
+
<div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}" data-value="${jo(s.value)}">
|
|
823
823
|
<span class="box" aria-hidden="true">
|
|
824
824
|
<svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
825
825
|
<path d="M3 8 L7 12 L13 4" />
|
|
826
826
|
</svg>
|
|
827
827
|
</span>
|
|
828
|
-
<span class="text">${
|
|
828
|
+
<span class="text">${Bt(e)}</span>
|
|
829
829
|
</div>
|
|
830
|
-
`,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(
|
|
830
|
+
`,!this.preSelectedDisabled){const c=this.shadow.querySelector(".row");if(c){const u=()=>this.toggle(s.value);c.addEventListener("click",u),c.addEventListener("keydown",d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),u())})}}return}if(r==="radio"){const s=this.preSelectedDisabled?"default":"pointer";this.shadow.innerHTML=`
|
|
831
831
|
<style>
|
|
832
832
|
:host { display: block; margin: 8px 0; }
|
|
833
833
|
.title {
|
|
@@ -839,7 +839,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
839
839
|
.list { display: flex; flex-direction: column; gap: 10px; }
|
|
840
840
|
.row {
|
|
841
841
|
display: flex; align-items: center; gap: 10px;
|
|
842
|
-
cursor: ${
|
|
842
|
+
cursor: ${s};
|
|
843
843
|
font-family: inherit;
|
|
844
844
|
font-size: 14px;
|
|
845
845
|
color: var(--aikaara-option-color, var(--aikaara-text, #1f2937));
|
|
@@ -867,14 +867,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
867
867
|
.row[aria-checked="true"] .dot { opacity: 1; transform: scale(1); }
|
|
868
868
|
.label { flex: 1; }
|
|
869
869
|
</style>
|
|
870
|
-
${e?`<div class="title">${
|
|
871
|
-
<div class="list" role="radiogroup" aria-label="${
|
|
870
|
+
${e?`<div class="title">${Bt(e)}</div>`:""}
|
|
871
|
+
<div class="list" role="radiogroup" aria-label="${Bt(e??this.data.name)}">
|
|
872
872
|
${t.map(a=>{const l=this.selected.has(a.value);return`
|
|
873
873
|
<div class="row" role="radio" tabindex="${this.preSelectedDisabled?"-1":"0"}"
|
|
874
874
|
aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}"
|
|
875
|
-
data-value="${
|
|
875
|
+
data-value="${jo(a.value)}">
|
|
876
876
|
<span class="circle" aria-hidden="true"><span class="dot"></span></span>
|
|
877
|
-
<span class="label">${
|
|
877
|
+
<span class="label">${Bt(a.label)}</span>
|
|
878
878
|
</div>`}).join("")}
|
|
879
879
|
</div>
|
|
880
880
|
`,this.preSelectedDisabled||this.shadow.querySelectorAll(".row").forEach(a=>{const l=()=>this.toggle(a.dataset.value||"");a.addEventListener("click",l),a.addEventListener("keydown",c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())})});return}this.shadow.innerHTML=`
|
|
@@ -910,18 +910,18 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
910
910
|
border-color: var(--aikaara-option-selected-border, var(--aikaara-primary, #6366f1));
|
|
911
911
|
}
|
|
912
912
|
</style>
|
|
913
|
-
${e?`<div class="title">${
|
|
914
|
-
<div class="grid" role="${
|
|
915
|
-
${t.map(
|
|
913
|
+
${e?`<div class="title">${Bt(e)}</div>`:""}
|
|
914
|
+
<div class="grid" role="${o?"group":"radiogroup"}" aria-label="${Bt(e??this.data.name)}">
|
|
915
|
+
${t.map(s=>`
|
|
916
916
|
<button class="opt" type="button"
|
|
917
|
-
data-value="${
|
|
918
|
-
role="${
|
|
919
|
-
aria-pressed="${this.selected.has(
|
|
917
|
+
data-value="${jo(s.value)}"
|
|
918
|
+
role="${o?"checkbox":"radio"}"
|
|
919
|
+
aria-pressed="${this.selected.has(s.value)}"
|
|
920
920
|
${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
|
|
921
|
-
${
|
|
921
|
+
${Bt(s.label)}
|
|
922
922
|
</button>`).join("")}
|
|
923
923
|
</div>
|
|
924
|
-
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(
|
|
924
|
+
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(s=>{s.addEventListener("click",()=>this.toggle(s.dataset.value||""))})}}function Bt(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function jo(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Sp 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">${Ep(e)}</button>
|
|
943
|
+
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Ep(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Ap extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
|
|
944
944
|
<style>
|
|
945
945
|
:host { all: initial; }
|
|
946
946
|
.overlay {
|
|
@@ -981,14 +981,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
981
981
|
</style>
|
|
982
982
|
<div class="overlay" role="dialog" aria-modal="true">
|
|
983
983
|
<div class="modal">
|
|
984
|
-
<div class="msg">${
|
|
984
|
+
<div class="msg">${Do(this.data.message)}</div>
|
|
985
985
|
<div class="actions">
|
|
986
|
-
${t?`<button class="cancel" type="button">${
|
|
987
|
-
<button class="ok" type="button">${
|
|
986
|
+
${t?`<button class="cancel" type="button">${Do(t)}</button>`:""}
|
|
987
|
+
<button class="ok" type="button">${Do(e)}</button>
|
|
988
988
|
</div>
|
|
989
989
|
</div>
|
|
990
990
|
</div>
|
|
991
|
-
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function
|
|
991
|
+
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function Do(i){return String(i).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Ip 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,16 +1022,16 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1022
1022
|
}
|
|
1023
1023
|
:host([data-consumed]) input { pointer-events: none; opacity: 0.65; background: var(--aikaara-input-bg, #f9fafb); }
|
|
1024
1024
|
</style>
|
|
1025
|
-
<label>${
|
|
1025
|
+
<label>${hr(e)}${o}</label>
|
|
1026
1026
|
<input
|
|
1027
1027
|
type="text"
|
|
1028
|
-
placeholder="${
|
|
1029
|
-
value="${
|
|
1030
|
-
aria-label="${
|
|
1028
|
+
placeholder="${hr(t)}"
|
|
1029
|
+
value="${hr(this._value)}"
|
|
1030
|
+
aria-label="${hr(e)}"
|
|
1031
1031
|
aria-invalid="false"
|
|
1032
1032
|
/>
|
|
1033
|
-
<div class="error" role="alert">${
|
|
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
|
|
1033
|
+
<div class="error" role="alert">${hr(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 hr(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Tp 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 Tc({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 Cp 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 Pp=[{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"}],Op=[{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 Lp extends HTMLElement{shadow;data=null;columns=Op;features=Pp;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
|
|
1085
1085
|
<style>
|
|
1086
1086
|
:host {
|
|
1087
1087
|
display: block;
|
|
@@ -1137,35 +1137,35 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1137
1137
|
<thead>
|
|
1138
1138
|
<tr>
|
|
1139
1139
|
<th>Feature</th>
|
|
1140
|
-
${e.map(r=>`<th>${
|
|
1140
|
+
${e.map(r=>`<th>${$o(r.label)}</th>`).join("")}
|
|
1141
1141
|
</tr>
|
|
1142
1142
|
</thead>
|
|
1143
1143
|
<tbody>
|
|
1144
|
-
${t.map((r,
|
|
1144
|
+
${t.map((r,o)=>`
|
|
1145
1145
|
<tr>
|
|
1146
|
-
<td>${
|
|
1147
|
-
${e.map(n=>n.features[
|
|
1146
|
+
<td>${$o(r.label)}</td>
|
|
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,
|
|
1157
|
-
<span>${
|
|
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
|
+
<span>${$o(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 $o(i){return i.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Mp 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
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1165
|
-
`;const r=this.shadow.querySelector(".modal-body"),
|
|
1166
|
-
<button class="chip" type="button" data-section-id="${
|
|
1167
|
-
<span class="chip-icon">${
|
|
1168
|
-
<span class="chip-label">${
|
|
1164
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${dc}</button>
|
|
1165
|
+
`;const r=this.shadow.querySelector(".modal-body"),o=this.schemas.map(s=>`
|
|
1166
|
+
<button class="chip" type="button" data-section-id="${Rp(s.id)}">
|
|
1167
|
+
<span class="chip-icon">${s.icon??"📄"}</span>
|
|
1168
|
+
<span class="chip-label">${hc(s.title)}</span>
|
|
1169
1169
|
</button>`).join("");r.innerHTML=`
|
|
1170
1170
|
<div class="picker">
|
|
1171
1171
|
<div class="intro-card">
|
|
@@ -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
|
-
`,this.bindCommon(),r.querySelectorAll(".chip").forEach(
|
|
1183
|
-
<button class="icon-btn back-btn" type="button" aria-label="Back">${
|
|
1184
|
-
<div class="modal-title">${
|
|
1185
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${
|
|
1186
|
-
`;const
|
|
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">${Np}</button>
|
|
1184
|
+
<div class="modal-title">${hc(t?.title??"Edit")}</div>
|
|
1185
|
+
<button class="icon-btn close-btn" type="button" aria-label="Close">${dc}</button>
|
|
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,15 +1321,15 @@ 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
|
|
1324
|
+
`}}const dc='<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>',Np='<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 Rp(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function hc(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class jp 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 typeof s.gt=="number"?typeof a=="number"&&a>s.gt:"equals"in s?a===s.equals:Array.isArray(s.in)?s.in.includes(a):null};return!(r(e.showWhen)===!1||r(e.hideWhen)===!0)}findField(e){let t;return this.walkFields(this.schema?.fields||[],r=>{!t&&r.id===e&&(t=r)}),t}normalizeUppercase(){this.getEntries().forEach((e,t)=>{this.walkFields(this.schema?.fields||[],r=>{if(r.type!=="text"||!r.uppercase)return;const o=e[r.id];typeof o=="string"&&o!==o.toUpperCase()&&this.setEntryNoRender(t,r.id,o.toUpperCase())})})}validate(){return this.normalizeUppercase(),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">
|
|
1328
1328
|
<div class="section-card">
|
|
1329
1329
|
<span class="section-icon">${this.schema.icon??"📝"}</span>
|
|
1330
1330
|
<div class="section-meta">
|
|
1331
|
-
<div class="section-title">${
|
|
1332
|
-
${this.schema.hint?`<div class="section-hint">${
|
|
1331
|
+
<div class="section-title">${Ke(this.schema.title)}</div>
|
|
1332
|
+
${this.schema.hint?`<div class="section-hint">${Ke(this.schema.hint)}</div>`:""}
|
|
1333
1333
|
</div>
|
|
1334
1334
|
</div>
|
|
1335
1335
|
<div class="entries">${t}</div>
|
|
@@ -1337,60 +1337,60 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1337
1337
|
</div>
|
|
1338
1338
|
<div class="footer">
|
|
1339
1339
|
<button class="save-btn" type="button" data-action="save">
|
|
1340
|
-
${
|
|
1340
|
+
${Ke(this.schema.submitLabel||"Save")}
|
|
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
|
-
${
|
|
1347
|
+
${Ke(o)}
|
|
1348
1348
|
</span>
|
|
1349
1349
|
${n}
|
|
1350
|
-
</div>`:""}<div class="entry-body">${
|
|
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,h=d.fields.map(b=>this.renderField(b,t,r)).join("");if(!d.collapsible)return`
|
|
1351
1351
|
<fieldset class="group">
|
|
1352
|
-
${d.title?`<legend class="group-title">${
|
|
1353
|
-
${d.hint?`<div class="group-hint">${
|
|
1354
|
-
<div class="group-body">${
|
|
1355
|
-
</fieldset>`;const g=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(g)&&(this.collapseSeeded.add(g),this.collapsed.add(g));const
|
|
1356
|
-
<fieldset class="group group--collapsible ${
|
|
1357
|
-
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${
|
|
1358
|
-
<span class="group-title">${
|
|
1352
|
+
${d.title?`<legend class="group-title">${Ke(d.title)}</legend>`:""}
|
|
1353
|
+
${d.hint?`<div class="group-hint">${Ke(d.hint)}</div>`:""}
|
|
1354
|
+
<div class="group-body">${h}</div>
|
|
1355
|
+
</fieldset>`;const g=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(g)&&(this.collapseSeeded.add(g),this.collapsed.add(g));const p=this.collapsed.has(g);return`
|
|
1356
|
+
<fieldset class="group group--collapsible ${p?"is-collapsed":""}">
|
|
1357
|
+
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${xt(g)}" aria-expanded="${!p}">
|
|
1358
|
+
<span class="group-title">${Ke(d.title??"")}</span>
|
|
1359
1359
|
<span class="group-chevron" aria-hidden="true"></span>
|
|
1360
1360
|
</button>
|
|
1361
|
-
${d.hint&&!
|
|
1362
|
-
<div class="group-body" ${
|
|
1363
|
-
</fieldset>`}const
|
|
1364
|
-
<div class="field ${
|
|
1361
|
+
${d.hint&&!p?`<div class="group-hint">${Ke(d.hint)}</div>`:""}
|
|
1362
|
+
<div class="group-body" ${p?"hidden":""}>${h}</div>
|
|
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)}">${Ke(e.label)} ${a}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ke(n)}</div>`:"";return`
|
|
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="${xt(String(o??""))}" placeholder="${xt(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="${xt(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Ke(String(o??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Ke(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}" ${
|
|
1372
|
-
</div>`}if(e.type==="date")return`<input type="date" class="input" id="${n}" ${
|
|
1371
|
+
<input type="number" class="input ${u}" id="${n}" ${s} value="${xt(String(o??""))}" placeholder="${xt(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="${xt(String(o??""))}"/>`;if(e.type==="select"){const a=e,l=a.options.map(c=>`<option value="${xt(c.value)}" ${o===c.value?"selected":""}>${Ke(c.label)}</option>`).join("");return`<select class="input" id="${n}" ${s}><option value="">${Ke(a.placeholder??"Select…")}</option>${l}</select>`}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}" ${
|
|
1377
|
-
<span class="radio-label">${
|
|
1376
|
+
<input type="radio" id="${u}" ${s} name="${n}" value="${xt(l.value)}" ${c}/>
|
|
1377
|
+
<span class="radio-label">${Ke(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
|
-
<input type="radio" ${
|
|
1382
|
+
<input type="radio" ${s} name="${n}" value="true" ${a}/>
|
|
1383
1383
|
<span class="radio-label">Yes</span>
|
|
1384
1384
|
</label>
|
|
1385
1385
|
<label class="radio-item ${l?"selected":""}">
|
|
1386
|
-
<input type="radio" ${
|
|
1386
|
+
<input type="radio" ${s} name="${n}" value="false" ${l}/>
|
|
1387
1387
|
<span class="radio-label">No</span>
|
|
1388
1388
|
</label>
|
|
1389
1389
|
</div>`}return e.type==="checkbox"?`
|
|
1390
1390
|
<label class="checkbox-item">
|
|
1391
|
-
<input type="checkbox" id="${n}" ${
|
|
1392
|
-
<span class="checkbox-label">${
|
|
1393
|
-
</label>`:""}fieldHtmlId(e,t){return`aikf-${e.id}-${t}`}bindHandlers(){this.shadow.querySelectorAll("input[data-field-id], textarea[data-field-id], select[data-field-id]").forEach(e=>{const t=e,r=t.dataset.fieldId,
|
|
1391
|
+
<input type="checkbox" id="${n}" ${s} ${o===!0?"checked":""}/>
|
|
1392
|
+
<span class="checkbox-label">${Ke(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], select[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"||t.type==="select-one"?"change":"input";t.addEventListener(s,()=>{let a;if(t.type==="checkbox")a=t.checked;else if(t.type==="radio")t.value==="true"?a=!0:t.value==="false"?a=!1:a=t.value;else if(t.type==="number")a=t.value===""?null:Number(t.value);else{const l=this.findField(r);if(l?.type==="text"&&l.uppercase){const c=t.value.toUpperCase();if(c!==t.value){const u=t.selectionStart;t.value=c,u!==null&&t.setSelectionRange(u,u)}}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,7 +1596,340 @@ 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 kt(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ve(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ro(){const i=[["aikaara-chat-widget",ql],["aikaara-chat-bubble",Hl],["aikaara-chat-header",Wl],["aikaara-message-list",Gl],["aikaara-message-bubble",Jl],["aikaara-chat-input",Xl],["aikaara-typing-indicator",Zl],["aikaara-streaming-message",ec],["aikaara-error-banner",tc],["aikaara-template-renderer",lf],["aikaara-system-pill",hf],["aikaara-option-list",ff],["aikaara-submit-action",pf],["aikaara-modal-action",gf],["aikaara-text-input",yf],["aikaara-chat",bf],["aikaara-link-modal",vf],["aikaara-compare-plans",_f],["aikaara-smart-edit-modal",Sf],["aikaara-schema-form",Af]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Ro();function rn(i,e,t=""){if(!e)return t;const r=e.split(".");let s=i;for(const n of r)if(s&&typeof s=="object"&&n in s)s=s[n];else return t;return typeof s=="string"?s:t}function sc(i){try{const e=i.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Jt(i){return typeof i=="function"?await i():i}class ac{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=sc(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Jt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",s={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:s};n==="POST"&&(s["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,o);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=rn(l,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!d)throw new Error("Session auth response missing token");const p=rn(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",f=rn(l,this.descriptor.fullNamePath??"data.fullName"),y=rn(l,this.descriptor.userPath??"data.userId"),b=sc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:f,userId:y,expiresAt:b},this.cache}}async function lc(i){const e={};for(const t of i.spec){const r=await If(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 If(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return Tf(t);case"localStorage":return nn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return nn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return nn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return nn(()=>document.querySelector(`meta[name="${Cf(t)}"]`)?.content??void 0);case"callback":{const r=e?.[i.name];if(!r)return;const s=await r();return typeof s=="string"?s:void 0}default:return}}function Tf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function nn(i){try{return i()}catch{return}}function Cf(i){return i.replace(/["\\]/g,"\\$&")}const Pf=1800;class cc{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 lc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const s=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!s)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(s,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Pf;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 Of=3e4,Mf=2e3,Lf=100;async function uc(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Xe("init","No init token supplied to Aikaara.init({token})");return{token:i.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Rf(r);if(!s)throw new Xe("query",`?${r}= not present`);return{token:s,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",s=Nf(r);if(!s)throw new Xe("hash",`#${r}= not present`);return{token:s,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",s=typeof t.key=="string"&&t.key?t.key:"token",n=Ff(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Of;return{token:await Bf({type:r,key:s,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Xe("cookie","cookie.name not configured");const s=jf(r);if(!s)throw new Xe("cookie",`cookie "${r}" not set`);return{token:s,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",s=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!s)throw new Xe("storage","storage.key not configured");const o=Uf(r,s,n);if(!o)throw new Xe("storage",`${r}Storage["${s}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Xe("global","global.path not configured");const s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Mf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Lf,o=await Df(r,s,n);if(!o)throw new Xe("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Xe("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class dc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await uc(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 Rf(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 Nf(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function jf(i){if(typeof document>"u")return;const e=encodeURIComponent(i),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const s=r.indexOf("=");if(s===-1)continue;const n=r.slice(0,s);if(n===i||n===e)try{return decodeURIComponent(r.slice(s+1))}catch{return r.slice(s+1)}}}function Uf(i,e,t){if(!(typeof window>"u"))try{const s=(i==="session"?window.sessionStorage:window.localStorage).getItem(e);if(s==null)return;if(!t)return s;let n;try{n=JSON.parse(s)}catch{return s}const o=hc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Df(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const s=hc(window,i);if(typeof s=="string"&&s.length>0)return s;if(typeof s=="function")try{const n=s();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Bf(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Xe("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(s)},s=setTimeout(()=>{r(),t(new Xe("postmsg",`timeout after ${i.timeoutMs}ms`))},i.timeoutMs),n=o=>{if(i.origins.length>0&&!i.origins.includes(o.origin))return;const a=o.data;if(!a||typeof a!="object")return;const l=a;if(i.type&&l.type!==i.type)return;const c=l[i.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Ff(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function hc(i,e){if(!e)return i;const t=e.split(".").filter(Boolean);let r=i;for(const s of t)if(r&&typeof r=="object"&&s in r)r=r[s];else return;return r}function $f(){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 qf="aikaara_chat:requestId";function No(i,e,t){const r=`${qf}:${i}:${e}`;return t?`${r}:${t}`:r}function fc(i,e,t){try{return localStorage.getItem(No(i,e,t))}catch{return null}}function Hf(i,e,t,r){try{localStorage.setItem(No(i,e,r),t)}catch{}}function Wf(i,e,t){try{localStorage.removeItem(No(i,e,t))}catch{}}async function jo(i,e,t="before-chat"){const r=i.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const s={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(s[u]=d);typeof e.serviceType=="string"&&(s.serviceType=e.serviceType),typeof e.userType=="string"&&(s.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in s?s[p]:""),o=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(o);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=o(g);return d}return u},a=await Jt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],p=n(d.url),g=d.method??(d.body?"POST":"GET"),f={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const S=d.authHeaderTemplate??"Bearer {token}";f.authorization=S.replace("{token}",a)}const y={method:g,headers:f};d.body&&(f["content-type"]="application/json",y.body=JSON.stringify(o(d.body)));let b=0,w="",m=0,k=null;for(;;)try{const S=await fetch(p,y);if(S.ok){k=S;break}if(b=S.status,w=await S.text().catch(()=>""),m<c.length&&Vf(b,w)){const x=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${b} (transient). Retry #${m} in ${x}ms.`),await new Promise(E=>setTimeout(E,x));continue}const v=`Preflight #${u} ${g} ${p} → ${b} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(S){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,S),await new Promise(x=>setTimeout(x,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,S);break}throw S}if(k&&d.capture&&d.capture.as)try{const S=await k.clone().text();let v=S;try{v=JSON.parse(S)}catch{}if(d.capture.path)for(const x of d.capture.path.split("."))if(v&&typeof v=="object"&&x in v)v=v[x];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let x=v;d.capture.stripPrefix&&x.startsWith(d.capture.stripPrefix)&&(x=x.slice(d.capture.stripPrefix.length)),l[d.capture.as]=x,s[d.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${x.slice(0,24)}…)`)}}catch(S){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,S)}}return{captured:l}}async function zf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await jo(e,{sessionToken:i.sessionToken,userId:i.userId,projectId:i.projectId??"",slug:i.slug??"",identity:i.identity,serviceType:i.serviceType,userType:i.userType},"on-method-select")).captured:{}}function Vf(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 pc(i,e){const t=await fetch(i,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const s=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${s.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function mc(i,e){return i.replace("{projectId}",e).replace("{uuid}",$f().replace(/-/g,""))}function gc(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=>rc(r)))}async function yc(i){const e={...i.config??(i.configUrl?await pc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};gc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const s=r?.projectId??"",n=i.identity.userId,o=i.conversationScope||void 0,a=i.forceNewConversation?null:fc(n,s,o),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??mc(l,s);(i.conversationId||!a||i.forceNewConversation)&&s&&Hf(n,s,c,o);const u=await i.tokenProvider(),d=i.tokenProvider,p=i.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:i.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...i.identity.departmentId?{departmentId:i.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:i.identity.senderFullname??i.identity.userName,tokenProvider:d}:void 0,f=i.uploadAdapter??(e.uploadEndpoint?xo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),y=i.historyAdapter??(e.historyApiBase?Rl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),b={transport:t,baseUrl:"",userToken:i.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:i.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:i.identity.userName,departmentId:i.identity.departmentId,senderFullname:i.identity.senderFullname??i.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:f,historyAdapter:y,onError:i.onError,onMessage:i.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(b),b.title&&w.setAttribute("title",b.title),b.primaryColor&&w.setAttribute("primary-color",b.primaryColor),b.display&&w.setAttribute("display",b.display),b.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),i.container.appendChild(w),{widget:w,requestId:c,config:b,destroy(){w.remove()}}}function Gf(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 bc(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 pc(t,i.configHeaders)}catch(I){if(!i.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${i.slug}" — using fallbackConfig.`,I)}const s={...i.fallbackConfig??{},...r??{},...i.overrides??{}};if(gc(s),s.templates&&Object.keys(s.templates).length>0){s.components={...s.components??{}};for(const[I,P]of Object.entries(s.templates)){const O=`template:${I}`;s.components[O]||!P?.scriptUrl||!P?.render||(s.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:s.templates,components:s.components,razorpay:s.razorpay,title:s.title,cloud:s.cloud??n.__aikaara_descriptor__?.cloud,upload:s.upload??n.__aikaara_descriptor__?.upload,themeSource:s.themeSource??n.__aikaara_descriptor__?.themeSource,api:s.api,auth:s.auth,smartEdit:s.smartEdit??n.__aikaara_descriptor__?.smartEdit},!s.auth)throw new Error(`mountFromSlug: widget_configs/${i.slug} descriptor must include "auth" block`);let o=null,a=i.user.id,l=i.user.name,c="",u=i.user.token,d=null;const p=await Jt(i.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&s.sso?.tokenSource){d=new dc({descriptor:{provider:s.sso.provider,flow:s.sso.flow,skipLogin:s.sso.skipLogin,autoRefresh:s.sso.autoRefresh,tokenSource:s.sso.tokenSource,tokenSourceConfig:s.sso.tokenSourceConfig,fallback:s.sso.fallback,map:s.sso.map},initToken:i.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,i.user.identity&&!i.user.identity.partnerToken&&(i.user.identity.partnerToken=I.token)}else if(!g&&s.sso&&s.sso.collect&&s.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(i.slug)}/sso_exchange`;o=await new cc({descriptor:s.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=o.extUid||a,l=l??o.displayName,c=o.userToken}let f="",y="";if(s.preflight&&s.preflight.length){const I=await jo(s.preflight,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const P=f;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(y=I.captured.requestId)}const b=new ac(s.auth,u);if(f){const I=s.tiledesk?.projectId??"",P=I?fc(a,I):null,O=s.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",B=P??(I?mc(O,I):"");b.prime(f,{requestId:B,fullName:l})}const w=await b.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,getSessionToken:()=>Jt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=d&&s.sso?.autoRefresh?async()=>{try{return await d.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,S=s.upload,v=async()=>`Bearer ${S&&"tokenSource"in S&&S.tokenSource==="chat"?(await b.get()).token:await Jt(i.user.token)}`,x=i.hooks?.upload??(S&&S.mode==="presigned-3step"?Ll({...S,authHeader:v}):S&&S.mode==="direct"?xo({endpoint:S.endpoint,fieldName:S.fieldName,extraFields:S.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await yc({container:Gf(i.container),config:s,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:i.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:x,historyAdapter:i.hooks?.history,conversationId:w.requestId||y||void 0,conversationScope:i.conversationScope,onError:i.hooks?.onError,onMessage:i.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Jt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:s,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=s.preflight;return!P||!P.length?{}:P.some(B=>B.trigger==="on-method-select")?(await jo(P,{sessionToken:u,userId:a,projectId:s.tiledesk?.projectId??"",slug:i.slug,identity:{...i.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}function Kf(i){Ro();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,s]of Object.entries(t)){const n=i[r];n!=null&&e.setAttribute(s,String(n))}return e.configure(i),document.body.appendChild(e),e}function Yf(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Jf="https://checkout.razorpay.com/v1/checkout.js";let ur=null;function dr(){return window}class vc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,s)=>{const n=r.name||"Open link",o=!!this.paidIdx[s];return`<button class="link${o?" paid":""}" data-i="${s}" type="button"${o?" disabled":""}><span class="lbl">${Qf(o?"Paid":n)}</span>`+(o?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const s=Number(r.dataset.i||0),n=e[s];n&&this.handleClick(s,n)})})}handleClick(e,t){const r=Xf(t),s=dr().__aikaara_descriptor__,n=s?.partnerPayment,o=s?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!o?.keyId){t.openLinkInNewTab?window.open(t.url,"_blank","noopener,noreferrer"):ip(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}ep(o.preferredBanksUrl,r,o.preferredBanksMethod,o.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Zf().then(()=>this.openRazorpay(e,r,o,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,s){tp(t,s).then(n=>{if(!n){Qt("Failed to generate payment link, please try again later");return}const o=(n.paymentStatus??"").toLowerCase();if(o==="paid"||o==="success"||o==="completed"){this.paidIdx[e]=!0,this.render(),Qt("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){Qt("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=rp(a);if(!u){window.open(a,"_blank"),Qt("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),np(u,s.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{Qt(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),Qt("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,s){const n=dr(),o=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof o.mobile=="string"?a.prefill.contact=o.mobile:typeof o.phone=="string"&&(a.prefill.contact=o.phone),typeof o.email=="string"&&(a.prefill.email=o.email),typeof o.name=="string"?a.prefill.name=o.name:typeof o.userName=="string"&&(a.prefill.name=o.userName),Array.isArray(s)&&s.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:s}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Qf(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Xf(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),s=r.get("orderId")||r.get("order_id");if(s)return s}}catch{}return null}function Zf(){return typeof dr().Razorpay=="function"?Promise.resolve():ur||(ur=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Jf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{ur=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),ur)}function ep(i,e,t,r){if(!i)return Promise.resolve([]);const s=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),o=dr().__aikaara_runtime__??{};return(typeof o.getSessionToken=="function"?o.getSessionToken():typeof o.getChatJwt=="function"?o.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:s,headers:c,credentials:"omit"};return s==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(p=>{if(typeof p=="string")return p;if(p&&typeof p=="object"){const g=p;return g.code||g.bankCode||g.bank_code||null}return null}).filter(p=>!!p)})}async function tp(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,s=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=dr().__aikaara_runtime__??{},o=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};o&&(a.Authorization=`Bearer ${o}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(s,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function rp(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),s=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${s},scrollbars=yes,resizable=yes`)}function np(i,e,t){let r=!1;function s(){clearInterval(a),window.removeEventListener("message",o)}function n(l){r||(r=!0,s(),l())}function o(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",o)}function Qt(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function ip(i,e){if(!i)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(i,e):window.open(i,"_blank","noopener,noreferrer")}function op(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",vc)}const sp=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:vc,registerAikaaraPaymentLink:op},Symbol.toStringTag,{value:"Module"}));class wc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1599
|
+
`}}function xt(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ke(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ce(i){return String(i).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Xt(i){return Ce(i)}function nt(i){return`₹${Math.round(Number.isFinite(i)?i:0).toLocaleString("en-IN")}`}function an(i){const e=Number(i.basePrice)||0,t=i.gstRate??.18,r=Math.round(e*t),o=Number(i.discount)||0;return{base:e,gst:r,discount:o,total:e+r-o}}function Uo(i){const[e,t,r]=i.split("-").map(Number);return new Date(e||1970,(t||1)-1,r||1)}function pc(i){const e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),r=String(i.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Dp(i,e){const t=new Date(i);return t.setDate(t.getDate()+e),t}function Bo(i){return Uo(i).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}function $p(i){const e=Uo(i);return{weekday:e.toLocaleDateString("en-GB",{weekday:"short"}),day:String(e.getDate()),month:e.toLocaleDateString("en-GB",{month:"short"})}}function pr(i){const[e=0,t=0]=i.split(":").map(Number);return`${fc(e*60+t)} – ${fc(e*60+t+30)}`}function fc(i){const e=(i%1440+1440)%1440,t=Math.floor(e/60),r=e%60,o=(t+11)%12+1,n=t<12?"AM":"PM";return`${o}:${String(r).padStart(2,"0")} ${n}`}const Up="serviceId";class Bp extends HTMLElement{shadow;data=null;selectedId=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{services:[]},this.dataset.consumed!=="true"&&(this.selectedId=null),this.render()}getName(){return this.data?.postbackKey??Up}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;typeof r=="string"&&r&&(this.selectedId=r),this.render()}locked(){return this.dataset.consumed==="true"}select(e){this.locked()||!this.data||(this.selectedId=e.id,this.render(),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e.name,attributes:{action:{[this.getName()]:e.id,serviceName:e.name,basePrice:e.basePrice,...e.discount?{discount:e.discount}:{},...this.data.messageId?{message_id:this.data.messageId}:{},...this.data.action??{}}}},bubbles:!0,composed:!0})))}render(){const e=this.data?.services??[],t=this.data?.showFrom??!0,r=e.map(o=>`
|
|
1600
|
+
<button class="service" type="button" role="radio" aria-checked="${o.id===this.selectedId}"
|
|
1601
|
+
data-id="${Xt(o.id)}" ${this.locked()?"disabled":""}>
|
|
1602
|
+
<span class="info">
|
|
1603
|
+
<span class="name">${Ce(o.name)}</span>
|
|
1604
|
+
${o.tagline?`<span class="tagline">${Ce(o.tagline)}</span>`:""}
|
|
1605
|
+
</span>
|
|
1606
|
+
${t?`<span class="from">from ${Ce(nt(o.basePrice))}</span>`:""}
|
|
1607
|
+
</button>`).join("");this.shadow.innerHTML=`
|
|
1608
|
+
<style>${Fp}</style>
|
|
1609
|
+
<div class="card" part="card">
|
|
1610
|
+
${this.data?.title?`<div class="title">${Ce(this.data.title)}</div>`:""}
|
|
1611
|
+
${this.data?.subtitle?`<div class="subtitle">${Ce(this.data.subtitle)}</div>`:""}
|
|
1612
|
+
<div class="list" role="radiogroup" aria-label="${Xt(this.data?.title??"Select a service")}">
|
|
1613
|
+
${r||'<div class="empty">No services available.</div>'}
|
|
1614
|
+
</div>
|
|
1615
|
+
</div>
|
|
1616
|
+
`,this.shadow.querySelectorAll("button.service").forEach(o=>{o.addEventListener("click",()=>{const n=o.dataset.id,s=e.find(a=>a.id===n);s&&this.select(s)})})}}const Fp=`
|
|
1617
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1618
|
+
.card {
|
|
1619
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1620
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1621
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1622
|
+
padding: 14px;
|
|
1623
|
+
}
|
|
1624
|
+
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1625
|
+
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1626
|
+
.list { display: flex; flex-direction: column; gap: 10px; margin-top: 12px; }
|
|
1627
|
+
.empty { padding: 16px 4px; text-align: center; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1628
|
+
.service {
|
|
1629
|
+
display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
|
|
1630
|
+
width: 100%; text-align: left; cursor: pointer; font-family: inherit;
|
|
1631
|
+
background: var(--aikaara-service-card-bg, var(--aikaara-surface, #fff));
|
|
1632
|
+
border: 1.5px solid var(--aikaara-border, #e5e7eb);
|
|
1633
|
+
border-radius: 12px; padding: 14px;
|
|
1634
|
+
transition: border-color 120ms, background 120ms;
|
|
1635
|
+
}
|
|
1636
|
+
.service:hover:not(:disabled) { border-color: var(--aikaara-primary, #6366f1); }
|
|
1637
|
+
.service[aria-checked="true"] { border-color: var(--aikaara-primary, #6366f1); background: var(--aikaara-primary-soft, #eef2ff); }
|
|
1638
|
+
.service:disabled { cursor: default; opacity: 0.85; }
|
|
1639
|
+
.info { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
|
1640
|
+
.name { font-weight: 600; font-size: 14px; }
|
|
1641
|
+
.tagline { font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1642
|
+
.from { flex-shrink: 0; font-size: 13px; font-weight: 600; color: var(--aikaara-primary, #6366f1); white-space: nowrap; }
|
|
1643
|
+
`,qp="serviceDetails";class Hp extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e,this.render()}getName(){return this.data?.postbackKey??qp}locked(){return this.dataset.consumed==="true"}handleContinue(){if(this.locked()||!this.data)return;const e=this.data.continueLabel??"Continue",t={[this.getName()]:!0,serviceName:this.data.name};typeof this.data.basePrice=="number"&&(t.total=an({basePrice:this.data.basePrice,discount:this.data.discount,gstRate:this.data.gstRate}).total),this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const{name:e,tagline:t,badge:r,inclusions:o=[],limitations:n=[],extraInclusions:s=[],extraLimitations:a=[]}=this.data,c=(this.data.showPricing??!0)&&typeof this.data.basePrice=="number"?an({basePrice:this.data.basePrice??0,discount:this.data.discount,gstRate:this.data.gstRate}):null,u=[...o,...s],d=[...n,...a],h=u.map(y=>`<li class="row"><span class="mark ok">✓</span><span>${Ce(y)}</span></li>`).join(""),g=d.map(y=>`<li class="row muted"><span class="mark no">✕</span><span>${Ce(y)}</span></li>`).join(""),p=c?`
|
|
1644
|
+
<div class="section">
|
|
1645
|
+
<h3>Pricing</h3>
|
|
1646
|
+
<div class="price">
|
|
1647
|
+
<div class="prow"><span>Service price</span><span>${Ce(nt(c.base))}</span></div>
|
|
1648
|
+
<div class="prow"><span>GST (${Math.round((this.data.gstRate??.18)*100)}%)</span><span>${Ce(nt(c.gst))}</span></div>
|
|
1649
|
+
${c.discount>0?`<div class="prow green"><span>Offer discount</span><span>-${Ce(nt(c.discount))}</span></div>`:""}
|
|
1650
|
+
<div class="prow total"><span>Final payable</span><span>${Ce(nt(c.total))}</span></div>
|
|
1651
|
+
</div>
|
|
1652
|
+
</div>`:"",b=this.locked()?"":`<button class="cta" type="button">${Ce(this.data.continueLabel??"Continue")}</button>`;this.shadow.innerHTML=`
|
|
1653
|
+
<style>${Wp}</style>
|
|
1654
|
+
<div class="card" part="card">
|
|
1655
|
+
<div class="section">
|
|
1656
|
+
${r?`<span class="badge">${Ce(r)}</span>`:""}
|
|
1657
|
+
<h2 class="name">${Ce(e)}</h2>
|
|
1658
|
+
${t?`<p class="tagline">${Ce(t)}</p>`:""}
|
|
1659
|
+
</div>
|
|
1660
|
+
${h?`<div class="section"><h3>What's Included</h3><ul>${h}</ul></div>`:""}
|
|
1661
|
+
${g?`<div class="section"><h3>Not Included</h3><ul>${g}</ul></div>`:""}
|
|
1662
|
+
${p}
|
|
1663
|
+
${b}
|
|
1664
|
+
</div>
|
|
1665
|
+
`,this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}const Wp=`
|
|
1666
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1667
|
+
.card {
|
|
1668
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1669
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1670
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1671
|
+
padding: 14px;
|
|
1672
|
+
}
|
|
1673
|
+
.section + .section { margin-top: 14px; border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 14px; }
|
|
1674
|
+
.badge {
|
|
1675
|
+
display: inline-block; padding: 3px 10px; border-radius: 999px; font-size: 12px; font-weight: 500;
|
|
1676
|
+
background: var(--aikaara-primary-soft, #eef2ff); color: var(--aikaara-primary, #6366f1);
|
|
1677
|
+
}
|
|
1678
|
+
.name { margin: 8px 0 0; font-size: 19px; font-weight: 700; color: var(--aikaara-text, #111827); }
|
|
1679
|
+
.tagline { margin: 2px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1680
|
+
h3 { margin: 0; font-size: 14px; font-weight: 600; }
|
|
1681
|
+
ul { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
|
1682
|
+
.row { display: flex; gap: 8px; font-size: 13px; align-items: flex-start; }
|
|
1683
|
+
.row.muted { color: var(--aikaara-text-secondary, #6b7280); }
|
|
1684
|
+
.mark { flex-shrink: 0; font-weight: 700; line-height: 1.4; }
|
|
1685
|
+
.mark.ok { color: #16a34a; }
|
|
1686
|
+
.mark.no { color: #9ca3af; }
|
|
1687
|
+
.price { margin-top: 8px; display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
|
|
1688
|
+
.prow { display: flex; justify-content: space-between; }
|
|
1689
|
+
.prow.green span:last-child { color: #16a34a; }
|
|
1690
|
+
.prow.total { border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 8px; font-size: 15px; font-weight: 700; }
|
|
1691
|
+
.cta {
|
|
1692
|
+
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1693
|
+
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1694
|
+
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1695
|
+
font-family: inherit; cursor: pointer;
|
|
1696
|
+
}
|
|
1697
|
+
.cta:hover { filter: brightness(0.96); }
|
|
1698
|
+
`,zp="priceAccepted";class Vp extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e,this.render()}getName(){return this.data?.postbackKey??zp}locked(){return this.dataset.consumed==="true"}handleContinue(){if(this.locked()||!this.data)return;const e=this.data.continueLabel??"Continue",t=an(this.data),r={[this.getName()]:!0,total:t.total};this.data.name&&(r.serviceName=this.data.name),this.data.messageId&&(r.message_id=this.data.messageId),Object.assign(r,this.data.action??{}),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=an(this.data),t=Math.round((this.data.gstRate??.18)*100),r=this.data.feeLabel??"Service Fee",o=this.data.discountLabel??"Discount",n=this.data.totalLabel??"Total Payable",s=this.data.name?`${Ce(this.data.name)} Consultation`:"Price Breakdown",a=this.locked()?"":`<button class="cta" type="button">${Ce(this.data.continueLabel??"Continue to Schedule")}</button>`;this.shadow.innerHTML=`
|
|
1699
|
+
<style>${Kp}</style>
|
|
1700
|
+
<div class="card" part="card">
|
|
1701
|
+
<h2>${s}</h2>
|
|
1702
|
+
<p class="sub">30 minute call with a tax expert</p>
|
|
1703
|
+
<table>
|
|
1704
|
+
<thead><tr><th>Particular</th><th class="right">Amount</th></tr></thead>
|
|
1705
|
+
<tbody>
|
|
1706
|
+
<tr><td>${Ce(r)}</td><td class="right">${Ce(nt(e.base))}</td></tr>
|
|
1707
|
+
<tr><td>GST (${t}%)</td><td class="right">${Ce(nt(e.gst))}</td></tr>
|
|
1708
|
+
<tr class="green"><td>${Ce(o)}</td><td class="right">${e.discount?"-"+Ce(nt(e.discount)):Ce(nt(0))}</td></tr>
|
|
1709
|
+
<tr class="total"><td>${Ce(n)}</td><td class="right">${Ce(nt(e.total))}</td></tr>
|
|
1710
|
+
</tbody>
|
|
1711
|
+
</table>
|
|
1712
|
+
${this.data.note?`<p class="note">${Ce(this.data.note)}</p>`:""}
|
|
1713
|
+
${a}
|
|
1714
|
+
</div>
|
|
1715
|
+
`,this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}const Kp=`
|
|
1716
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1717
|
+
.card {
|
|
1718
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1719
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1720
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1721
|
+
padding: 14px;
|
|
1722
|
+
}
|
|
1723
|
+
h2 { margin: 0; font-size: 16px; font-weight: 700; color: var(--aikaara-text, #111827); }
|
|
1724
|
+
.sub { margin: 2px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1725
|
+
table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: 13px; }
|
|
1726
|
+
th { padding: 8px 0; text-align: left; font-weight: 500; color: var(--aikaara-text-secondary, #6b7280); border-bottom: 1px solid var(--aikaara-border, #eef1f4); }
|
|
1727
|
+
td { padding: 9px 0; }
|
|
1728
|
+
.right { text-align: right; }
|
|
1729
|
+
tr.green td { color: #16a34a; }
|
|
1730
|
+
tr.total td { border-top: 1px solid var(--aikaara-border, #eef1f4); font-size: 15px; font-weight: 700; }
|
|
1731
|
+
.note { margin: 8px 0 0; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1732
|
+
.cta {
|
|
1733
|
+
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1734
|
+
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1735
|
+
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1736
|
+
font-family: inherit; cursor: pointer;
|
|
1737
|
+
}
|
|
1738
|
+
.cta:hover { filter: brightness(0.96); }
|
|
1739
|
+
`,Gp=["09:00","10:00","11:00","12:00","14:00","15:00","16:00","17:00"],Yp=7,Jp="callSlot";class Qp extends HTMLElement{shadow;data=null;selectedDate=null;selectedSlot=null;availabilityOverride=null;loading=!1;errorMessage="";submitted=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{},this.availabilityOverride=null,this.loading=!1,this.errorMessage="",this.dataset.consumed!=="true"&&(this.submitted=!1,this.selectedDate=null,this.selectedSlot=null),this.render()}setAvailability(e){this.availabilityOverride=Array.isArray(e)?e:[],this.selectedSlot=null,this.render()}setSlots(e){this.setAvailability(e)}setLoading(e){this.loading=!!e,this.render()}setError(e){this.errorMessage=e??"",this.render()}getName(){return this.data?.postbackKey??Jp}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;if(typeof r=="string"&&r.trim()){const[o,n]=r.trim().split(/[ T]/);o&&(this.selectedDate=o),n&&(this.selectedSlot=n),this.submitted=!0}this.render()}isLocked(){return this.submitted||this.dataset.consumed==="true"}normalizeDays(){const e=this.data;if(!e)return[];const t=new Set(e.disabledDates??[]),r=this.availabilityOverride??e.days??e.availability??e.slots;if(r&&r.length)return r.filter(l=>l&&typeof l.date=="string").map(l=>({iso:l.date,slots:(l.slots??[]).map(Xp)})).filter(l=>!t.has(l.iso));const o=e.startDate?Uo(e.startDate):new Date,n=Math.max(1,e.daysAhead??Yp),s=e.times&&e.times.length?e.times:Gp,a=[];for(let l=0;l<n;l++){const c=pc(Dp(o,l));t.has(c)||a.push({iso:c,slots:s.map(u=>({start:u,available:!0}))})}return a}isSelectable(e,t){if(t.available===!1)return!1;if(e!==pc(new Date))return!0;const[r=0,o=0]=t.start.split(":").map(Number),n=new Date;return r*60+o>n.getHours()*60+n.getMinutes()}selectDate(e){this.isLocked()||(this.selectedDate=e,this.selectedSlot=null,this.render())}selectSlot(e){this.isLocked()||(this.selectedSlot=e,this.render())}handleContinue(){if(this.isLocked()||!this.data||!this.selectedDate||!this.selectedSlot)return;const e=this.data.continueLabel??"Continue",t={[this.getName()]:`${this.selectedDate} ${this.selectedSlot}`,scheduledDate:this.selectedDate,scheduledTime:this.selectedSlot,slot:this.selectedSlot,slotLabel:pr(this.selectedSlot)};this.data.timezone&&(t.timezone=this.data.timezone),this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.submitted=!0,this.render(),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??e,attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}if(this.isLocked()&&this.selectedDate&&this.selectedSlot){this.shadow.innerHTML=this.lockedTemplate();return}const e=this.normalizeDays();e.length&&(!this.selectedDate||!e.some(r=>r.iso===this.selectedDate))&&(this.selectedDate=e[0].iso,this.selectedSlot=null);const t=e.find(r=>r.iso===this.selectedDate)??null;this.shadow.innerHTML=`
|
|
1740
|
+
<style>${mc}</style>
|
|
1741
|
+
<div class="card" part="card">
|
|
1742
|
+
${this.data.title?`<div class="title">${Ce(this.data.title)}</div>`:""}
|
|
1743
|
+
${this.data.subtitle?`<div class="subtitle">${Ce(this.data.subtitle)}</div>`:""}
|
|
1744
|
+
${this.renderBody(e,t)}
|
|
1745
|
+
</div>
|
|
1746
|
+
`,this.attachListeners()}renderBody(e,t){if(this.loading)return'<div class="state">Loading available times…</div>';if(this.errorMessage)return`<div class="state error">${Ce(this.errorMessage)}</div>`;if(!e.length)return'<div class="state">No call slots are available right now.</div>';const r=e.map(a=>{const{weekday:l,day:c,month:u}=$p(a.iso);return`
|
|
1747
|
+
<button class="day" type="button" role="radio" aria-checked="${a.iso===this.selectedDate}" data-date="${Xt(a.iso)}">
|
|
1748
|
+
<span class="day-weekday">${Ce(l)}</span>
|
|
1749
|
+
<span class="day-num">${Ce(c)}</span>
|
|
1750
|
+
<span class="day-month">${Ce(u)}</span>
|
|
1751
|
+
</button>`}).join(""),o=(t?.slots??[]).map(a=>{const l=t?this.isSelectable(t.iso,a):!1;return`
|
|
1752
|
+
<button class="slot" type="button" role="radio" aria-checked="${a.start===this.selectedSlot}"
|
|
1753
|
+
data-time="${Xt(a.start)}" ${l?"":"disabled"}>
|
|
1754
|
+
${Ce(pr(a.start))}
|
|
1755
|
+
</button>`}).join(""),n=this.selectedDate&&this.selectedSlot?`<div class="summary">${Ce(Bo(this.selectedDate))} · ${Ce(pr(this.selectedSlot))}</div>`:"",s=this.isLocked()?"":`<button class="cta" type="button" ${this.selectedDate&&this.selectedSlot?"":"disabled"}>
|
|
1756
|
+
${Ce(this.data?.continueLabel??"Continue")}
|
|
1757
|
+
</button>`;return`
|
|
1758
|
+
<section><h3>Select Date</h3><div class="days" role="radiogroup" aria-label="Select a date">${r}</div></section>
|
|
1759
|
+
<section>
|
|
1760
|
+
<h3>Select Time Slot</h3>
|
|
1761
|
+
${t?`<div class="times" role="radiogroup" aria-label="Select a time">${o}</div>`:'<p class="hint">Pick a date to see available slots.</p>'}
|
|
1762
|
+
</section>
|
|
1763
|
+
${n}
|
|
1764
|
+
${s}
|
|
1765
|
+
`}lockedTemplate(){return`
|
|
1766
|
+
<style>${mc}</style>
|
|
1767
|
+
<div class="card locked" part="card">
|
|
1768
|
+
<div class="locked-head"><span class="tick" aria-hidden="true">✓</span> Slot selected</div>
|
|
1769
|
+
<div class="locked-when">${Ce(Bo(this.selectedDate))} · ${Ce(pr(this.selectedSlot))}</div>
|
|
1770
|
+
${this.data?.timezone?`<div class="locked-tz">${Ce(this.data.timezone)}</div>`:""}
|
|
1771
|
+
</div>
|
|
1772
|
+
`}attachListeners(){this.shadow.querySelectorAll("button.day").forEach(e=>{e.addEventListener("click",()=>this.selectDate(e.dataset.date||""))}),this.shadow.querySelectorAll("button.slot").forEach(e=>{e.addEventListener("click",()=>this.selectSlot(e.dataset.time||""))}),this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}function Xp(i){return typeof i=="string"?{start:i,available:!0}:{start:i.start,available:i.available}}const mc=`
|
|
1773
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1774
|
+
.card {
|
|
1775
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1776
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1777
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1778
|
+
padding: 14px;
|
|
1779
|
+
}
|
|
1780
|
+
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1781
|
+
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1782
|
+
section { margin-top: 12px; }
|
|
1783
|
+
h3 { margin: 0 0 8px; font-size: 14px; font-weight: 600; }
|
|
1784
|
+
.state, .hint { padding: 12px 2px; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1785
|
+
.state { text-align: center; }
|
|
1786
|
+
.state.error { color: var(--aikaara-input-error-color, #ef4444); }
|
|
1787
|
+
.days { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 4px; }
|
|
1788
|
+
.day {
|
|
1789
|
+
flex: 0 0 auto; display: flex; flex-direction: column; align-items: center; gap: 1px;
|
|
1790
|
+
min-width: 54px; padding: 8px 6px; cursor: pointer; font-family: inherit;
|
|
1791
|
+
background: var(--aikaara-slot-day-bg, transparent);
|
|
1792
|
+
color: var(--aikaara-text, #1f2937);
|
|
1793
|
+
border: 1.5px solid var(--aikaara-border, #e5e7eb);
|
|
1794
|
+
border-radius: 10px; transition: border-color 120ms, background 120ms, color 120ms;
|
|
1795
|
+
}
|
|
1796
|
+
.day:hover { border-color: var(--aikaara-primary, #6366f1); }
|
|
1797
|
+
.day[aria-checked="true"] { background: var(--aikaara-primary, #6366f1); color: #fff; border-color: var(--aikaara-primary, #6366f1); }
|
|
1798
|
+
.day-weekday, .day-month { font-size: 11px; opacity: 0.85; }
|
|
1799
|
+
.day-num { font-size: 16px; font-weight: 700; line-height: 1.1; }
|
|
1800
|
+
.times { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
|
1801
|
+
.slot {
|
|
1802
|
+
padding: 9px 8px; font-size: 13px; font-family: inherit; cursor: pointer;
|
|
1803
|
+
background: var(--aikaara-slot-bg, transparent);
|
|
1804
|
+
color: var(--aikaara-text, #1f2937);
|
|
1805
|
+
border: 1.5px solid var(--aikaara-slot-border, var(--aikaara-border, #e5e7eb));
|
|
1806
|
+
border-radius: 9px; transition: background 120ms, color 120ms, border-color 120ms;
|
|
1807
|
+
}
|
|
1808
|
+
.slot:hover:not(:disabled) { border-color: var(--aikaara-primary, #6366f1); }
|
|
1809
|
+
.slot[aria-checked="true"] { background: var(--aikaara-primary, #6366f1); color: #fff; border-color: var(--aikaara-primary, #6366f1); font-weight: 600; }
|
|
1810
|
+
.slot:disabled { cursor: not-allowed; text-decoration: line-through; opacity: 0.55; }
|
|
1811
|
+
.summary {
|
|
1812
|
+
margin-top: 12px; padding: 10px 12px; border-radius: 10px; font-size: 13px; font-weight: 600;
|
|
1813
|
+
background: var(--aikaara-primary-soft, #eef2ff); color: var(--aikaara-primary, #6366f1);
|
|
1814
|
+
}
|
|
1815
|
+
.cta {
|
|
1816
|
+
width: 100%; margin-top: 12px; padding: 12px 16px;
|
|
1817
|
+
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1818
|
+
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1819
|
+
font-family: inherit; cursor: pointer;
|
|
1820
|
+
}
|
|
1821
|
+
.cta:hover:not(:disabled) { filter: brightness(0.96); }
|
|
1822
|
+
.cta:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
1823
|
+
.card.locked { background: var(--aikaara-surface-muted, #f6fafb); }
|
|
1824
|
+
.locked-head { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; }
|
|
1825
|
+
.tick { color: #16a34a; font-weight: 700; }
|
|
1826
|
+
.locked-when { margin-top: 6px; font-size: 14px; }
|
|
1827
|
+
.locked-tz { margin-top: 2px; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1828
|
+
`,Zp="callDetails";class ef extends HTMLElement{shadow;data=null;query="";fileNames=[];error="";submitted=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{},this.query="",this.fileNames=[],this.error="",this.dataset.consumed!=="true"&&(this.submitted=!1),this.render()}getName(){return this.data?.postbackKey??Zp}setConsumedValues(e){const t=e?.query,r=Array.isArray(t)?t[0]:t;typeof r=="string"&&(this.query=r),Array.isArray(e?.fileNames)&&(this.fileNames=e.fileNames),this.submitted=!0,this.render()}uploadConfig(){const e=this.data?.upload;return e===!1?{enabled:!1}:e===!0||e===void 0?{enabled:!0}:{enabled:e.enabled??!0,...e}}queryConfig(){const e=this.data?.query;return e===!1?{enabled:!1}:e===!0||e===void 0?{enabled:!0}:{enabled:e.enabled??!0,...e}}isLocked(){return this.submitted||this.dataset.consumed==="true"}handleFiles(e){if(!e)return;const t=this.uploadConfig().maxFiles??10,r=[...this.fileNames,...Array.from(e).map(o=>o.name)];this.fileNames=r.slice(0,t),this.render()}handleSubmit(){if(this.isLocked()||!this.data)return;const e=this.queryConfig();if(e.enabled!==!1&&e.required&&!this.query.trim()){this.error="Please describe your query",this.render();return}this.error="";const t={[this.getName()]:!0,query:this.query.trim(),fileNames:[...this.fileNames],fileCount:this.fileNames.length};this.data.messageId&&(t.message_id=this.data.messageId),Object.assign(t,this.data.action??{}),this.submitted=!0,this.render(),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:this.data.postbackMessage??this.data.submitLabel??"Schedule Call",attributes:{action:t}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.uploadConfig(),t=this.queryConfig(),r=this.isLocked(),o=this.fileNames.length?`<ul class="files">${this.fileNames.map((c,u)=>`<li><span class="fname">${Ce(c)}</span>${r?"":`<button class="rm" type="button" data-i="${u}" aria-label="Remove file">✕</button>`}</li>`).join("")}</ul>`:"",n=e.enabled===!1?"":`
|
|
1829
|
+
<div class="section">
|
|
1830
|
+
<h3>${Ce(e.label??"Upload Documents")} <span class="opt">(Optional)</span></h3>
|
|
1831
|
+
<p class="hint">${Ce(e.hint??"ITR / tax documents, GST documents, notices, statements or anything that helps the expert understand your case.")}</p>
|
|
1832
|
+
${r?"":`<label class="drop">
|
|
1833
|
+
<span class="drop-title">Tap to upload</span>
|
|
1834
|
+
<span class="drop-hint">PDF, JPG, PNG · up to ${e.maxFiles??10} files</span>
|
|
1835
|
+
<input type="file" multiple accept="${Xt(e.accept??".pdf,.jpg,.jpeg,.png")}" />
|
|
1836
|
+
</label>`}
|
|
1837
|
+
${o}
|
|
1838
|
+
</div>`,s=t.enabled===!1?"":`
|
|
1839
|
+
<div class="section">
|
|
1840
|
+
<h3>${Ce(t.label??"Briefly describe your query")}</h3>
|
|
1841
|
+
${r?`<p class="locked-query">${Ce(this.query||"—")}</p>`:`<textarea rows="5" maxlength="${t.maxLength??1e3}"
|
|
1842
|
+
placeholder="${Xt(t.placeholder??"Briefly tell us what you would like to discuss with the expert.")}">${Ce(this.query)}</textarea>
|
|
1843
|
+
<p class="counter">${this.query.length}/${t.maxLength??1e3}</p>`}
|
|
1844
|
+
</div>`,a=r?"":`<button class="cta" type="button">${Ce(this.data.submitLabel??"Schedule Call")}</button>`;this.shadow.innerHTML=`
|
|
1845
|
+
<style>${tf}</style>
|
|
1846
|
+
<div class="card" part="card">
|
|
1847
|
+
${this.data.title?`<div class="title">${Ce(this.data.title)}</div>`:""}
|
|
1848
|
+
${this.data.subtitle?`<div class="subtitle">${Ce(this.data.subtitle)}</div>`:""}
|
|
1849
|
+
${n}
|
|
1850
|
+
${s}
|
|
1851
|
+
${this.error?`<p class="error">${Ce(this.error)}</p>`:""}
|
|
1852
|
+
${a}
|
|
1853
|
+
</div>
|
|
1854
|
+
`,this.shadow.querySelector('input[type="file"]')?.addEventListener("change",c=>{this.handleFiles(c.target.files)}),this.shadow.querySelectorAll("button.rm").forEach(c=>{c.addEventListener("click",()=>{const u=Number(c.dataset.i);this.fileNames=this.fileNames.filter((d,h)=>h!==u),this.render()})});const l=this.shadow.querySelector("textarea");l&&(l.value=this.query,l.addEventListener("input",()=>{this.query=l.value;const c=this.shadow.querySelector(".counter");c&&(c.textContent=`${this.query.length}/${this.queryConfig().maxLength??1e3}`)})),this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleSubmit())}}const tf=`
|
|
1855
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1856
|
+
.card {
|
|
1857
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1858
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1859
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1860
|
+
padding: 14px;
|
|
1861
|
+
}
|
|
1862
|
+
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1863
|
+
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1864
|
+
.section + .section { margin-top: 14px; border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 14px; }
|
|
1865
|
+
h3 { margin: 0; font-size: 14px; font-weight: 600; }
|
|
1866
|
+
.opt { font-weight: 400; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1867
|
+
.hint { margin: 4px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1868
|
+
.drop {
|
|
1869
|
+
display: flex; flex-direction: column; align-items: center; gap: 3px; margin-top: 10px;
|
|
1870
|
+
padding: 18px; border: 2px dashed var(--aikaara-input-border, #d1d5db); border-radius: 10px;
|
|
1871
|
+
cursor: pointer; text-align: center;
|
|
1872
|
+
}
|
|
1873
|
+
.drop:hover { border-color: var(--aikaara-primary, #6366f1); }
|
|
1874
|
+
.drop input { display: none; }
|
|
1875
|
+
.drop-title { font-size: 13px; font-weight: 600; color: var(--aikaara-primary, #6366f1); }
|
|
1876
|
+
.drop-hint { font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1877
|
+
.files { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
|
1878
|
+
.files li { display: flex; align-items: center; justify-content: space-between; gap: 8px; background: var(--aikaara-surface-muted, #f3f4f6); border-radius: 8px; padding: 8px 10px; font-size: 13px; }
|
|
1879
|
+
.fname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1880
|
+
.rm { border: none; background: transparent; cursor: pointer; color: var(--aikaara-text-secondary, #6b7280); font-size: 12px; }
|
|
1881
|
+
textarea {
|
|
1882
|
+
width: 100%; box-sizing: border-box; margin-top: 8px; padding: 10px 12px; resize: vertical;
|
|
1883
|
+
border: 1.5px solid var(--aikaara-input-border, #d1d5db); border-radius: 8px;
|
|
1884
|
+
background: var(--aikaara-input-bg, #fff); color: var(--aikaara-input-color, #111827);
|
|
1885
|
+
font-size: 14px; font-family: inherit; outline: none;
|
|
1886
|
+
}
|
|
1887
|
+
textarea:focus { border-color: var(--aikaara-primary, #6366f1); }
|
|
1888
|
+
.counter { margin: 4px 0 0; text-align: right; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1889
|
+
.locked-query { margin: 8px 0 0; font-size: 13px; white-space: pre-wrap; }
|
|
1890
|
+
.error { margin: 10px 0 0; font-size: 12px; color: var(--aikaara-input-error-color, #ef4444); }
|
|
1891
|
+
.cta {
|
|
1892
|
+
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1893
|
+
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1894
|
+
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1895
|
+
font-family: inherit; cursor: pointer;
|
|
1896
|
+
}
|
|
1897
|
+
.cta:hover { filter: brightness(0.96); }
|
|
1898
|
+
`;class rf extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e,t){this.data=e??{},this.render()}displayDate(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)?Bo(e):e}displayTime(e){return/^\d{2}:\d{2}$/.test(e)?pr(e):e}render(){if(!this.data){this.shadow.innerHTML="";return}const{expert:e,service:t,date:r,time:o,amount:n,bookingId:s,documents:a}=this.data,l=[];e&&l.push(["Expert",e]),t&&l.push(["Service",t]),r&&l.push(["Date",this.displayDate(r)]),o&&l.push(["Time",this.displayTime(o)]),typeof n=="number"&&l.push(["Amount paid",nt(n)]),s&&l.push(["Booking ID",s]),typeof a=="number"&&l.push(["Documents",`${a} uploaded`]);const c=l.map(([u,d])=>`<div class="row"><span class="label">${Ce(u)}</span><span class="value">${Ce(d)}</span></div>`).join("");this.shadow.innerHTML=`
|
|
1899
|
+
<style>${nf}</style>
|
|
1900
|
+
<div class="card" part="card">
|
|
1901
|
+
<div class="head">
|
|
1902
|
+
<div class="icon" aria-hidden="true">✓</div>
|
|
1903
|
+
<h2>${Ce(this.data.title??"Call Scheduled Successfully!")}</h2>
|
|
1904
|
+
${e?`<p class="with">Your call has been scheduled with</p><p class="expert">${Ce(e)}</p>`:""}
|
|
1905
|
+
</div>
|
|
1906
|
+
${c?`<div class="summary">${c}</div>`:""}
|
|
1907
|
+
<p class="note">${Ce(this.data.note??"A Google Meet link will be shared on your registered email & WhatsApp.")}</p>
|
|
1908
|
+
</div>
|
|
1909
|
+
`}}const nf=`
|
|
1910
|
+
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1911
|
+
.card {
|
|
1912
|
+
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1913
|
+
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1914
|
+
border-radius: var(--aikaara-radius, 12px);
|
|
1915
|
+
padding: 18px 14px;
|
|
1916
|
+
}
|
|
1917
|
+
.head { text-align: center; }
|
|
1918
|
+
.icon {
|
|
1919
|
+
width: 60px; height: 60px; margin: 4px auto 10px; border-radius: 50%;
|
|
1920
|
+
display: flex; align-items: center; justify-content: center;
|
|
1921
|
+
background: var(--aikaara-success-soft, #dcfce7); color: #16a34a; font-size: 30px; font-weight: 700;
|
|
1922
|
+
}
|
|
1923
|
+
h2 { margin: 0; font-size: 19px; font-weight: 700; }
|
|
1924
|
+
.with { margin: 6px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1925
|
+
.expert { margin: 2px 0 0; font-size: 15px; font-weight: 600; color: var(--aikaara-primary, #6366f1); }
|
|
1926
|
+
.summary { margin-top: 14px; border: 1px solid var(--aikaara-border, #eef1f4); border-radius: 10px; padding: 6px 12px; }
|
|
1927
|
+
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px 0; border-bottom: 1px solid var(--aikaara-border, #eef1f4); font-size: 13px; }
|
|
1928
|
+
.row:last-child { border-bottom: none; }
|
|
1929
|
+
.label { color: var(--aikaara-text-secondary, #6b7280); }
|
|
1930
|
+
.value { font-weight: 600; text-align: right; }
|
|
1931
|
+
.note { margin: 12px 0 0; text-align: center; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1932
|
+
`;function Fo(){const i=[["aikaara-chat-widget",Yl],["aikaara-chat-bubble",Jl],["aikaara-chat-header",Ql],["aikaara-message-list",ec],["aikaara-message-bubble",nc],["aikaara-chat-input",oc],["aikaara-typing-indicator",sc],["aikaara-streaming-message",ac],["aikaara-error-banner",lc],["aikaara-template-renderer",yp],["aikaara-system-pill",_p],["aikaara-option-list",xp],["aikaara-submit-action",Sp],["aikaara-modal-action",Ap],["aikaara-text-input",Ip],["aikaara-chat",Tp],["aikaara-link-modal",Cp],["aikaara-compare-plans",Lp],["aikaara-smart-edit-modal",Mp],["aikaara-schema-form",jp],["aikaara-service-picker",Bp],["aikaara-service-details",Hp],["aikaara-price-breakdown",Vp],["aikaara-slot-picker",Qp],["aikaara-call-upload",ef],["aikaara-call-confirmation",rf]];for(const[e,t]of i)customElements.get(e)||customElements.define(e,t)}Fo();function ln(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 gc(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 Zt(i){return typeof i=="function"?await i():i}class bc{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=gc(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 Zt(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=ln(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 h=ln(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||h||"",p=ln(l,this.descriptor.fullNamePath??"data.fullName"),b=ln(l,this.descriptor.userPath??"data.userId"),y=gc(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:p,userId:b,expiresAt:y},this.cache}}async function yc(i){const e={};for(const t of i.spec){const r=await of(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 of(i,e){const t=i.key??i.name;switch(i.source){case"cookie":return sf(t);case"localStorage":return cn(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return cn(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return cn(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return cn(()=>document.querySelector(`meta[name="${af(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 sf(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 cn(i){try{return i()}catch{return}}function af(i){return i.replace(/["\\]/g,"\\$&")}const lf=1800;class vc{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 yc({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??lf;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,uf=2e3,df=100;async function wc(i){const{descriptor:e}=i,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!i.initToken)throw new Ze("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=hf(r);if(!o)throw new Ze("query",`?${r}= not present`);return{token:o,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",o=pf(r);if(!o)throw new Ze("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=yf(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:cf;return{token:await bf({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 Ze("cookie","cookie.name not configured");const o=ff(r);if(!o)throw new Ze("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 Ze("storage","storage.key not configured");const s=mf(r,o,n);if(!s)throw new Ze("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 Ze("global","global.path not configured");const o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:uf,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:df,s=await gf(r,o,n);if(!s)throw new Ze("global",`window.${r} not present`);return{token:s,source:"global"}}default:{const r=e.tokenSource;throw new Ze("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class kc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await wc(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 Ze extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function hf(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 pf(i){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(i)??void 0}catch{return}}function ff(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 mf(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=_c(n,t);return typeof s=="string"?s:void 0}catch{return}}async function gf(i,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const o=_c(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 bf(i){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ze("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(o)},o=setTimeout(()=>{r(),t(new Ze("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 yf(i){return i?i.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function _c(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 vf(){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 wf="aikaara_chat:requestId";function qo(i,e,t){const r=`${wf}:${i}:${e}`;return t?`${r}:${t}`:r}function xc(i,e,t){try{return localStorage.getItem(qo(i,e,t))}catch{return null}}function kf(i,e,t,r){try{localStorage.setItem(qo(i,e,r),t)}catch{}}function _f(i,e,t){try{localStorage.removeItem(qo(i,e,t))}catch{}}async function Ho(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,h)=>h in o?o[h]:""),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[h,g]of Object.entries(u))d[h]=s(g);return d}return u},a=await Zt(e.sessionToken),l={},c=[800,1500,3e3,5e3,8e3];for(let u=0;u<r.length;u++){const d=r[u],h=n(d.url),g=d.method??(d.body?"POST":"GET"),p={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const x=d.authHeaderTemplate??"Bearer {token}";p.authorization=x.replace("{token}",a)}const b={method:g,headers:p};d.body&&(p["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const x=await fetch(h,b);if(x.ok){k=x;break}if(y=x.status,w=await x.text().catch(()=>""),m<c.length&&Sf(y,w)){const S=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${h} → ${y} (transient). Retry #${m} in ${S}ms.`),await new Promise(E=>setTimeout(E,S));continue}const v=`Preflight #${u} ${g} ${h} → ${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(k&&d.capture&&d.capture.as)try{const x=await k.clone().text();let v=x;try{v=JSON.parse(x)}catch{}if(d.capture.path)for(const 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 xf(i){const e=i.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await Ho(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 Sf(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 Sc(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 Ec(i,e){return i.replace("{projectId}",e).replace("{uuid}",vf().replace(/-/g,""))}function Ac(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 Ic(i){const e={...i.config??(i.configUrl?await Sc(i.configUrl,i.configHeaders):{}),...i.overrides??{}};Ac(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:xc(n,o,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=i.conversationId??a??Ec(l,o);(i.conversationId||!a||i.forceNewConversation)&&o&&kf(n,o,c,s);const u=await i.tokenProvider(),d=i.tokenProvider,h=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,p=i.uploadAdapter??(e.uploadEndpoint?Co({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=i.historyAdapter??(e.historyApiBase?Fl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):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:p,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 Ef(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 Tc(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 Sc(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(Ac(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,smartEdit:o.smartEdit??n.__aikaara_descriptor__?.smartEdit},!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 h=await Zt(i.user.token).catch(()=>""),g=typeof h=="string"&&h.length>0;if(!g&&o.sso?.tokenSource){d=new kc({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 vc({descriptor:o.sso,providers:i.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let p="",b="";if(o.preflight&&o.preflight.length){const I=await Ho(o.preflight,{sessionToken:u,userId:a,projectId:o.tiledesk?.projectId??"",slug:i.slug,identity:i.user.identity});if(I.captured.sessionToken){p=I.captured.sessionToken;const P=p;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new bc(o.auth,u);if(p){const I=o.tiledesk?.projectId??"",P=I?xc(a,I):null,O=o.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",U=P??(I?Ec(O,I):"");y.prime(p,{requestId:U,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:()=>Zt(i.user.token),identity:i.user.identity,slug:i.slug,configBase:e};const k=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 Zt(i.user.token)}`,S=i.hooks?.upload??(x&&x.mode==="presigned-3step"?Bl({...x,authHeader:v}):x&&x.mode==="direct"?Co({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),E=await Ic({container:Ef(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:Zt(i.user.token)});return Object.assign(E,{fullName:m,requestId:w.requestId,descriptor:o,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=o.preflight;return!P||!P.length?{}:P.some(U=>U.trigger==="on-method-select")?(await Ho(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:{}}})}function Af(i){Fo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,o]of Object.entries(t)){const n=i[r];n!=null&&e.setAttribute(o,String(n))}return e.configure(i),document.body.appendChild(e),e}function If(){const i=document.querySelector("aikaara-chat-widget");i&&i.remove()}const Tf="https://checkout.razorpay.com/v1/checkout.js";let fr=null;function mr(){return window}class Cc extends HTMLElement{shadow;payloadData=[];message="";paidIdx={};constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}setPayload(e,t){this.payloadData=Array.isArray(e)?e:[],this.message=t??"",this.render()}render(){const e=this.payloadData.filter(r=>!!r&&typeof r=="object"&&r.type==="link"&&typeof r.url=="string"),t=e.map((r,o)=>{const n=r.name||"Open link",s=!!this.paidIdx[o];return`<button class="link${s?" paid":""}" data-i="${o}" type="button"${s?" disabled":""}><span class="lbl">${Cf(s?"Paid":n)}</span>`+(s?'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8.5 L7 12 L13 5"/></svg>':'<svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 11 L11 5 M6 5 H11 V10"/></svg>')+"</button>"}).join("");this.shadow.innerHTML="<style>:host { display:block; margin:6px 0; font-family:inherit; }.bubble { padding:12px 16px; border-radius:14px; background:var(--aikaara-bot-bubble-bg, #d8e5f5); color:var(--aikaara-bot-bubble-text, #1a2845); font-size:14px; line-height:1.55; margin-bottom:10px; }.links { display:flex; flex-direction:column; gap:8px; }.link { display:inline-flex; align-items:center; justify-content:center; gap:8px; padding:11px 22px; border:1.5px solid var(--aikaara-primary, #1849a9); background:var(--aikaara-primary, #1849a9); color:var(--aikaara-primary-contrast, #fff); border-radius:24px; font-size:14px; font-weight:600; cursor:pointer; font-family:inherit; text-decoration:none; transition: filter 120ms; width:150px; align-self:flex-start; }.link:hover:not(:disabled) { filter: brightness(0.94); }.link.paid, .link:disabled { background:#e7f5ec; color:#0e7c3a; border-color:#0e7c3a; cursor:default; }.icon { width:13px; height:13px; }</style>"+(this.message?`<div class="bubble">${this.message}</div>`:"")+`<div class="links">${t}</div>`,this.shadow.querySelectorAll(".link").forEach(r=>{r.addEventListener("click",()=>{if(r.disabled)return;const o=Number(r.dataset.i||0),n=e[o];n&&this.handleClick(o,n)})})}handleClick(e,t){const r=Pf(t),o=mr().__aikaara_descriptor__,n=o?.partnerPayment,s=o?.razorpay;if(r&&n?.paymentLinkUrl){this.openPartnerPaymentLink(e,r,t,n);return}if(!r||!s?.keyId){t.openLinkInNewTab?window.open(t.url,"_blank","noopener,noreferrer"):jf(t.url,t.name||"Pay"),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t.name||"link-click",attributes:{action:{type:"link",url:t.url,orderId:r||t.orderId,openedIn:"modal"}}},bubbles:!0,composed:!0}));return}Lf(s.preferredBanksUrl,r,s.preferredBanksMethod,s.preferredBanksHeaders).catch(a=>(console.warn("[payment_link] preferred-banks fetch failed; continuing with default UI",a),[])).then(a=>Of().then(()=>this.openRazorpay(e,r,s,a))).catch(a=>{console.error("[payment_link] Razorpay launch failed",a)})}openPartnerPaymentLink(e,t,r,o){Mf(t,o).then(n=>{if(!n){er("Failed to generate payment link, please try again later");return}const s=(n.paymentStatus??"").toLowerCase();if(s==="paid"||s==="success"||s==="completed"){this.paidIdx[e]=!0,this.render(),er("Payment already completed");return}const a=n.vendorPaymentLink;if(!a){er("Failed to generate payment link, please try again later");return}const l=navigator.userAgent.toLowerCase();if(l.includes("iphone")||l.includes("ipad")||l.includes("ipod")){window.location.href=a;return}const u=Nf(a);if(!u){window.open(a,"_blank"),er("Allow popups for the best payment experience");return}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:r.name||"link-click",attributes:{action:{type:"partner-payment",url:a,orderId:t,openedIn:"popup"}}},bubbles:!0,composed:!0})),Rf(u,o.checkoutOrigin,{onSuccess:()=>{this.paidIdx[e]=!0,this.render()},onError:d=>{er(d||"Payment failed, please try again")},onClose:()=>{}})}).catch(n=>{console.error("[payment_link] partner payment link fetch failed",n),er("Failed to generate payment link, please try again later")})}openRazorpay(e,t,r,o){const n=mr(),s=n.__aikaara_runtime__?.identity??{},a={key:r.keyId,order_id:t,name:r.name||n.__aikaara_descriptor__?.title||"Payment",prefill:{},handler:()=>{this.paidIdx[e]=!0,this.render()},modal:{ondismiss:()=>{}}};typeof s.mobile=="string"?a.prefill.contact=s.mobile:typeof s.phone=="string"&&(a.prefill.contact=s.phone),typeof s.email=="string"&&(a.prefill.email=s.email),typeof s.name=="string"?a.prefill.name=s.name:typeof s.userName=="string"&&(a.prefill.name=s.userName),Array.isArray(o)&&o.length&&(a.config={display:{blocks:{utib:{name:"Pay Using Preferred Netbanking",instruments:[{method:"netbanking",banks:o}]}},sequence:["block.utib","netbanking","card","upi"],preferences:{show_default_blocks:!0}}});const l=n.Razorpay;if(typeof l!="function")throw new Error("Razorpay Checkout script not available");const c=new l(a);c.on("payment.failed",u=>{console.warn("[payment_link] payment.failed",u?.error)}),c.open()}}function Cf(i){return String(i??"").replace(/[&<>]/g,e=>e==="&"?"&":e==="<"?"<":">")}function Pf(i){if(typeof i.orderId=="string"&&i.orderId)return i.orderId;try{const e=new URL(i.url,window.location.origin),t=e.searchParams.get("orderId")||e.searchParams.get("order_id");if(t)return t;if(e.hash&&e.hash.length>1){const r=new URLSearchParams(e.hash.replace(/^#/,"")),o=r.get("orderId")||r.get("order_id");if(o)return o}}catch{}return null}function Of(){return typeof mr().Razorpay=="function"?Promise.resolve():fr||(fr=new Promise((i,e)=>{const t=document.querySelector('script[data-aikaara-razorpay="1"]');if(t){t.addEventListener("load",()=>i()),t.addEventListener("error",()=>e(new Error("checkout.js failed to load")));return}const r=document.createElement("script");r.src=Tf,r.async=!0,r.dataset.aikaaraRazorpay="1",r.onload=()=>i(),r.onerror=()=>{fr=null,e(new Error("checkout.js failed to load"))},document.head.appendChild(r)}),fr)}function Lf(i,e,t,r){if(!i)return Promise.resolve([]);const o=String(t||"GET").toUpperCase()==="POST"?"POST":"GET",n=i.includes("{orderId}")?i.replace("{orderId}",encodeURIComponent(e)):i+(i.includes("?")?"&":"?")+"orderId="+encodeURIComponent(e),s=mr().__aikaara_runtime__??{};return(typeof s.getSessionToken=="function"?s.getSessionToken():typeof s.getChatJwt=="function"?s.getChatJwt():Promise.resolve(null)).then(l=>{const c={Accept:"application/json",...r??{}};l&&(c.Authorization=`Bearer ${l}`);const u={method:o,headers:c,credentials:"omit"};return o==="POST"&&(c["Content-Type"]="application/json",u.body=JSON.stringify({orderId:e})),fetch(n,u)}).then(l=>{if(!l.ok)throw new Error(`preferred-banks ${l.status}`);return l.json()}).then(l=>{const c=l,u=c?.data&&typeof c.data=="object"&&!Array.isArray(c.data)?c.data:null;return(Array.isArray(l)?l:Array.isArray(c?.banks)?c.banks:Array.isArray(c?.data)?c.data:Array.isArray(u?.preferredPaymentBank)?u.preferredPaymentBank:Array.isArray(u?.banks)?u.banks:[]).map(h=>{if(typeof h=="string")return h;if(h&&typeof h=="object"){const g=h;return g.code||g.bankCode||g.bank_code||null}return null}).filter(h=>!!h)})}async function Mf(i,e){const t=String(e.method||"GET").toUpperCase()==="POST"?"POST":"GET",r=e.paymentLinkUrl,o=r.includes("{orderId}")?r.replace("{orderId}",encodeURIComponent(i)):r+(r.includes("?")?"&":"?")+"orderId="+encodeURIComponent(i),n=mr().__aikaara_runtime__??{},s=typeof n.getSessionToken=="function"?await n.getSessionToken():typeof n.getChatJwt=="function"?await n.getChatJwt():null,a={Accept:"application/json",...e.headers??{}};s&&(a.Authorization=`Bearer ${s}`);const l={method:t,headers:a,credentials:"omit"};t==="POST"&&(a["Content-Type"]="application/json",l.body=JSON.stringify({orderId:i}));const c=await fetch(o,l);if(!c.ok)throw new Error(`partner-payment-link ${c.status}`);const d=(await c.json())?.data;return!d||typeof d.vendorPaymentLink!="string"?null:{vendorPaymentLink:d.vendorPaymentLink,paymentStatus:d.paymentStatus??""}}function Nf(i){const r=window.screenX+Math.round((window.outerWidth-520)/2),o=window.screenY+Math.round((window.outerHeight-680)/2);return window.open(i,"taxbuddy_payment",`width=520,height=680,left=${r},top=${o},scrollbars=yes,resizable=yes`)}function Rf(i,e,t){let r=!1;function o(){clearInterval(a),window.removeEventListener("message",s)}function n(l){r||(r=!0,o(),l())}function s(l){if(e&&l.origin!==e)return;const c=l.data;if(!(!c||typeof c!="object")){if(c.type==="payment-completed"&&c.success===!0){n(()=>t.onSuccess());return}c.type==="payment-error"&&c.success===!1&&n(()=>t.onError(c.error??"Payment failed"))}}const a=setInterval(()=>{i.closed&&n(()=>t.onClose())},500);window.addEventListener("message",s)}function er(i){try{const e=document.querySelector("aikaara-error-banner");if(e&&typeof e.show=="function"){e.show(i);return}}catch{}console.warn("[payment_link]",i)}function jf(i,e){if(!i)return;let t=document.querySelector("aikaara-link-modal");t||(t=document.createElement("aikaara-link-modal"),document.body.appendChild(t)),typeof t.show=="function"?t.show(i,e):window.open(i,"_blank","noopener,noreferrer")}function Df(){typeof customElements>"u"||customElements.get("aikaara-template-payment-link")||customElements.define("aikaara-template-payment-link",Cc)}const $f=Object.freeze(Object.defineProperty({__proto__:null,AikaaraPaymentLink:Cc,registerAikaaraPaymentLink:Df},Symbol.toStringTag,{value:"Module"}));class Pc extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
1600
1933
|
<style>
|
|
1601
1934
|
:host { display: block; margin-top: 8px; }
|
|
1602
1935
|
button {
|
|
@@ -1617,7 +1950,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
1617
1950
|
button[disabled] { opacity: 0.5; cursor: not-allowed; }
|
|
1618
1951
|
</style>
|
|
1619
1952
|
<button type="button" ${e?"":"disabled"}>
|
|
1620
|
-
${
|
|
1953
|
+
${Uf(e?.name??"Open")}
|
|
1621
1954
|
<span aria-hidden="true">↗</span>
|
|
1622
1955
|
</button>
|
|
1623
|
-
`,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:
|
|
1956
|
+
`,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,openInPopup:o,orderId:n,extra:s,messageId:a}=this.payload,l=o?"popup":r?"tab":"modal",c=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:n,openedIn:l,extra:s,messageId:a},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(c))if(o)Zl(e);else if(r)window.open(e,"_blank","noopener,noreferrer");else{const d=Bf();requestAnimationFrame(()=>d?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:n,openedIn:l,...s??{}},...a?{message_id:a}:{}}},bubbles:!0,composed:!0}))}}function Uf(i){return i.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Bf(){if(typeof document>"u")return null;let i=document.querySelector("aikaara-link-modal");if(!i){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),i=e}return i}function Ff(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",Pc)}const qf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:Pc,registerAikaaraLinkButton:Ff},Symbol.toStringTag,{value:"Module"}));return Me.ActionCableClient=hn,Me.AikaaraChatBubble=Jl,Me.AikaaraChatClient=$l,Me.AikaaraChatHeader=Ql,Me.AikaaraChatInput=oc,Me.AikaaraChatWidget=Yl,Me.AikaaraErrorBanner=lc,Me.AikaaraMessageBubble=nc,Me.AikaaraMessageList=ec,Me.AikaaraStreamingMessage=ac,Me.AikaaraTypingIndicator=sc,Me.ApiClient=Jo,Me.ChannelSubscription=Vo,Me.ConnectionManager=Yo,Me.ConversationManager=rs,Me.EventEmitter=kr,Me.FormBridge=uh,Me.MessageStore=Qo,Me.SessionAuthAdapter=bc,Me.SsoExchangeAdapter=vc,Me.TiledeskTransport=Ml,Me.TokenDiscoveryError=Ze,Me.TokenDiscoveryReader=kc,Me.clearPersistedConversationId=_f,Me.collectSsoCredentials=yc,Me.createFetchUploadAdapter=Co,Me.createPresigned3StepUploadAdapter=Bl,Me.createTiledeskHistoryAdapter=Fl,Me.discoverToken=wc,Me.extractTiledeskFileEnvelope=jl,Me.inferTiledeskRole=Rl,Me.isTiledeskSelfEcho=Nl,Me.mount=Af,Me.mountFromSlug=Tc,Me.mountTenantWidget=Ic,Me.parseTiledeskTemplate=Io,Me.registerComponents=Fo,Me.runMethodSelectPreflight=xf,Me.unmount=If,Object.defineProperty(Me,Symbol.toStringTag,{value:"Module"}),Me})({});
|