@aikaara/chat-sdk 1.5.28 → 1.5.30
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-v4bie0j6.mjs → AikaaraLinkButton-DJYY1qZX.mjs} +1 -1
- package/dist/{AikaaraLinkButton-DbppaZG0.cjs → AikaaraLinkButton-DRYE4ZFn.cjs} +1 -1
- package/dist/{MountTenant-DJFhZwnE.mjs → MountTenant-BAwzMvJH.mjs} +3240 -3207
- package/dist/MountTenant-BVgARrQ4.cjs +1940 -0
- package/dist/cdn/aikaara-chat.iife.js +83 -83
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
- package/dist/MountTenant-VbDtm4gc.cjs +0 -1940
|
@@ -1,1940 +0,0 @@
|
|
|
1
|
-
"use strict";class pa{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 wn{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 pa(t,i=>{this.send({command:"message",identifier:t,data:JSON.stringify(i)})});return this.subscriptions.set(t,r),this.send({command:"subscribe",identifier:t}),r}subscribeAsync(e){const t=this.subscribe(e),r=t.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(r,{resolve:()=>i(t),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(r)&&(this.pendingSubscriptions.delete(r),n(new Error(`Subscription timeout for ${r}`)))},1e4)})}unsubscribe(e){this.send({command:"unsubscribe",identifier:e}),this.subscriptions.delete(e)}perform(e,t,r={}){this.send({command:"message",identifier:e,data:JSON.stringify({action:t,...r})})}get isConnected(){return this.ws?.readyState===WebSocket.OPEN}send(e){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}handleMessage(e){let t;try{t=JSON.parse(e.data)}catch{return}switch(t.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyConnected();const n=this.pendingSubscriptions.get(r);n&&(n.resolve(),this.pendingSubscriptions.delete(r));break}case"reject_subscription":{const r=t.identifier;this.subscriptions.get(r)?._notifyRejected(),this.subscriptions.delete(r);const n=this.pendingSubscriptions.get(r);n&&(n.reject(new Error(`Subscription rejected: ${r}`)),this.pendingSubscriptions.delete(r));break}case"disconnect":this.subscriptions.forEach(r=>r._notifyDisconnected());break;default:{t.identifier&&t.message!==void 0&&this.subscriptions.get(t.identifier)?._notifyReceived(t.message);break}}}}class xo{handlers=new Map;on(e,t){return this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),()=>this.off(e,t)}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){this.handlers.get(e)?.forEach(r=>{try{r(t)}catch(i){console.error(`Error in event handler for "${e}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const Zc=1e3,eu=10,tu=400,ru=600,qo="#6366f1",nu=12,iu="system-ui, -apple-system, sans-serif",Ho="Type a message...",ou="bottom-right",su="light",au={x:20,y:20},ln="aikaara_conversation_id";class ma extends xo{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 wn(t)}async connect(){const e=this.reconnectAttempt>0;this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0,e&&this.emit("reconnected",void 0)}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,t){const r=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(r,"send_message",{content:t})}sendUserEvent(e,t,r,i){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_user_event",{event_key:t,...r&&{value:r},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??eu;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const r=(this.config.reconnectInterval??Zc)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client.disconnect(),this.client=new wn(i),await this.connect()}catch{}},r)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,t){if(this.config.wsUrl){const i=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${i}token=${t}`}return`${e.replace(/^http/,"ws")}/cable?token=${t}`}}class ga{baseUrl;apiKey;authToken;userToken;refreshHook=null;constructor(e,t,r,i){this.baseUrl=e,this.userToken=t,this.apiKey=r,this.authToken=i}setAuthRefreshHook(e){this.refreshHook=e}getAuthToken(){return this.authToken}setAuthToken(e){this.authToken=e}async createConversation(e){const t={conversation:{...e.extUid&&{ext_uid:e.extUid},...e.systemPromptId&&{system_prompt_id:e.systemPromptId},...e.channel&&{channel:e.channel},...e.title&&{title:e.title}}};return this.request("POST","/api/v1/conversations",t)}async updateContext(e,t){const r=this.authToken?`/dashboard/sidekick_conversations/${e}`:`/api/v1/conversations/${e}`;await this.request("PATCH",r,t)}async getMessages(e){return(await this.request("GET",`/api/v1/conversations/${e}/messages`)).map(this.mapMessage)}mapMessage(e){return{id:String(e.id),conversationId:String(e.conversation_id),role:e.role,content:e.content||"",toolCalls:e.tool_calls?.map(t=>({id:t.id,type:t.type,function:t.function})),toolCallResults:e.tool_call_results,tokensInput:e.tokens_input,tokensOutput:e.tokens_output,metadata:e.metadata,createdAt:e.created_at,status:"complete"}}async request(e,t,r){const i=`${this.baseUrl}${t}`;let n=await this.fetchWithHeaders(i,e,r);if(n.status===401&&this.refreshHook){let a=null;try{a=await this.refreshHook()}catch(l){console.warn("[aikaara-chat-sdk] auth refresh hook threw",l)}a&&(this.authToken=a,n=await this.fetchWithHeaders(i,e,r))}if(!n.ok){const a=await n.text();let l;try{const c=JSON.parse(a);l=c.error||c.message||a}catch{l=a}throw new Error(`API error ${n.status}: ${l}`)}const s=await n.json();if(s&&typeof s=="object"&&"success"in s){if(!s.success)throw new Error(`API error: ${s.message||"Request failed"}`);return s.data}return s}async fetchWithHeaders(e,t,r){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey),this.authToken&&(i.Authorization=`Bearer ${this.authToken}`);const n={method:t,headers:i};return r&&(n.body=JSON.stringify(r)),fetch(e,n)}}class ba{_messages=[];optimisticCounter=0;get messages(){return[...this._messages]}addOptimistic(e,t,r){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:r,role:e,content:t,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}reconcileOptimistic(e,t=3e4){const r=this._messages.findLast(i=>i.status==="sending"&&i.role===e.role&&i.content===e.content&&i.conversationId===e.conversationId&&Date.now()-new Date(i.createdAt).getTime()<t);return r?(r.status=e.status??"sent",r.externalId=e.externalId??e.id,e.template&&(r.template=e.template),e.attachments&&(r.attachments=e.attachments),e.metadata&&(r.metadata={...r.metadata??{},...e.metadata}),r):null}upsertRemoteMessage(e){const t=this.reconcileOptimistic(e);if(t)return{message:t,deduped:!0};const r=e.externalId?this._messages.find(n=>n.externalId&&n.externalId===e.externalId):void 0;if(r)return Object.assign(r,e,{id:r.id}),{message:r,deduped:!0};const i=Wo(this._messages,e);return i?(Object.assign(i,e,{id:i.id}),{message:i,deduped:!0}):(this._messages.push(e),{message:e,deduped:!1})}updateMessageStatus(e,t){const r=this._messages.find(i=>i.externalId===e||i.id===e);return r&&(r.status=t),r}confirmOptimistic(e){const t=this._messages.find(r=>r.id===e);t&&(t.status="sent")}addStreamingMessage(e){const t={id:`streaming_${Date.now()}`,conversationId:e,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(t),t}updateStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content=e)}appendToStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");t&&(t.content+=e)}get streamingContent(){return this._messages.findLast(t=>t.status==="streaming")?.content||""}finalizeStreaming(e){const t=this._messages.findLast(r=>r.status==="streaming");return t&&(t.status="complete",e&&(t.tokensInput=e.tokensInput,t.tokensOutput=e.tokensOutput)),t}addMessage(e){this._messages.push(e)}setMessages(e){const t=[];for(const r of e){const i=Wo(t,r);if(i){const n=Yr(i),s=Yr(r);!n&&s&&Object.assign(i,r,{id:i.id});continue}t.push({...r})}this._messages=t}clear(){this._messages=[]}}function Wo(o,e,t=15e3){const r=e.attachments&&e.attachments[0],i=(e.metadata??{}).attributes;if(!(!!r||!!(i&&i.fileMessage)))return null;const s=Yr(e),a=zo(e),l=Vo(e);if(!s&&!a&&!l)return null;const c=new Date(e.createdAt).getTime();for(let u=o.length-1;u>=0;u--){const d=o[u],p=d.attachments&&d.attachments[0],g=(d.metadata??{}).attributes;if(!(!!p||!!(g&&g.fileMessage)))continue;const b=(d.content||"").trim().toLowerCase();if(b==="file_uploaded"||b==="file_upload"||Math.abs(c-new Date(d.createdAt).getTime())>t)continue;const y=Yr(d);if(s&&y&&s===y)return d;const w=zo(d);if(a&&w&&a===w)return d;const m=Vo(d);if(l&&m&&l===m)return d}return null}function zo(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileUrl=="string")return e.fileUrl;const t=ya(o);if(t)return t}function Vo(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.fileName=="string")return e.fileName;const t=(o.metadata??{}).attributes;if(t&&typeof t.fileName=="string")return t.fileName;const n=o.template?.payload?.elements?.[0]?.description;if(typeof n=="string"&&n)return n}function Yr(o){const e=o.attachments&&o.attachments[0];if(e&&typeof e.cloudFileId=="string")return e.cloudFileId;const t=(o.metadata??{}).attributes;if(t&&typeof t.cloudFileId=="string")return t.cloudFileId;const r=ya(o);if(r){const i=/[?&]cloudFileId=([^&]+)/.exec(r);if(i)return decodeURIComponent(i[1])}}function ya(o){const e=o.template;if(e?.templateId!=="7")return;const r=e.payload?.elements?.[0]?.action?.url;return typeof r=="string"?r:void 0}class va{_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 _o=Object.defineProperty,lu=Object.getOwnPropertyDescriptor,cu=Object.getOwnPropertyNames,uu=Object.prototype.hasOwnProperty,Qe=(o,e)=>()=>(o&&(e=o(o=0)),e),me=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Qt=(o,e)=>{for(var t in e)_o(o,t,{get:e[t],enumerable:!0})},du=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of cu(e))!uu.call(o,i)&&i!==t&&_o(o,i,{get:()=>e[i],enumerable:!(r=lu(e,i))||r.enumerable});return o},Re=o=>du(_o({},"__esModule",{value:!0}),o),le=Qe(()=>{}),je={};Qt(je,{_debugEnd:()=>ei,_debugProcess:()=>Zn,_events:()=>mi,_eventsCount:()=>gi,_exiting:()=>Un,_fatalExceptions:()=>Jn,_getActiveHandles:()=>Aa,_getActiveRequests:()=>Ea,_kill:()=>qn,_linkedBinding:()=>_a,_maxListeners:()=>pi,_preload_modules:()=>hi,_rawDebug:()=>jn,_startProfilerIdleNotifier:()=>ti,_stopProfilerIdleNotifier:()=>ri,_tickCallback:()=>Xn,abort:()=>si,addListener:()=>bi,allowedNodeEnvironmentFlags:()=>Gn,arch:()=>xn,argv:()=>En,argv0:()=>di,assert:()=>Ia,binding:()=>Pn,browser:()=>Rn,chdir:()=>Mn,config:()=>Bn,cpuUsage:()=>ar,cwd:()=>Ln,debugPort:()=>ui,default:()=>Eo,dlopen:()=>Sa,domain:()=>$n,emit:()=>xi,emitWarning:()=>Cn,env:()=>Sn,execArgv:()=>An,execPath:()=>ci,exit:()=>Vn,features:()=>Yn,hasUncaughtExceptionCaptureCallback:()=>Ta,hrtime:()=>Sr,kill:()=>zn,listeners:()=>Pa,memoryUsage:()=>Wn,moduleLoadList:()=>Dn,nextTick:()=>ka,off:()=>vi,on:()=>pt,once:()=>yi,openStdin:()=>Kn,pid:()=>ai,platform:()=>_n,ppid:()=>li,prependListener:()=>_i,prependOnceListener:()=>Si,reallyExit:()=>Fn,release:()=>Nn,removeAllListeners:()=>ki,removeListener:()=>wi,resourceUsage:()=>Hn,setSourceMapsEnabled:()=>fi,setUncaughtExceptionCaptureCallback:()=>Qn,stderr:()=>ii,stdin:()=>oi,stdout:()=>ni,title:()=>kn,umask:()=>On,uptime:()=>Ca,version:()=>In,versions:()=>Tn});function So(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function hu(){!Dt||!Rt||(Dt=!1,Rt.length?dt=Rt.concat(dt):hr=-1,dt.length&&wa())}function wa(){if(!Dt){var o=setTimeout(hu,0);Dt=!0;for(var e=dt.length;e;){for(Rt=dt,dt=[];++hr<e;)Rt&&Rt[hr].run();hr=-1,e=dt.length}Rt=null,Dt=!1,clearTimeout(o)}}function ka(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];dt.push(new xa(o,e)),dt.length===1&&!Dt&&setTimeout(wa,0)}function xa(o,e){this.fun=o,this.array=e}function We(){}function _a(o){So("_linkedBinding")}function Sa(o){So("dlopen")}function Ea(){return[]}function Aa(){return[]}function Ia(o,e){if(!o)throw new Error(e||"assertion error")}function Ta(){return!1}function Ca(){return gt.now()/1e3}function Sr(o){var e=Math.floor((Date.now()-gt.now())*.001),t=gt.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return o&&(r=r-o[0],i=i-o[1],i<0&&(r--,i+=Er)),[r,i]}function pt(){return Eo}function Pa(o){return[]}var dt,Dt,Rt,hr,kn,xn,_n,Sn,En,An,In,Tn,Cn,Pn,On,Ln,Mn,Nn,Rn,jn,Dn,$n,Un,Bn,Fn,qn,ar,Hn,Wn,zn,Vn,Kn,Gn,Yn,Jn,Qn,Xn,Zn,ei,ti,ri,ni,ii,oi,si,ai,li,ci,ui,di,hi,fi,gt,cn,Er,pi,mi,gi,bi,yi,vi,wi,ki,xi,_i,Si,Eo,fu=Qe(()=>{le(),ue(),ce(),dt=[],Dt=!1,hr=-1,xa.prototype.run=function(){this.fun.apply(null,this.array)},kn="browser",xn="x64",_n="browser",Sn={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},En=["/usr/bin/node"],An=[],In="v16.8.0",Tn={},Cn=function(o,e){console.warn((e?e+": ":"")+o)},Pn=function(o){So("binding")},On=function(o){return 0},Ln=function(){return"/"},Mn=function(o){},Nn={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},Rn=!0,jn=We,Dn=[],$n={},Un=!1,Bn={},Fn=We,qn=We,ar=function(){return{}},Hn=ar,Wn=ar,zn=We,Vn=We,Kn=We,Gn={},Yn={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Jn=We,Qn=We,Xn=We,Zn=We,ei=We,ti=We,ri=We,ni=void 0,ii=void 0,oi=void 0,si=We,ai=2,li=1,ci="/bin/usr/node",ui=9229,di="node",hi=[],fi=We,gt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},gt.now===void 0&&(cn=Date.now(),gt.timing&>.timing.navigationStart&&(cn=gt.timing.navigationStart),gt.now=()=>Date.now()-cn),Er=1e9,Sr.bigint=function(o){var e=Sr(o);return typeof BigInt>"u"?e[0]*Er+e[1]:BigInt(e[0]*Er)+BigInt(e[1])},pi=10,mi={},gi=0,bi=pt,yi=pt,vi=pt,wi=pt,ki=pt,xi=We,_i=pt,Si=pt,Eo={version:In,versions:Tn,arch:xn,platform:_n,browser:Rn,release:Nn,_rawDebug:jn,moduleLoadList:Dn,binding:Pn,_linkedBinding:_a,_events:mi,_eventsCount:gi,_maxListeners:pi,on:pt,addListener:bi,once:yi,off:vi,removeListener:wi,removeAllListeners:ki,emit:xi,prependListener:_i,prependOnceListener:Si,listeners:Pa,domain:$n,_exiting:Un,config:Bn,dlopen:Sa,uptime:Ca,_getActiveRequests:Ea,_getActiveHandles:Aa,reallyExit:Fn,_kill:qn,cpuUsage:ar,resourceUsage:Hn,memoryUsage:Wn,kill:zn,exit:Vn,openStdin:Kn,allowedNodeEnvironmentFlags:Gn,assert:Ia,features:Yn,_fatalExceptions:Jn,setUncaughtExceptionCaptureCallback:Qn,hasUncaughtExceptionCaptureCallback:Ta,emitWarning:Cn,nextTick:ka,_tickCallback:Xn,_debugProcess:Zn,_debugEnd:ei,_startProfilerIdleNotifier:ti,_stopProfilerIdleNotifier:ri,stdout:ni,stdin:oi,stderr:ii,abort:si,umask:On,chdir:Mn,cwd:Ln,env:Sn,title:kn,argv:En,execArgv:An,pid:ai,ppid:li,execPath:ci,debugPort:ui,hrtime:Sr,argv0:di,_preload_modules:hi,setSourceMapsEnabled:fi}}),ce=Qe(()=>{fu()});function pu(){if(Ei)return Wt;Ei=!0,Wt.byteLength=a,Wt.toByteArray=c,Wt.fromByteArray=p;for(var o=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,n=r.length;i<n;++i)o[i]=r[i],e[r.charCodeAt(i)]=i;e[45]=62,e[95]=63;function s(g){var h=g.length;if(h%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=g.indexOf("=");b===-1&&(b=h);var y=b===h?0:4-b%4;return[b,y]}function a(g){var h=s(g),b=h[0],y=h[1];return(b+y)*3/4-y}function l(g,h,b){return(h+b)*3/4-b}function c(g){var h,b=s(g),y=b[0],w=b[1],m=new t(l(g,y,w)),k=0,_=w>0?y-4:y,v;for(v=0;v<_;v+=4)h=e[g.charCodeAt(v)]<<18|e[g.charCodeAt(v+1)]<<12|e[g.charCodeAt(v+2)]<<6|e[g.charCodeAt(v+3)],m[k++]=h>>16&255,m[k++]=h>>8&255,m[k++]=h&255;return w===2&&(h=e[g.charCodeAt(v)]<<2|e[g.charCodeAt(v+1)]>>4,m[k++]=h&255),w===1&&(h=e[g.charCodeAt(v)]<<10|e[g.charCodeAt(v+1)]<<4|e[g.charCodeAt(v+2)]>>2,m[k++]=h>>8&255,m[k++]=h&255),m}function u(g){return o[g>>18&63]+o[g>>12&63]+o[g>>6&63]+o[g&63]}function d(g,h,b){for(var y,w=[],m=h;m<b;m+=3)y=(g[m]<<16&16711680)+(g[m+1]<<8&65280)+(g[m+2]&255),w.push(u(y));return w.join("")}function p(g){for(var h,b=g.length,y=b%3,w=[],m=16383,k=0,_=b-y;k<_;k+=m)w.push(d(g,k,k+m>_?_:k+m));return y===1?(h=g[b-1],w.push(o[h>>2]+o[h<<4&63]+"==")):y===2&&(h=(g[b-2]<<8)+g[b-1],w.push(o[h>>10]+o[h>>4&63]+o[h<<2&63]+"=")),w.join("")}return Wt}function mu(){return Ai?lr:(Ai=!0,lr.read=function(o,e,t,r,i){var n,s,a=i*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=t?i-1:0,p=t?-1:1,g=o[e+d];for(d+=p,n=g&(1<<-u)-1,g>>=-u,u+=a;u>0;n=n*256+o[e+d],d+=p,u-=8);for(s=n&(1<<-u)-1,n>>=-u,u+=r;u>0;s=s*256+o[e+d],d+=p,u-=8);if(n===0)n=1-c;else{if(n===l)return s?NaN:(g?-1:1)*(1/0);s=s+Math.pow(2,r),n=n-c}return(g?-1:1)*s*Math.pow(2,n-r)},lr.write=function(o,e,t,r,i,n){var s,a,l,c=n*8-i-1,u=(1<<c)-1,d=u>>1,p=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=r?0:n-1,h=r?1:-1,b=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=p/l:e+=p*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,i),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),s=0));i>=8;o[t+g]=a&255,g+=h,a/=256,i-=8);for(s=s<<i|a,c+=i;c>0;o[t+g]=s&255,g+=h,s/=256,c-=8);o[t+g-h]|=b*128},lr)}function gu(){if(Ii)return It;Ii=!0;let o=pu(),e=mu(),t=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;It.Buffer=s,It.SlowBuffer=w,It.INSPECT_MAX_BYTES=50;let r=2147483647;It.kMaxLength=r,s.TYPED_ARRAY_SUPPORT=i(),!s.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{let f=new Uint8Array(1),x={foo:function(){return 42}};return Object.setPrototypeOf(x,Uint8Array.prototype),Object.setPrototypeOf(f,x),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 x=new Uint8Array(f);return Object.setPrototypeOf(x,s.prototype),x}function s(f,x,A){if(typeof f=="number"){if(typeof x=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return u(f)}return a(f,x,A)}s.poolSize=8192;function a(f,x,A){if(typeof f=="string")return d(f,x);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 h(f,x,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,x,A);let ee=b(f);if(ee)return ee;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof f[Symbol.toPrimitive]=="function")return s.from(f[Symbol.toPrimitive]("string"),x,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,x,A){return a(f,x,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,x,A){return l(f),f<=0?n(f):x!==void 0?typeof A=="string"?n(f).fill(x,A):n(f).fill(x):n(f)}s.alloc=function(f,x,A){return c(f,x,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,x){if((typeof x!="string"||x==="")&&(x="utf8"),!s.isEncoding(x))throw new TypeError("Unknown encoding: "+x);let A=m(f,x)|0,B=n(A),ee=B.write(f,x);return ee!==A&&(B=B.slice(0,ee)),B}function p(f){let x=f.length<0?0:y(f.length)|0,A=n(x);for(let B=0;B<x;B+=1)A[B]=f[B]&255;return A}function g(f){if(H(f,Uint8Array)){let x=new Uint8Array(f);return h(x.buffer,x.byteOffset,x.byteLength)}return p(f)}function h(f,x,A){if(x<0||f.byteLength<x)throw new RangeError('"offset" is outside of buffer bounds');if(f.byteLength<x+(A||0))throw new RangeError('"length" is outside of buffer bounds');let B;return x===void 0&&A===void 0?B=new Uint8Array(f):A===void 0?B=new Uint8Array(f,x):B=new Uint8Array(f,x,A),Object.setPrototypeOf(B,s.prototype),B}function b(f){if(s.isBuffer(f)){let x=y(f.length)|0,A=n(x);return A.length===0||f.copy(A,0,0,x),A}if(f.length!==void 0)return typeof f.length!="number"||ge(f.length)?n(0):p(f);if(f.type==="Buffer"&&Array.isArray(f.data))return p(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,x){if(H(f,Uint8Array)&&(f=s.from(f,f.offset,f.byteLength)),H(x,Uint8Array)&&(x=s.from(x,x.offset,x.byteLength)),!s.isBuffer(f)||!s.isBuffer(x))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(f===x)return 0;let A=f.length,B=x.length;for(let ee=0,de=Math.min(A,B);ee<de;++ee)if(f[ee]!==x[ee]){A=f[ee],B=x[ee];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,x){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(x===void 0)for(x=0,A=0;A<f.length;++A)x+=f[A].length;let B=s.allocUnsafe(x),ee=0;for(A=0;A<f.length;++A){let de=f[A];if(H(de,Uint8Array))ee+de.length>B.length?(s.isBuffer(de)||(de=s.from(de)),de.copy(B,ee)):Uint8Array.prototype.set.call(B,de,ee);else if(s.isBuffer(de))de.copy(B,ee);else throw new TypeError('"list" argument must be an Array of Buffers');ee+=de.length}return B};function m(f,x){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 ee=!1;for(;;)switch(x){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 fe(f).length;default:if(ee)return B?-1:q(f).length;x=(""+x).toLowerCase(),ee=!0}}s.byteLength=m;function k(f,x,A){let B=!1;if((x===void 0||x<0)&&(x=0),x>this.length||((A===void 0||A>this.length)&&(A=this.length),A<=0)||(A>>>=0,x>>>=0,A<=x))return"";for(f||(f="utf8");;)switch(f){case"hex":return W(this,x,A);case"utf8":case"utf-8":return F(this,x,A);case"ascii":return X(this,x,A);case"latin1":case"binary":return z(this,x,A);case"base64":return T(this,x,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ne(this,x,A);default:if(B)throw new TypeError("Unknown encoding: "+f);f=(f+"").toLowerCase(),B=!0}}s.prototype._isBuffer=!0;function _(f,x,A){let B=f[x];f[x]=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 x=0;x<f;x+=2)_(this,x,x+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 x=0;x<f;x+=4)_(this,x,x+3),_(this,x+1,x+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 x=0;x<f;x+=8)_(this,x,x+7),_(this,x+1,x+6),_(this,x+2,x+5),_(this,x+3,x+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="",x=It.INSPECT_MAX_BYTES;return f=this.toString("hex",0,x).replace(/(.{2})/g,"$1 ").trim(),this.length>x&&(f+=" ... "),"<Buffer "+f+">"},t&&(s.prototype[t]=s.prototype.inspect),s.prototype.compare=function(f,x,A,B,ee){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(x===void 0&&(x=0),A===void 0&&(A=f?f.length:0),B===void 0&&(B=0),ee===void 0&&(ee=this.length),x<0||A>f.length||B<0||ee>this.length)throw new RangeError("out of range index");if(B>=ee&&x>=A)return 0;if(B>=ee)return-1;if(x>=A)return 1;if(x>>>=0,A>>>=0,B>>>=0,ee>>>=0,this===f)return 0;let de=ee-B,xe=A-x,K=Math.min(de,xe),oe=this.slice(B,ee),Ie=f.slice(x,A);for(let Te=0;Te<K;++Te)if(oe[Te]!==Ie[Te]){de=oe[Te],xe=Ie[Te];break}return de<xe?-1:xe<de?1:0};function v(f,x,A,B,ee){if(f.length===0)return-1;if(typeof A=="string"?(B=A,A=0):A>2147483647?A=2147483647:A<-2147483648&&(A=-2147483648),A=+A,ge(A)&&(A=ee?0:f.length-1),A<0&&(A=f.length+A),A>=f.length){if(ee)return-1;A=f.length-1}else if(A<0)if(ee)A=0;else return-1;if(typeof x=="string"&&(x=s.from(x,B)),s.isBuffer(x))return x.length===0?-1:E(f,x,A,B,ee);if(typeof x=="number")return x=x&255,typeof Uint8Array.prototype.indexOf=="function"?ee?Uint8Array.prototype.indexOf.call(f,x,A):Uint8Array.prototype.lastIndexOf.call(f,x,A):E(f,[x],A,B,ee);throw new TypeError("val must be string, number or Buffer")}function E(f,x,A,B,ee){let de=1,xe=f.length,K=x.length;if(B!==void 0&&(B=String(B).toLowerCase(),B==="ucs2"||B==="ucs-2"||B==="utf16le"||B==="utf-16le")){if(f.length<2||x.length<2)return-1;de=2,xe/=2,K/=2,A/=2}function oe(Te,Oe){return de===1?Te[Oe]:Te.readUInt16BE(Oe*de)}let Ie;if(ee){let Te=-1;for(Ie=A;Ie<xe;Ie++)if(oe(f,Ie)===oe(x,Te===-1?0:Ie-Te)){if(Te===-1&&(Te=Ie),Ie-Te+1===K)return Te*de}else Te!==-1&&(Ie-=Ie-Te),Te=-1}else for(A+K>xe&&(A=xe-K),Ie=A;Ie>=0;Ie--){let Te=!0;for(let Oe=0;Oe<K;Oe++)if(oe(f,Ie+Oe)!==oe(x,Oe)){Te=!1;break}if(Te)return Ie}return-1}s.prototype.includes=function(f,x,A){return this.indexOf(f,x,A)!==-1},s.prototype.indexOf=function(f,x,A){return v(this,f,x,A,!0)},s.prototype.lastIndexOf=function(f,x,A){return v(this,f,x,A,!1)};function S(f,x,A,B){A=Number(A)||0;let ee=f.length-A;B?(B=Number(B),B>ee&&(B=ee)):B=ee;let de=x.length;B>de/2&&(B=de/2);let xe;for(xe=0;xe<B;++xe){let K=parseInt(x.substr(xe*2,2),16);if(ge(K))return xe;f[A+xe]=K}return xe}function I(f,x,A,B){return ye(q(x,f.length-A),f,A,B)}function P(f,x,A,B){return ye(re(x),f,A,B)}function O(f,x,A,B){return ye(fe(x),f,A,B)}function j(f,x,A,B){return ye(he(x,f.length-A),f,A,B)}s.prototype.write=function(f,x,A,B){if(x===void 0)B="utf8",A=this.length,x=0;else if(A===void 0&&typeof x=="string")B=x,A=this.length,x=0;else if(isFinite(x))x=x>>>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 ee=this.length-x;if((A===void 0||A>ee)&&(A=ee),f.length>0&&(A<0||x<0)||x>this.length)throw new RangeError("Attempt to write outside buffer bounds");B||(B="utf8");let de=!1;for(;;)switch(B){case"hex":return S(this,f,x,A);case"utf8":case"utf-8":return I(this,f,x,A);case"ascii":case"latin1":case"binary":return P(this,f,x,A);case"base64":return O(this,f,x,A);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,f,x,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,x,A){return x===0&&A===f.length?o.fromByteArray(f):o.fromByteArray(f.slice(x,A))}function F(f,x,A){A=Math.min(f.length,A);let B=[],ee=x;for(;ee<A;){let de=f[ee],xe=null,K=de>239?4:de>223?3:de>191?2:1;if(ee+K<=A){let oe,Ie,Te,Oe;switch(K){case 1:de<128&&(xe=de);break;case 2:oe=f[ee+1],(oe&192)===128&&(Oe=(de&31)<<6|oe&63,Oe>127&&(xe=Oe));break;case 3:oe=f[ee+1],Ie=f[ee+2],(oe&192)===128&&(Ie&192)===128&&(Oe=(de&15)<<12|(oe&63)<<6|Ie&63,Oe>2047&&(Oe<55296||Oe>57343)&&(xe=Oe));break;case 4:oe=f[ee+1],Ie=f[ee+2],Te=f[ee+3],(oe&192)===128&&(Ie&192)===128&&(Te&192)===128&&(Oe=(de&15)<<18|(oe&63)<<12|(Ie&63)<<6|Te&63,Oe>65535&&Oe<1114112&&(xe=Oe))}}xe===null?(xe=65533,K=1):xe>65535&&(xe-=65536,B.push(xe>>>10&1023|55296),xe=56320|xe&1023),B.push(xe),ee+=K}return U(B)}let $=4096;function U(f){let x=f.length;if(x<=$)return String.fromCharCode.apply(String,f);let A="",B=0;for(;B<x;)A+=String.fromCharCode.apply(String,f.slice(B,B+=$));return A}function X(f,x,A){let B="";A=Math.min(f.length,A);for(let ee=x;ee<A;++ee)B+=String.fromCharCode(f[ee]&127);return B}function z(f,x,A){let B="";A=Math.min(f.length,A);for(let ee=x;ee<A;++ee)B+=String.fromCharCode(f[ee]);return B}function W(f,x,A){let B=f.length;(!x||x<0)&&(x=0),(!A||A<0||A>B)&&(A=B);let ee="";for(let de=x;de<A;++de)ee+=we[f[de]];return ee}function ne(f,x,A){let B=f.slice(x,A),ee="";for(let de=0;de<B.length-1;de+=2)ee+=String.fromCharCode(B[de]+B[de+1]*256);return ee}s.prototype.slice=function(f,x){let A=this.length;f=~~f,x=x===void 0?A:~~x,f<0?(f+=A,f<0&&(f=0)):f>A&&(f=A),x<0?(x+=A,x<0&&(x=0)):x>A&&(x=A),x<f&&(x=f);let B=this.subarray(f,x);return Object.setPrototypeOf(B,s.prototype),B};function D(f,x,A){if(f%1!==0||f<0)throw new RangeError("offset is not uint");if(f+x>A)throw new RangeError("Trying to access beyond buffer length")}s.prototype.readUintLE=s.prototype.readUIntLE=function(f,x,A){f=f>>>0,x=x>>>0,A||D(f,x,this.length);let B=this[f],ee=1,de=0;for(;++de<x&&(ee*=256);)B+=this[f+de]*ee;return B},s.prototype.readUintBE=s.prototype.readUIntBE=function(f,x,A){f=f>>>0,x=x>>>0,A||D(f,x,this.length);let B=this[f+--x],ee=1;for(;x>0&&(ee*=256);)B+=this[f+--x]*ee;return B},s.prototype.readUint8=s.prototype.readUInt8=function(f,x){return f=f>>>0,x||D(f,1,this.length),this[f]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(f,x){return f=f>>>0,x||D(f,2,this.length),this[f]|this[f+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(f,x){return f=f>>>0,x||D(f,2,this.length),this[f]<<8|this[f+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(f,x){return f=f>>>0,x||D(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,x){return f=f>>>0,x||D(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,Z(f,"offset");let x=this[f],A=this[f+7];(x===void 0||A===void 0)&&be(f,this.length-8);let B=x+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24,ee=this[++f]+this[++f]*2**8+this[++f]*2**16+A*2**24;return BigInt(B)+(BigInt(ee)<<BigInt(32))}),s.prototype.readBigUInt64BE=ae(function(f){f=f>>>0,Z(f,"offset");let x=this[f],A=this[f+7];(x===void 0||A===void 0)&&be(f,this.length-8);let B=x*2**24+this[++f]*2**16+this[++f]*2**8+this[++f],ee=this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A;return(BigInt(B)<<BigInt(32))+BigInt(ee)}),s.prototype.readIntLE=function(f,x,A){f=f>>>0,x=x>>>0,A||D(f,x,this.length);let B=this[f],ee=1,de=0;for(;++de<x&&(ee*=256);)B+=this[f+de]*ee;return ee*=128,B>=ee&&(B-=Math.pow(2,8*x)),B},s.prototype.readIntBE=function(f,x,A){f=f>>>0,x=x>>>0,A||D(f,x,this.length);let B=x,ee=1,de=this[f+--B];for(;B>0&&(ee*=256);)de+=this[f+--B]*ee;return ee*=128,de>=ee&&(de-=Math.pow(2,8*x)),de},s.prototype.readInt8=function(f,x){return f=f>>>0,x||D(f,1,this.length),this[f]&128?(255-this[f]+1)*-1:this[f]},s.prototype.readInt16LE=function(f,x){f=f>>>0,x||D(f,2,this.length);let A=this[f]|this[f+1]<<8;return A&32768?A|4294901760:A},s.prototype.readInt16BE=function(f,x){f=f>>>0,x||D(f,2,this.length);let A=this[f+1]|this[f]<<8;return A&32768?A|4294901760:A},s.prototype.readInt32LE=function(f,x){return f=f>>>0,x||D(f,4,this.length),this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24},s.prototype.readInt32BE=function(f,x){return f=f>>>0,x||D(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,Z(f,"offset");let x=this[f],A=this[f+7];(x===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(x+this[++f]*2**8+this[++f]*2**16+this[++f]*2**24)}),s.prototype.readBigInt64BE=ae(function(f){f=f>>>0,Z(f,"offset");let x=this[f],A=this[f+7];(x===void 0||A===void 0)&&be(f,this.length-8);let B=(x<<24)+this[++f]*2**16+this[++f]*2**8+this[++f];return(BigInt(B)<<BigInt(32))+BigInt(this[++f]*2**24+this[++f]*2**16+this[++f]*2**8+A)}),s.prototype.readFloatLE=function(f,x){return f=f>>>0,x||D(f,4,this.length),e.read(this,f,!0,23,4)},s.prototype.readFloatBE=function(f,x){return f=f>>>0,x||D(f,4,this.length),e.read(this,f,!1,23,4)},s.prototype.readDoubleLE=function(f,x){return f=f>>>0,x||D(f,8,this.length),e.read(this,f,!0,52,8)},s.prototype.readDoubleBE=function(f,x){return f=f>>>0,x||D(f,8,this.length),e.read(this,f,!1,52,8)};function G(f,x,A,B,ee,de){if(!s.isBuffer(f))throw new TypeError('"buffer" argument must be a Buffer instance');if(x>ee||x<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,x,A,B){if(f=+f,x=x>>>0,A=A>>>0,!B){let xe=Math.pow(2,8*A)-1;G(this,f,x,A,xe,0)}let ee=1,de=0;for(this[x]=f&255;++de<A&&(ee*=256);)this[x+de]=f/ee&255;return x+A},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(f,x,A,B){if(f=+f,x=x>>>0,A=A>>>0,!B){let xe=Math.pow(2,8*A)-1;G(this,f,x,A,xe,0)}let ee=A-1,de=1;for(this[x+ee]=f&255;--ee>=0&&(de*=256);)this[x+ee]=f/de&255;return x+A},s.prototype.writeUint8=s.prototype.writeUInt8=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,1,255,0),this[x]=f&255,x+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,2,65535,0),this[x]=f&255,this[x+1]=f>>>8,x+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,2,65535,0),this[x]=f>>>8,this[x+1]=f&255,x+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,4,4294967295,0),this[x+3]=f>>>24,this[x+2]=f>>>16,this[x+1]=f>>>8,this[x]=f&255,x+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,4,4294967295,0),this[x]=f>>>24,this[x+1]=f>>>16,this[x+2]=f>>>8,this[x+3]=f&255,x+4};function L(f,x,A,B,ee){Q(x,B,ee,f,A,7);let de=Number(x&BigInt(4294967295));f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de,de=de>>8,f[A++]=de;let xe=Number(x>>BigInt(32)&BigInt(4294967295));return f[A++]=xe,xe=xe>>8,f[A++]=xe,xe=xe>>8,f[A++]=xe,xe=xe>>8,f[A++]=xe,A}function Y(f,x,A,B,ee){Q(x,B,ee,f,A,7);let de=Number(x&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 xe=Number(x>>BigInt(32)&BigInt(4294967295));return f[A+3]=xe,xe=xe>>8,f[A+2]=xe,xe=xe>>8,f[A+1]=xe,xe=xe>>8,f[A]=xe,A+8}s.prototype.writeBigUInt64LE=ae(function(f,x=0){return L(this,f,x,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=ae(function(f,x=0){return Y(this,f,x,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(f,x,A,B){if(f=+f,x=x>>>0,!B){let K=Math.pow(2,8*A-1);G(this,f,x,A,K-1,-K)}let ee=0,de=1,xe=0;for(this[x]=f&255;++ee<A&&(de*=256);)f<0&&xe===0&&this[x+ee-1]!==0&&(xe=1),this[x+ee]=(f/de>>0)-xe&255;return x+A},s.prototype.writeIntBE=function(f,x,A,B){if(f=+f,x=x>>>0,!B){let K=Math.pow(2,8*A-1);G(this,f,x,A,K-1,-K)}let ee=A-1,de=1,xe=0;for(this[x+ee]=f&255;--ee>=0&&(de*=256);)f<0&&xe===0&&this[x+ee+1]!==0&&(xe=1),this[x+ee]=(f/de>>0)-xe&255;return x+A},s.prototype.writeInt8=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,1,127,-128),f<0&&(f=255+f+1),this[x]=f&255,x+1},s.prototype.writeInt16LE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,2,32767,-32768),this[x]=f&255,this[x+1]=f>>>8,x+2},s.prototype.writeInt16BE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,2,32767,-32768),this[x]=f>>>8,this[x+1]=f&255,x+2},s.prototype.writeInt32LE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,4,2147483647,-2147483648),this[x]=f&255,this[x+1]=f>>>8,this[x+2]=f>>>16,this[x+3]=f>>>24,x+4},s.prototype.writeInt32BE=function(f,x,A){return f=+f,x=x>>>0,A||G(this,f,x,4,2147483647,-2147483648),f<0&&(f=4294967295+f+1),this[x]=f>>>24,this[x+1]=f>>>16,this[x+2]=f>>>8,this[x+3]=f&255,x+4},s.prototype.writeBigInt64LE=ae(function(f,x=0){return L(this,f,x,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=ae(function(f,x=0){return Y(this,f,x,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function pe(f,x,A,B,ee,de){if(A+B>f.length)throw new RangeError("Index out of range");if(A<0)throw new RangeError("Index out of range")}function te(f,x,A,B,ee){return x=+x,A=A>>>0,ee||pe(f,x,A,4),e.write(f,x,A,B,23,4),A+4}s.prototype.writeFloatLE=function(f,x,A){return te(this,f,x,!0,A)},s.prototype.writeFloatBE=function(f,x,A){return te(this,f,x,!1,A)};function ve(f,x,A,B,ee){return x=+x,A=A>>>0,ee||pe(f,x,A,8),e.write(f,x,A,B,52,8),A+8}s.prototype.writeDoubleLE=function(f,x,A){return ve(this,f,x,!0,A)},s.prototype.writeDoubleBE=function(f,x,A){return ve(this,f,x,!1,A)},s.prototype.copy=function(f,x,A,B){if(!s.isBuffer(f))throw new TypeError("argument should be a Buffer");if(A||(A=0),!B&&B!==0&&(B=this.length),x>=f.length&&(x=f.length),x||(x=0),B>0&&B<A&&(B=A),B===A||f.length===0||this.length===0)return 0;if(x<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-x<B-A&&(B=f.length-x+A);let ee=B-A;return this===f&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(x,A,B):Uint8Array.prototype.set.call(f,this.subarray(A,B),x),ee},s.prototype.fill=function(f,x,A,B){if(typeof f=="string"){if(typeof x=="string"?(B=x,x=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(x<0||this.length<x||this.length<A)throw new RangeError("Out of range index");if(A<=x)return this;x=x>>>0,A=A===void 0?this.length:A>>>0,f||(f=0);let ee;if(typeof f=="number")for(ee=x;ee<A;++ee)this[ee]=f;else{let de=s.isBuffer(f)?f:s.from(f,B),xe=de.length;if(xe===0)throw new TypeError('The value "'+f+'" is invalid for argument "value"');for(ee=0;ee<A-x;++ee)this[ee+x]=de[ee%xe]}return this};let J={};function R(f,x,A){J[f]=class extends A{constructor(){super(),Object.defineProperty(this,"message",{value:x.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}`}}}R("ERR_BUFFER_OUT_OF_BOUNDS",function(f){return f?`${f} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),R("ERR_INVALID_ARG_TYPE",function(f,x){return`The "${f}" argument must be of type number. Received type ${typeof x}`},TypeError),R("ERR_OUT_OF_RANGE",function(f,x,A){let B=`The value of "${f}" is out of range.`,ee=A;return Number.isInteger(A)&&Math.abs(A)>2**32?ee=ie(String(A)):typeof A=="bigint"&&(ee=String(A),(A>BigInt(2)**BigInt(32)||A<-(BigInt(2)**BigInt(32)))&&(ee=ie(ee)),ee+="n"),B+=` It must be ${x}. Received ${ee}`,B},RangeError);function ie(f){let x="",A=f.length,B=f[0]==="-"?1:0;for(;A>=B+4;A-=3)x=`_${f.slice(A-3,A)}${x}`;return`${f.slice(0,A)}${x}`}function V(f,x,A){Z(x,"offset"),(f[x]===void 0||f[x+A]===void 0)&&be(x,f.length-(A+1))}function Q(f,x,A,B,ee,de){if(f>A||f<x){let xe=typeof x=="bigint"?"n":"",K;throw x===0||x===BigInt(0)?K=`>= 0${xe} and < 2${xe} ** ${(de+1)*8}${xe}`:K=`>= -(2${xe} ** ${(de+1)*8-1}${xe}) and < 2 ** ${(de+1)*8-1}${xe}`,new J.ERR_OUT_OF_RANGE("value",K,f)}V(B,ee,de)}function Z(f,x){if(typeof f!="number")throw new J.ERR_INVALID_ARG_TYPE(x,"number",f)}function be(f,x,A){throw Math.floor(f)!==f?(Z(f,A),new J.ERR_OUT_OF_RANGE("offset","an integer",f)):x<0?new J.ERR_BUFFER_OUT_OF_BOUNDS:new J.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${x}`,f)}let se=/[^+/0-9A-Za-z-_]/g;function M(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,x){x=x||1/0;let A,B=f.length,ee=null,de=[];for(let xe=0;xe<B;++xe){if(A=f.charCodeAt(xe),A>55295&&A<57344){if(!ee){if(A>56319){(x-=3)>-1&&de.push(239,191,189);continue}else if(xe+1===B){(x-=3)>-1&&de.push(239,191,189);continue}ee=A;continue}if(A<56320){(x-=3)>-1&&de.push(239,191,189),ee=A;continue}A=(ee-55296<<10|A-56320)+65536}else ee&&(x-=3)>-1&&de.push(239,191,189);if(ee=null,A<128){if((x-=1)<0)break;de.push(A)}else if(A<2048){if((x-=2)<0)break;de.push(A>>6|192,A&63|128)}else if(A<65536){if((x-=3)<0)break;de.push(A>>12|224,A>>6&63|128,A&63|128)}else if(A<1114112){if((x-=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 re(f){let x=[];for(let A=0;A<f.length;++A)x.push(f.charCodeAt(A)&255);return x}function he(f,x){let A,B,ee,de=[];for(let xe=0;xe<f.length&&!((x-=2)<0);++xe)A=f.charCodeAt(xe),B=A>>8,ee=A%256,de.push(ee),de.push(B);return de}function fe(f){return o.toByteArray(M(f))}function ye(f,x,A,B){let ee;for(ee=0;ee<B&&!(ee+A>=x.length||ee>=f.length);++ee)x[ee+A]=f[ee];return ee}function H(f,x){return f instanceof x||f!=null&&f.constructor!=null&&f.constructor.name!=null&&f.constructor.name===x.name}function ge(f){return f!==f}let we=(function(){let f="0123456789abcdef",x=new Array(256);for(let A=0;A<16;++A){let B=A*16;for(let ee=0;ee<16;++ee)x[B+ee]=f[A]+f[ee]}return x})();function ae(f){return typeof BigInt>"u"?Le:f}function Le(){throw new Error("BigInt not supported")}return It}var Wt,Ei,lr,Ai,It,Ii,bu=Qe(()=>{le(),ue(),ce(),Wt={},Ei=!1,lr={},Ai=!1,It={},Ii=!1}),Fe={};Qt(Fe,{Buffer:()=>Jr,INSPECT_MAX_BYTES:()=>Oa,default:()=>mt,kMaxLength:()=>La});var mt,Jr,Oa,La,qe=Qe(()=>{le(),ue(),ce(),bu(),mt=gu(),mt.Buffer,mt.SlowBuffer,mt.INSPECT_MAX_BYTES,mt.kMaxLength,Jr=mt.Buffer,Oa=mt.INSPECT_MAX_BYTES,La=mt.kMaxLength}),ue=Qe(()=>{qe()}),Ue=me((o,e)=>{le(),ue(),ce();var t=class extends Error{constructor(r){if(!Array.isArray(r))throw new TypeError(`Expected input to be an Array, got ${typeof r}`);let i="";for(let n=0;n<r.length;n++)i+=` ${r[n].stack}
|
|
2
|
-
`;super(i),this.name="AggregateError",this.errors=r}};e.exports={AggregateError:t,ArrayIsArray(r){return Array.isArray(r)},ArrayPrototypeIncludes(r,i){return r.includes(i)},ArrayPrototypeIndexOf(r,i){return r.indexOf(i)},ArrayPrototypeJoin(r,i){return r.join(i)},ArrayPrototypeMap(r,i){return r.map(i)},ArrayPrototypePop(r,i){return r.pop(i)},ArrayPrototypePush(r,i){return r.push(i)},ArrayPrototypeSlice(r,i,n){return r.slice(i,n)},Error,FunctionPrototypeCall(r,i,...n){return r.call(i,...n)},FunctionPrototypeSymbolHasInstance(r,i){return Function.prototype[Symbol.hasInstance].call(r,i)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(r,i){return Object.defineProperties(r,i)},ObjectDefineProperty(r,i,n){return Object.defineProperty(r,i,n)},ObjectGetOwnPropertyDescriptor(r,i){return Object.getOwnPropertyDescriptor(r,i)},ObjectKeys(r){return Object.keys(r)},ObjectSetPrototypeOf(r,i){return Object.setPrototypeOf(r,i)},Promise,PromisePrototypeCatch(r,i){return r.catch(i)},PromisePrototypeThen(r,i,n){return r.then(i,n)},PromiseReject(r){return Promise.reject(r)},PromiseResolve(r){return Promise.resolve(r)},ReflectApply:Reflect.apply,RegExpPrototypeTest(r,i){return r.test(i)},SafeSet:Set,String,StringPrototypeSlice(r,i,n){return r.slice(i,n)},StringPrototypeToLowerCase(r){return r.toLowerCase()},StringPrototypeToUpperCase(r){return r.toUpperCase()},StringPrototypeTrim(r){return r.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(r,i,n){return r.set(i,n)},Boolean,Uint8Array}}),Ma=me((o,e)=>{le(),ue(),ce(),e.exports={format(t,...r){return t.replace(/%([sdifj])/g,function(...[i,n]){let s=r.shift();return n==="f"?s.toFixed(6):n==="j"?JSON.stringify(s):n==="s"&&typeof s=="object"?`${s.constructor!==Object?s.constructor.name:""} {}`.trim():s.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}}),Ye=me((o,e)=>{le(),ue(),ce();var{format:t,inspect:r}=Ma(),{AggregateError:i}=Ue(),n=globalThis.AggregateError||i,s=Symbol("kIsNodeError"),a=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,c="__node_internal_",u={};function d(m,k){if(!m)throw new u.ERR_INTERNAL_ASSERTION(k)}function p(m){let k="",_=m.length,v=m[0]==="-"?1:0;for(;_>=v+4;_-=3)k=`_${m.slice(_-3,_)}${k}`;return`${m.slice(0,_)}${k}`}function g(m,k,_){if(typeof k=="function")return d(k.length<=_.length,`Code: ${m}; The provided arguments length (${_.length}) does not match the required ones (${k.length}).`),k(..._);let v=(k.match(/%[dfijoOs]/g)||[]).length;return d(v===_.length,`Code: ${m}; The provided arguments length (${_.length}) does not match the required ones (${v}).`),_.length===0?k:t(k,..._)}function h(m,k,_){_||(_=Error);class v extends _{constructor(...S){super(g(m,k,S))}toString(){return`${this.name} [${m}]: ${this.message}`}}Object.defineProperties(v.prototype,{name:{value:_.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 _=new n([k,m],k.message);return _.code=k.code,_}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"}};h("ERR_ASSERTION","%s",Error),h("ERR_INVALID_ARG_TYPE",(m,k,_)=>{d(typeof m=="string","'name' must be a string"),Array.isArray(k)||(k=[k]);let v="The ";m.endsWith(" argument")?v+=`${m} `:v+=`"${m}" ${m.includes(".")?"property":"argument"} `,v+="must be ";let E=[],S=[],I=[];for(let O of k)d(typeof O=="string","All expected entries have to be of type string"),a.includes(O)?E.push(O.toLowerCase()):l.test(O)?S.push(O):(d(O!=="object",'The value "object" should be written as "Object"'),I.push(O));if(S.length>0){let O=E.indexOf("object");O!==-1&&(E.splice(E,O,1),S.push("Object"))}if(E.length>0){switch(E.length){case 1:v+=`of type ${E[0]}`;break;case 2:v+=`one of type ${E[0]} or ${E[1]}`;break;default:{let O=E.pop();v+=`one of type ${E.join(", ")}, or ${O}`}}(S.length>0||I.length>0)&&(v+=" or ")}if(S.length>0){switch(S.length){case 1:v+=`an instance of ${S[0]}`;break;case 2:v+=`an instance of ${S[0]} or ${S[1]}`;break;default:{let O=S.pop();v+=`an instance of ${S.join(", ")}, or ${O}`}}I.length>0&&(v+=" or ")}switch(I.length){case 0:break;case 1:I[0].toLowerCase()!==I[0]&&(v+="an "),v+=`${I[0]}`;break;case 2:v+=`one of ${I[0]} or ${I[1]}`;break;default:{let O=I.pop();v+=`one of ${I.join(", ")}, or ${O}`}}if(_==null)v+=`. Received ${_}`;else if(typeof _=="function"&&_.name)v+=`. Received function ${_.name}`;else if(typeof _=="object"){var P;if((P=_.constructor)!==null&&P!==void 0&&P.name)v+=`. Received an instance of ${_.constructor.name}`;else{let O=r(_,{depth:-1});v+=`. Received ${O}`}}else{let O=r(_,{colors:!1});O.length>25&&(O=`${O.slice(0,25)}...`),v+=`. Received type ${typeof _} (${O})`}return v},TypeError),h("ERR_INVALID_ARG_VALUE",(m,k,_="is invalid")=>{let v=r(k);return v.length>128&&(v=v.slice(0,128)+"..."),`The ${m.includes(".")?"property":"argument"} '${m}' ${_}. Received ${v}`},TypeError),h("ERR_INVALID_RETURN_VALUE",(m,k,_)=>{var v;let E=_!=null&&(v=_.constructor)!==null&&v!==void 0&&v.name?`instance of ${_.constructor.name}`:`type ${typeof _}`;return`Expected ${m} to be returned from the "${k}" function but got ${E}.`},TypeError),h("ERR_MISSING_ARGS",(...m)=>{d(m.length>0,"At least one arg needs to be specified");let k,_=m.length;switch(m=(Array.isArray(m)?m:[m]).map(v=>`"${v}"`).join(" or "),_){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),h("ERR_OUT_OF_RANGE",(m,k,_)=>{d(k,'Missing "range" argument');let v;if(Number.isInteger(_)&&Math.abs(_)>2**32)v=p(String(_));else if(typeof _=="bigint"){v=String(_);let E=BigInt(2)**BigInt(32);(_>E||_<-E)&&(v=p(v)),v+="n"}else v=r(_);return`The value of "${m}" is out of range. It must be ${k}. Received ${v}`},RangeError),h("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),h("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),h("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),h("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),h("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),h("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),h("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),h("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),h("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),h("ERR_STREAM_WRITE_AFTER_END","write after end",Error),h("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:w,aggregateTwoErrors:b(y),hideStackFrames:b,codes:u}}),pr=me((o,e)=>{le(),ue(),ce();var{AbortController:t,AbortSignal:r}=typeof self<"u"?self:typeof window<"u"?window:void 0;e.exports=t,e.exports.AbortSignal=r,e.exports.default=t}),Pt={};Qt(Pt,{EventEmitter:()=>Na,default:()=>zt,defaultMaxListeners:()=>Ra,init:()=>ja,listenerCount:()=>Da,on:()=>$a,once:()=>Ua});function yu(){if(Ti)return cr;Ti=!0;var o=typeof Reflect=="object"?Reflect:null,e=o&&typeof o.apply=="function"?o.apply:function(_,v,E){return Function.prototype.apply.call(_,v,E)},t;o&&typeof o.ownKeys=="function"?t=o.ownKeys:Object.getOwnPropertySymbols?t=function(_){return Object.getOwnPropertyNames(_).concat(Object.getOwnPropertySymbols(_))}:t=function(_){return Object.getOwnPropertyNames(_)};function r(_){console&&console.warn&&console.warn(_)}var i=Number.isNaN||function(_){return _!==_};function n(){n.init.call(this)}cr=n,cr.once=w,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var s=10;function a(_){if(typeof _!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof _)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(_){if(typeof _!="number"||_<0||i(_))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+_+".");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(_){if(typeof _!="number"||_<0||i(_))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+_+".");return this._maxListeners=_,this};function l(_){return _._maxListeners===void 0?n.defaultMaxListeners:_._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(_){for(var v=[],E=1;E<arguments.length;E++)v.push(arguments[E]);var S=_==="error",I=this._events;if(I!==void 0)S=S&&I.error===void 0;else if(!S)return!1;if(S){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 j=I[_];if(j===void 0)return!1;if(typeof j=="function")e(j,this,v);else for(var T=j.length,F=h(j,T),E=0;E<T;++E)e(F[E],this,v);return!0};function c(_,v,E,S){var I,P,O;if(a(E),P=_._events,P===void 0?(P=_._events=Object.create(null),_._eventsCount=0):(P.newListener!==void 0&&(_.emit("newListener",v,E.listener?E.listener:E),P=_._events),O=P[v]),O===void 0)O=P[v]=E,++_._eventsCount;else if(typeof O=="function"?O=P[v]=S?[E,O]:[O,E]:S?O.unshift(E):O.push(E),I=l(_),I>0&&O.length>I&&!O.warned){O.warned=!0;var j=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(v)+" listeners added. Use emitter.setMaxListeners() to increase limit");j.name="MaxListenersExceededWarning",j.emitter=_,j.type=v,j.count=O.length,r(j)}return _}n.prototype.addListener=function(_,v){return c(this,_,v,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(_,v){return c(this,_,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(_,v,E){var S={fired:!1,wrapFn:void 0,target:_,type:v,listener:E},I=u.bind(S);return I.listener=E,S.wrapFn=I,I}n.prototype.once=function(_,v){return a(v),this.on(_,d(this,_,v)),this},n.prototype.prependOnceListener=function(_,v){return a(v),this.prependListener(_,d(this,_,v)),this},n.prototype.removeListener=function(_,v){var E,S,I,P,O;if(a(v),S=this._events,S===void 0)return this;if(E=S[_],E===void 0)return this;if(E===v||E.listener===v)--this._eventsCount===0?this._events=Object.create(null):(delete S[_],S.removeListener&&this.emit("removeListener",_,E.listener||v));else if(typeof E!="function"){for(I=-1,P=E.length-1;P>=0;P--)if(E[P]===v||E[P].listener===v){O=E[P].listener,I=P;break}if(I<0)return this;I===0?E.shift():b(E,I),E.length===1&&(S[_]=E[0]),S.removeListener!==void 0&&this.emit("removeListener",_,O||v)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(_){var v,E,S;if(E=this._events,E===void 0)return this;if(E.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):E[_]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete E[_]),this;if(arguments.length===0){var I=Object.keys(E),P;for(S=0;S<I.length;++S)P=I[S],P!=="removeListener"&&this.removeAllListeners(P);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(v=E[_],typeof v=="function")this.removeListener(_,v);else if(v!==void 0)for(S=v.length-1;S>=0;S--)this.removeListener(_,v[S]);return this};function p(_,v,E){var S=_._events;if(S===void 0)return[];var I=S[v];return I===void 0?[]:typeof I=="function"?E?[I.listener||I]:[I]:E?y(I):h(I,I.length)}n.prototype.listeners=function(_){return p(this,_,!0)},n.prototype.rawListeners=function(_){return p(this,_,!1)},n.listenerCount=function(_,v){return typeof _.listenerCount=="function"?_.listenerCount(v):g.call(_,v)},n.prototype.listenerCount=g;function g(_){var v=this._events;if(v!==void 0){var E=v[_];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function h(_,v){for(var E=new Array(v),S=0;S<v;++S)E[S]=_[S];return E}function b(_,v){for(;v+1<_.length;v++)_[v]=_[v+1];_.pop()}function y(_){for(var v=new Array(_.length),E=0;E<v.length;++E)v[E]=_[E].listener||_[E];return v}function w(_,v){return new Promise(function(E,S){function I(O){_.removeListener(v,P),S(O)}function P(){typeof _.removeListener=="function"&&_.removeListener("error",I),E([].slice.call(arguments))}k(_,v,P,{once:!0}),v!=="error"&&m(_,I,{once:!0})})}function m(_,v,E){typeof _.on=="function"&&k(_,"error",v,E)}function k(_,v,E,S){if(typeof _.on=="function")S.once?_.once(v,E):_.on(v,E);else if(typeof _.addEventListener=="function")_.addEventListener(v,function I(P){S.once&&_.removeEventListener(v,I),E(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof _)}return cr}var cr,Ti,zt,Na,Ra,ja,Da,$a,Ua,Ut=Qe(()=>{le(),ue(),ce(),cr={},Ti=!1,zt=yu(),zt.once,zt.once=function(o,e){return new Promise((t,r)=>{function i(...s){n!==void 0&&o.removeListener("error",n),t(s)}let n;e!=="error"&&(n=s=>{o.removeListener(name,i),r(s)},o.once("error",n)),o.once(e,i)})},zt.on=function(o,e){let t=[],r=[],i=null,n=!1,s={async next(){let c=t.shift();if(c)return createIterResult(c,!1);if(i){let u=Promise.reject(i);return i=null,u}return n?createIterResult(void 0,!0):new Promise((u,d)=>r.push({resolve:u,reject:d}))},async return(){o.removeListener(e,a),o.removeListener("error",l),n=!0;for(let c of r)c.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(c){i=c,o.removeListener(e,a),o.removeListener("error",l)},[Symbol.asyncIterator](){return this}};return o.on(e,a),o.on("error",l),s;function a(...c){let u=r.shift();u?u.resolve(createIterResult(c,!1)):t.push(c)}function l(c){n=!0;let u=r.shift();u?u.reject(c):i=c,s.return()}},{EventEmitter:Na,defaultMaxListeners:Ra,init:ja,listenerCount:Da,on:$a,once:Ua}=zt}),Je=me((o,e)=>{le(),ue(),ce();var t=(qe(),Re(Fe)),{format:r,inspect:i}=Ma(),{codes:{ERR_INVALID_ARG_TYPE:n}}=Ye(),{kResistStopPropagation:s,AggregateError:a,SymbolDispose:l}=Ue(),c=globalThis.AbortSignal||pr().AbortSignal,u=globalThis.AbortController||pr().AbortController,d=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||t.Blob,g=typeof p<"u"?function(y){return y instanceof p}:function(y){return!1},h=(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,..._)=>k?m(k):w(..._))})},debuglog(){return function(){}},format:r,inspect:i,types:{isAsyncFunction(y){return y instanceof d},isArrayBufferView(y){return ArrayBuffer.isView(y)}},isBlob:g,deprecate(y,w){return y},addAbortListener:(Ut(),Re(Pt)).addAbortListener||function(y,w){if(y===void 0)throw new n("signal","AbortSignal",y);h(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=>{h(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")}),gr=me((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ArrayPrototypeIncludes:r,ArrayPrototypeJoin:i,ArrayPrototypeMap:n,NumberIsInteger:s,NumberIsNaN:a,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:c,NumberParseInt:u,ObjectPrototypeHasOwnProperty:d,RegExpPrototypeExec:p,String:g,StringPrototypeToUpperCase:h,StringPrototypeTrim:b}=Ue(),{hideStackFrames:y,codes:{ERR_SOCKET_BAD_PORT:w,ERR_INVALID_ARG_TYPE:m,ERR_INVALID_ARG_VALUE:k,ERR_OUT_OF_RANGE:_,ERR_UNKNOWN_SIGNAL:v}}=Ye(),{normalizeEncoding:E}=Je(),{isAsyncFunction:S,isArrayBufferView:I}=Je().types,P={};function O(H){return H===(H|0)}function j(H){return H===H>>>0}var T=/^[0-7]+$/,F="must be a 32-bit unsigned integer or an octal string";function $(H,ge,we){if(typeof H>"u"&&(H=we),typeof H=="string"){if(p(T,H)===null)throw new k(ge,H,F);H=u(H,8)}return z(H,ge),H}var U=y((H,ge,we=c,ae=l)=>{if(typeof H!="number")throw new m(ge,"number",H);if(!s(H))throw new _(ge,"an integer",H);if(H<we||H>ae)throw new _(ge,`>= ${we} && <= ${ae}`,H)}),X=y((H,ge,we=-2147483648,ae=2147483647)=>{if(typeof H!="number")throw new m(ge,"number",H);if(!s(H))throw new _(ge,"an integer",H);if(H<we||H>ae)throw new _(ge,`>= ${we} && <= ${ae}`,H)}),z=y((H,ge,we=!1)=>{if(typeof H!="number")throw new m(ge,"number",H);if(!s(H))throw new _(ge,"an integer",H);let ae=we?1:0,Le=4294967295;if(H<ae||H>Le)throw new _(ge,`>= ${ae} && <= ${Le}`,H)});function W(H,ge){if(typeof H!="string")throw new m(ge,"string",H)}function ne(H,ge,we=void 0,ae){if(typeof H!="number")throw new m(ge,"number",H);if(we!=null&&H<we||ae!=null&&H>ae||(we!=null||ae!=null)&&a(H))throw new _(ge,`${we!=null?`>= ${we}`:""}${we!=null&&ae!=null?" && ":""}${ae!=null?`<= ${ae}`:""}`,H)}var D=y((H,ge,we)=>{if(!r(we,H)){let ae="must be one of: "+i(n(we,Le=>typeof Le=="string"?`'${Le}'`:g(Le)),", ");throw new k(ge,H,ae)}});function G(H,ge){if(typeof H!="boolean")throw new m(ge,"boolean",H)}function L(H,ge,we){return H==null||!d(H,ge)?we:H[ge]}var Y=y((H,ge,we=null)=>{let ae=L(we,"allowArray",!1),Le=L(we,"allowFunction",!1);if(!L(we,"nullable",!1)&&H===null||!ae&&t(H)||typeof H!="object"&&(!Le||typeof H!="function"))throw new m(ge,"Object",H)}),pe=y((H,ge)=>{if(H!=null&&typeof H!="object"&&typeof H!="function")throw new m(ge,"a dictionary",H)}),te=y((H,ge,we=0)=>{if(!t(H))throw new m(ge,"Array",H);if(H.length<we){let ae=`must be longer than ${we}`;throw new k(ge,H,ae)}});function ve(H,ge){te(H,ge);for(let we=0;we<H.length;we++)W(H[we],`${ge}[${we}]`)}function J(H,ge){te(H,ge);for(let we=0;we<H.length;we++)G(H[we],`${ge}[${we}]`)}function R(H,ge){te(H,ge);for(let we=0;we<H.length;we++){let ae=H[we],Le=`${ge}[${we}]`;if(ae==null)throw new m(Le,"AbortSignal",ae);be(ae,Le)}}function ie(H,ge="signal"){if(W(H,ge),P[H]===void 0)throw P[h(H)]!==void 0?new v(H+" (signals must use all capital letters)"):new v(H)}var V=y((H,ge="buffer")=>{if(!I(H))throw new m(ge,["Buffer","TypedArray","DataView"],H)});function Q(H,ge){let we=E(ge),ae=H.length;if(we==="hex"&&ae%2!==0)throw new k("encoding",ge,`is invalid for data of length ${ae}`)}function Z(H,ge="Port",we=!0){if(typeof H!="number"&&typeof H!="string"||typeof H=="string"&&b(H).length===0||+H!==+H>>>0||H>65535||H===0&&!we)throw new w(ge,H,we);return H|0}var be=y((H,ge)=>{if(H!==void 0&&(H===null||typeof H!="object"||!("aborted"in H)))throw new m(ge,"AbortSignal",H)}),se=y((H,ge)=>{if(typeof H!="function")throw new m(ge,"Function",H)}),M=y((H,ge)=>{if(typeof H!="function"||S(H))throw new m(ge,"Function",H)}),q=y((H,ge)=>{if(H!==void 0)throw new m(ge,"undefined",H)});function re(H,ge,we){if(!r(we,H))throw new m(ge,`('${i(we,"|")}')`,H)}var he=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function fe(H,ge){if(typeof H>"u"||!p(he,H))throw new k(ge,H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function ye(H){if(typeof H=="string")return fe(H,"hints"),H;if(t(H)){let ge=H.length,we="";if(ge===0)return we;for(let ae=0;ae<ge;ae++){let Le=H[ae];fe(Le,"hints"),we+=Le,ae!==ge-1&&(we+=", ")}return we}throw new k("hints",H,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:O,isUint32:j,parseFileMode:$,validateArray:te,validateStringArray:ve,validateBooleanArray:J,validateAbortSignalArray:R,validateBoolean:G,validateBuffer:V,validateDictionary:pe,validateEncoding:Q,validateFunction:se,validateInt32:X,validateInteger:U,validateNumber:ne,validateObject:Y,validateOneOf:D,validatePlainFunction:M,validatePort:Z,validateSignalName:ie,validateString:W,validateUint32:z,validateUndefined:q,validateUnion:re,validateAbortSignal:be,validateLinkHeaderValue:ye}}),Bt=me((o,e)=>{le(),ue(),ce();var t=e.exports={},r,i;function n(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?r=setTimeout:r=n}catch{r=n}try{typeof clearTimeout=="function"?i=clearTimeout:i=s}catch{i=s}})();function a(w){if(r===setTimeout)return setTimeout(w,0);if((r===n||!r)&&setTimeout)return r=setTimeout,setTimeout(w,0);try{return r(w,0)}catch{try{return r.call(null,w,0)}catch{return r.call(this,w,0)}}}function l(w){if(i===clearTimeout)return clearTimeout(w);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(w);try{return i(w)}catch{try{return i.call(null,w)}catch{return i.call(this,w)}}}var c=[],u=!1,d,p=-1;function g(){!u||!d||(u=!1,d.length?c=d.concat(c):p=-1,c.length&&h())}function h(){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 b(w,m)),c.length===1&&!u&&a(h)};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}}),wt=me((o,e)=>{le(),ue(),ce();var{SymbolAsyncIterator:t,SymbolIterator:r,SymbolFor:i}=Ue(),n=i("nodejs.stream.destroyed"),s=i("nodejs.stream.errored"),a=i("nodejs.stream.readable"),l=i("nodejs.stream.writable"),c=i("nodejs.stream.disturbed"),u=i("nodejs.webstream.isClosedPromise"),d=i("nodejs.webstream.controllerErrorFunction");function p(L,Y=!1){var pe;return!!(L&&typeof L.pipe=="function"&&typeof L.on=="function"&&(!Y||typeof L.pause=="function"&&typeof L.resume=="function")&&(!L._writableState||((pe=L._readableState)===null||pe===void 0?void 0:pe.readable)!==!1)&&(!L._writableState||L._readableState))}function g(L){var Y;return!!(L&&typeof L.write=="function"&&typeof L.on=="function"&&(!L._readableState||((Y=L._writableState)===null||Y===void 0?void 0:Y.writable)!==!1))}function h(L){return!!(L&&typeof L.pipe=="function"&&L._readableState&&typeof L.on=="function"&&typeof L.write=="function")}function b(L){return L&&(L._readableState||L._writableState||typeof L.write=="function"&&typeof L.on=="function"||typeof L.pipe=="function"&&typeof L.on=="function")}function y(L){return!!(L&&!b(L)&&typeof L.pipeThrough=="function"&&typeof L.getReader=="function"&&typeof L.cancel=="function")}function w(L){return!!(L&&!b(L)&&typeof L.getWriter=="function"&&typeof L.abort=="function")}function m(L){return!!(L&&!b(L)&&typeof L.readable=="object"&&typeof L.writable=="object")}function k(L){return y(L)||w(L)||m(L)}function _(L,Y){return L==null?!1:Y===!0?typeof L[t]=="function":Y===!1?typeof L[r]=="function":typeof L[t]=="function"||typeof L[r]=="function"}function v(L){if(!b(L))return null;let Y=L._writableState,pe=L._readableState,te=Y||pe;return!!(L.destroyed||L[n]||te!=null&&te.destroyed)}function E(L){if(!g(L))return null;if(L.writableEnded===!0)return!0;let Y=L._writableState;return Y!=null&&Y.errored?!1:typeof Y?.ended!="boolean"?null:Y.ended}function S(L,Y){if(!g(L))return null;if(L.writableFinished===!0)return!0;let pe=L._writableState;return pe!=null&&pe.errored?!1:typeof pe?.finished!="boolean"?null:!!(pe.finished||Y===!1&&pe.ended===!0&&pe.length===0)}function I(L){if(!p(L))return null;if(L.readableEnded===!0)return!0;let Y=L._readableState;return!Y||Y.errored?!1:typeof Y?.ended!="boolean"?null:Y.ended}function P(L,Y){if(!p(L))return null;let pe=L._readableState;return pe!=null&&pe.errored?!1:typeof pe?.endEmitted!="boolean"?null:!!(pe.endEmitted||Y===!1&&pe.ended===!0&&pe.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 j(L){return L&&L[l]!=null?L[l]:typeof L?.writable!="boolean"?null:v(L)?!1:g(L)&&L.writable&&!E(L)}function T(L,Y){return b(L)?v(L)?!0:!(Y?.readable!==!1&&O(L)||Y?.writable!==!1&&j(L)):null}function F(L){var Y,pe;return b(L)?L.writableErrored?L.writableErrored:(Y=(pe=L._writableState)===null||pe===void 0?void 0:pe.errored)!==null&&Y!==void 0?Y:null:null}function $(L){var Y,pe;return b(L)?L.readableErrored?L.readableErrored:(Y=(pe=L._readableState)===null||pe===void 0?void 0:pe.errored)!==null&&Y!==void 0?Y:null:null}function U(L){if(!b(L))return null;if(typeof L.closed=="boolean")return L.closed;let Y=L._writableState,pe=L._readableState;return typeof Y?.closed=="boolean"||typeof pe?.closed=="boolean"?Y?.closed||pe?.closed:typeof L._closed=="boolean"&&X(L)?L._closed:null}function X(L){return typeof L._closed=="boolean"&&typeof L._defaultKeepAlive=="boolean"&&typeof L._removedConnection=="boolean"&&typeof L._removedContLen=="boolean"}function z(L){return typeof L._sent100=="boolean"&&X(L)}function W(L){var Y;return typeof L._consuming=="boolean"&&typeof L._dumped=="boolean"&&((Y=L.req)===null||Y===void 0?void 0:Y.upgradeOrConnect)===void 0}function ne(L){if(!b(L))return null;let Y=L._writableState,pe=L._readableState,te=Y||pe;return!te&&z(L)||!!(te&&te.autoDestroy&&te.emitClose&&te.closed===!1)}function D(L){var Y;return!!(L&&((Y=L[c])!==null&&Y!==void 0?Y:L.readableDidRead||L.readableAborted))}function G(L){var Y,pe,te,ve,J,R,ie,V,Q,Z;return!!(L&&((Y=(pe=(te=(ve=(J=(R=L[s])!==null&&R!==void 0?R:L.readableErrored)!==null&&J!==void 0?J:L.writableErrored)!==null&&ve!==void 0?ve:(ie=L._readableState)===null||ie===void 0?void 0:ie.errorEmitted)!==null&&te!==void 0?te:(V=L._writableState)===null||V===void 0?void 0:V.errorEmitted)!==null&&pe!==void 0?pe:(Q=L._readableState)===null||Q===void 0?void 0:Q.errored)!==null&&Y!==void 0?Y:!((Z=L._writableState)===null||Z===void 0)&&Z.errored))}e.exports={isDestroyed:v,kIsDestroyed:n,isDisturbed:D,kIsDisturbed:c,isErrored:G,kIsErrored:s,isReadable:O,kIsReadable:a,kIsClosedPromise:u,kControllerErrorFunction:d,kIsWritable:l,isClosed:U,isDuplexNodeStream:h,isFinished:T,isIterable:_,isReadableNodeStream:p,isReadableStream:y,isReadableEnded:I,isReadableFinished:P,isReadableErrored:$,isNodeStream:b,isWebStream:k,isWritable:j,isWritableNodeStream:g,isWritableStream:w,isWritableEnded:E,isWritableFinished:S,isWritableErrored:F,isServerRequest:W,isServerResponse:z,willEmitClose:ne,isTransformStream:m}}),Ot=me((o,e)=>{le(),ue(),ce();var t=Bt(),{AbortError:r,codes:i}=Ye(),{ERR_INVALID_ARG_TYPE:n,ERR_STREAM_PREMATURE_CLOSE:s}=i,{kEmptyObject:a,once:l}=Je(),{validateAbortSignal:c,validateFunction:u,validateObject:d,validateBoolean:p}=gr(),{Promise:g,PromisePrototypeThen:h,SymbolDispose:b}=Ue(),{isClosed:y,isReadable:w,isReadableNodeStream:m,isReadableStream:k,isReadableFinished:_,isReadableErrored:v,isWritable:E,isWritableNodeStream:S,isWritableStream:I,isWritableFinished:P,isWritableErrored:O,isNodeStream:j,willEmitClose:T,kIsClosedPromise:F}=wt(),$;function U(D){return D.setHeader&&typeof D.abort=="function"}var X=()=>{};function z(D,G,L){var Y,pe;if(arguments.length===2?(L=G,G=a):G==null?G=a:d(G,"options"),u(L,"callback"),c(G.signal,"options.signal"),L=l(L),k(D)||I(D))return W(D,G,L);if(!j(D))throw new n("stream",["ReadableStream","WritableStream","Stream"],D);let te=(Y=G.readable)!==null&&Y!==void 0?Y:m(D),ve=(pe=G.writable)!==null&&pe!==void 0?pe:S(D),J=D._writableState,R=D._readableState,ie=()=>{D.writable||Z()},V=T(D)&&m(D)===te&&S(D)===ve,Q=P(D,!1),Z=()=>{Q=!0,D.destroyed&&(V=!1),!(V&&(!D.readable||te))&&(!te||be)&&L.call(D)},be=_(D,!1),se=()=>{be=!0,D.destroyed&&(V=!1),!(V&&(!D.writable||ve))&&(!ve||Q)&&L.call(D)},M=H=>{L.call(D,H)},q=y(D),re=()=>{q=!0;let H=O(D)||v(D);if(H&&typeof H!="boolean")return L.call(D,H);if(te&&!be&&m(D,!0)&&!_(D,!1))return L.call(D,new s);if(ve&&!Q&&!P(D,!1))return L.call(D,new s);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",Z)};U(D)?(D.on("complete",Z),V||D.on("abort",re),D.req?fe():D.on("request",fe)):ve&&!J&&(D.on("end",ie),D.on("close",ie)),!V&&typeof D.aborted=="boolean"&&D.on("aborted",re),D.on("end",se),D.on("finish",Z),G.error!==!1&&D.on("error",M),D.on("close",re),q?t.nextTick(re):J!=null&&J.errorEmitted||R!=null&&R.errorEmitted?V||t.nextTick(he):(!te&&(!V||w(D))&&(Q||E(D)===!1)||!ve&&(!V||E(D))&&(be||w(D)===!1)||R&&D.req&&D.aborted)&&t.nextTick(he);let ye=()=>{L=X,D.removeListener("aborted",re),D.removeListener("complete",Z),D.removeListener("abort",re),D.removeListener("request",fe),D.req&&D.req.removeListener("finish",Z),D.removeListener("end",ie),D.removeListener("close",ie),D.removeListener("finish",Z),D.removeListener("end",se),D.removeListener("error",M),D.removeListener("close",re)};if(G.signal&&!q){let H=()=>{let ge=L;ye(),ge.call(D,new r(void 0,{cause:G.signal.reason}))};if(G.signal.aborted)t.nextTick(H);else{$=$||Je().addAbortListener;let ge=$(G.signal,H),we=L;L=l((...ae)=>{ge[b](),we.apply(D,ae)})}}return ye}function W(D,G,L){let Y=!1,pe=X;if(G.signal)if(pe=()=>{Y=!0,L.call(D,new r(void 0,{cause:G.signal.reason}))},G.signal.aborted)t.nextTick(pe);else{$=$||Je().addAbortListener;let ve=$(G.signal,pe),J=L;L=l((...R)=>{ve[b](),J.apply(D,R)})}let te=(...ve)=>{Y||t.nextTick(()=>L.apply(D,ve))};return h(D[F].promise,te,te),X}function ne(D,G){var L;let Y=!1;return G===null&&(G=a),(L=G)!==null&&L!==void 0&&L.cleanup&&(p(G.cleanup,"cleanup"),Y=G.cleanup),new g((pe,te)=>{let ve=z(D,G,J=>{Y&&ve(),J?te(J):pe()})})}e.exports=z,e.exports.finished=ne}),Xt=me((o,e)=>{le(),ue(),ce();var t=Bt(),{aggregateTwoErrors:r,codes:{ERR_MULTIPLE_CALLBACK:i},AbortError:n}=Ye(),{Symbol:s}=Ue(),{kIsDestroyed:a,isDestroyed:l,isFinished:c,isServerRequest:u}=wt(),d=s("kDestroy"),p=s("kConstruct");function g(T,F,$){T&&(T.stack,F&&!F.errored&&(F.errored=T),$&&!$.errored&&($.errored=T))}function h(T,F){let $=this._readableState,U=this._writableState,X=U||$;return U!=null&&U.destroyed||$!=null&&$.destroyed?(typeof F=="function"&&F(),this):(g(T,U,$),U&&(U.destroyed=!0),$&&($.destroyed=!0),X.constructed?b(this,T,F):this.once(d,function(z){b(this,r(z,T),F)}),this)}function b(T,F,$){let U=!1;function X(z){if(U)return;U=!0;let W=T._readableState,ne=T._writableState;g(z,ne,W),ne&&(ne.closed=!0),W&&(W.closed=!0),typeof $=="function"&&$(z),z?t.nextTick(y,T,z):t.nextTick(w,T)}try{T._destroy(F||null,X)}catch(z){X(z)}}function y(T,F){m(T,F),w(T)}function w(T){let F=T._readableState,$=T._writableState;$&&($.closeEmitted=!0),F&&(F.closeEmitted=!0),($!=null&&$.emitClose||F!=null&&F.emitClose)&&T.emit("close")}function m(T,F){let $=T._readableState,U=T._writableState;U!=null&&U.errorEmitted||$!=null&&$.errorEmitted||(U&&(U.errorEmitted=!0),$&&($.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 _(T,F,$){let U=T._readableState,X=T._writableState;if(X!=null&&X.destroyed||U!=null&&U.destroyed)return this;U!=null&&U.autoDestroy||X!=null&&X.autoDestroy?T.destroy(F):F&&(F.stack,X&&!X.errored&&(X.errored=F),U&&!U.errored&&(U.errored=F),$?t.nextTick(m,T,F):m(T,F))}function v(T,F){if(typeof T._construct!="function")return;let $=T._readableState,U=T._writableState;$&&($.constructed=!1),U&&(U.constructed=!1),T.once(p,F),!(T.listenerCount(p)>1)&&t.nextTick(E,T)}function E(T){let F=!1;function $(U){if(F){_(T,U??new i);return}F=!0;let X=T._readableState,z=T._writableState,W=z||X;X&&(X.constructed=!0),z&&(z.constructed=!0),W.destroyed?T.emit(d,U):U?_(T,U,!0):t.nextTick(S,T)}try{T._construct(U=>{t.nextTick($,U)})}catch(U){t.nextTick($,U)}}function S(T){T.emit(p)}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 j(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:j,destroy:h,undestroy:k,errorOrDestroy:_}}),Ao=me((o,e)=>{le(),ue(),ce();var{ArrayIsArray:t,ObjectSetPrototypeOf:r}=Ue(),{EventEmitter:i}=(Ut(),Re(Pt));function n(a){i.call(this,a)}r(n.prototype,i.prototype),r(n,i),n.prototype.pipe=function(a,l){let c=this;function u(w){a.writable&&a.write(w)===!1&&c.pause&&c.pause()}c.on("data",u);function d(){c.readable&&c.resume&&c.resume()}a.on("drain",d),!a._isStdio&&(!l||l.end!==!1)&&(c.on("end",g),c.on("close",h));let p=!1;function g(){p||(p=!0,a.end())}function h(){p||(p=!0,typeof a.destroy=="function"&&a.destroy())}function b(w){y(),i.listenerCount(this,"error")===0&&this.emit("error",w)}s(c,"error",b),s(a,"error",b);function y(){c.removeListener("data",u),a.removeListener("drain",d),c.removeListener("end",g),c.removeListener("close",h),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}}),en=me((o,e)=>{le(),ue(),ce();var{SymbolDispose:t}=Ue(),{AbortError:r,codes:i}=Ye(),{isNodeStream:n,isWebStream:s,kControllerErrorFunction:a}=wt(),l=Ot(),{ERR_INVALID_ARG_TYPE:c}=i,u,d=(p,g)=>{if(typeof p!="object"||!("aborted"in p))throw new c(g,"AbortSignal",p)};e.exports.addAbortSignal=function(p,g){if(d(p,"signal"),!n(g)&&!s(g))throw new c("stream",["ReadableStream","WritableStream","Stream"],g);return e.exports.addAbortSignalNoValidate(p,g)},e.exports.addAbortSignalNoValidate=function(p,g){if(typeof p!="object"||!("aborted"in p))return g;let h=n(g)?()=>{g.destroy(new r(void 0,{cause:p.reason}))}:()=>{g[a](new r(void 0,{cause:p.reason}))};if(p.aborted)h();else{u=u||Je().addAbortListener;let b=u(p,h);l(g,b[t])}return g}}),vu=me((o,e)=>{le(),ue(),ce();var{StringPrototypeSlice:t,SymbolIterator:r,TypedArrayPrototypeSet:i,Uint8Array:n}=Ue(),{Buffer:s}=(qe(),Re(Fe)),{inspect:a}=Je();e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(l){let c={data:l,next:null};this.length>0?this.tail.next=c:this.head=c,this.tail=c,++this.length}unshift(l){let c={data:l,next:this.head};this.length===0&&(this.tail=c),this.head=c,++this.length}shift(){if(this.length===0)return;let l=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,l}clear(){this.head=this.tail=null,this.length=0}join(l){if(this.length===0)return"";let c=this.head,u=""+c.data;for(;(c=c.next)!==null;)u+=l+c.data;return u}concat(l){if(this.length===0)return s.alloc(0);let c=s.allocUnsafe(l>>>0),u=this.head,d=0;for(;u;)i(c,u.data,d),d+=u.data.length,u=u.next;return c}consume(l,c){let u=this.head.data;if(l<u.length){let d=u.slice(0,l);return this.head.data=u.slice(l),d}return l===u.length?this.shift():c?this._getString(l):this._getBuffer(l)}first(){return this.head.data}*[r](){for(let l=this.head;l;l=l.next)yield l.data}_getString(l){let c="",u=this.head,d=0;do{let p=u.data;if(l>p.length)c+=p,l-=p.length;else{l===p.length?(c+=p,++d,u.next?this.head=u.next:this.head=this.tail=null):(c+=t(p,0,l),this.head=u,u.data=t(p,l));break}++d}while((u=u.next)!==null);return this.length-=d,c}_getBuffer(l){let c=s.allocUnsafe(l),u=l,d=this.head,p=0;do{let g=d.data;if(l>g.length)i(c,g,u-l),l-=g.length;else{l===g.length?(i(c,g,u-l),++p,d.next?this.head=d.next:this.head=this.tail=null):(i(c,new n(g.buffer,g.byteOffset,l),u-l),this.head=d,d.data=g.slice(l));break}++p}while((d=d.next)!==null);return this.length-=p,c}[Symbol.for("nodejs.util.inspect.custom")](l,c){return a(this,{...c,depth:0,customInspect:!1})}}}),tn=me((o,e)=>{le(),ue(),ce();var{MathFloor:t,NumberIsInteger:r}=Ue(),{validateInteger:i}=gr(),{ERR_INVALID_ARG_VALUE:n}=Ye().codes,s=16*1024,a=16;function l(p,g,h){return p.highWaterMark!=null?p.highWaterMark:g?p[h]:null}function c(p){return p?a:s}function u(p,g){i(g,"value",0),p?a=g:s=g}function d(p,g,h,b){let y=l(g,b,h);if(y!=null){if(!r(y)||y<0){let w=b?`options.${h}`:"options.highWaterMark";throw new n(w,y)}return t(y)}return c(p.objectMode)}e.exports={getHighWaterMark:d,getDefaultHighWaterMark:c,setDefaultHighWaterMark:u}}),wu=me((o,e)=>{le(),ue(),ce();var t=(qe(),Re(Fe)),r=t.Buffer;function i(s,a){for(var l in s)a[l]=s[l]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=t:(i(t,o),o.Buffer=n);function n(s,a,l){return r(s,a,l)}n.prototype=Object.create(r.prototype),i(r,n),n.from=function(s,a,l){if(typeof s=="number")throw new TypeError("Argument must not be a number");return r(s,a,l)},n.alloc=function(s,a,l){if(typeof s!="number")throw new TypeError("Argument must be a number");var c=r(s);return a!==void 0?typeof l=="string"?c.fill(a,l):c.fill(a):c.fill(0),c},n.allocUnsafe=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return r(s)},n.allocUnsafeSlow=function(s){if(typeof s!="number")throw new TypeError("Argument must be a number");return t.SlowBuffer(s)}}),ku=me(o=>{le(),ue(),ce();var e=wu().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 i(m){var k=r(m);if(typeof k!="string"&&(e.isEncoding===t||!t(m)))throw new Error("Unknown encoding: "+m);return k||m}o.StringDecoder=n;function n(m){this.encoding=i(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=h,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,_;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";_=this.lastNeed,this.lastNeed=0}else _=0;return _<m.length?k?k+this.text(m,_):this.text(m,_):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,_){var v=k.length-1;if(v<_)return 0;var E=s(k[v]);return E>=0?(E>0&&(m.lastNeed=E-1),E):--v<_||E===-2?0:(E=s(k[v]),E>=0?(E>0&&(m.lastNeed=E-2),E):--v<_||E===-2?0:(E=s(k[v]),E>=0?(E>0&&(E===2?E=0:m.lastNeed=E-3),E):0))}function l(m,k,_){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,_=l(this,m);if(_!==void 0)return _;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 _=a(this,m,k);if(!this.lastNeed)return m.toString("utf8",k);this.lastTotal=_;var v=m.length-(_-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 _=m.toString("utf16le",k);if(_){var v=_.charCodeAt(_.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],_.slice(0,-1)}return _}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 _=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,_)}return k}function h(m,k){var _=(m.length-k)%3;return _===0?m.toString("base64",k):(this.lastNeed=3-_,this.lastTotal=3,_===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-_))}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):""}}),Ba=me((o,e)=>{le(),ue(),ce();var t=Bt(),{PromisePrototypeThen:r,SymbolAsyncIterator:i,SymbolIterator:n}=Ue(),{Buffer:s}=(qe(),Re(Fe)),{ERR_INVALID_ARG_TYPE:a,ERR_STREAM_NULL_VALUES:l}=Ye().codes;function c(u,d,p){let g;if(typeof d=="string"||d instanceof s)return new u({objectMode:!0,...p,read(){this.push(d),this.push(null)}});let h;if(d&&d[i])h=!0,g=d[i]();else if(d&&d[n])h=!1,g=d[n]();else throw new a("iterable",["Iterable"],d);let b=new u({objectMode:!0,highWaterMark:1,...p}),y=!1;b._read=function(){y||(y=!0,m())},b._destroy=function(k,_){r(w(k),()=>t.nextTick(_,k),v=>t.nextTick(_,v||k))};async function w(k){let _=k!=null,v=typeof g.throw=="function";if(_&&v){let{value:E,done:S}=await g.throw(k);if(await E,S)return}if(typeof g.return=="function"){let{value:E}=await g.return();await E}}async function m(){for(;;){try{let{value:k,done:_}=h?await g.next():g.next();if(_)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}),rn=me((o,e)=>{le(),ue(),ce();var t=Bt(),{ArrayPrototypeIndexOf:r,NumberIsInteger:i,NumberIsNaN:n,NumberParseInt:s,ObjectDefineProperties:a,ObjectKeys:l,ObjectSetPrototypeOf:c,Promise:u,SafeSet:d,SymbolAsyncDispose:p,SymbolAsyncIterator:g,Symbol:h}=Ue();e.exports=ae,ae.ReadableState=we;var{EventEmitter:b}=(Ut(),Re(Pt)),{Stream:y,prependListener:w}=Ao(),{Buffer:m}=(qe(),Re(Fe)),{addAbortSignal:k}=en(),_=Ot(),v=Je().debuglog("stream",C=>{v=C}),E=vu(),S=Xt(),{getHighWaterMark:I,getDefaultHighWaterMark:P}=tn(),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:j,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_OUT_OF_RANGE:F,ERR_STREAM_PUSH_AFTER_EOF:$,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:U},AbortError:X}=Ye(),{validateObject:z}=gr(),W=h("kPaused"),{StringDecoder:ne}=ku(),D=Ba();c(ae.prototype,y.prototype),c(ae,y);var G=()=>{},{errorOrDestroy:L}=S,Y=1,pe=2,te=4,ve=8,J=16,R=32,ie=64,V=128,Q=256,Z=512,be=1024,se=2048,M=4096,q=8192,re=16384,he=32768,fe=65536,ye=1<<17,H=1<<18;function ge(C){return{enumerable:!1,get(){return(this.state&C)!==0},set(N){N?this.state|=C:this.state&=~C}}}a(we.prototype,{objectMode:ge(Y),ended:ge(pe),endEmitted:ge(te),reading:ge(ve),constructed:ge(J),sync:ge(R),needReadable:ge(ie),emittedReadable:ge(V),readableListening:ge(Q),resumeScheduled:ge(Z),errorEmitted:ge(be),emitClose:ge(se),autoDestroy:ge(M),destroyed:ge(q),closed:ge(re),closeEmitted:ge(he),multiAwaitDrain:ge(fe),readingMore:ge(ye),dataEmitted:ge(H)});function we(C,N,ke){typeof ke!="boolean"&&(ke=N instanceof yt()),this.state=se|M|J|R,C&&C.objectMode&&(this.state|=Y),ke&&C&&C.readableObjectMode&&(this.state|=Y),this.highWaterMark=C?I(this,C,"readableHighWaterMark",ke):P(!1),this.buffer=new E,this.length=0,this.pipes=[],this.flowing=null,this[W]=null,C&&C.emitClose===!1&&(this.state&=~se),C&&C.autoDestroy===!1&&(this.state&=~M),this.errored=null,this.defaultEncoding=C&&C.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,C&&C.encoding&&(this.decoder=new ne(C.encoding),this.encoding=C.encoding)}function ae(C){if(!(this instanceof ae))return new ae(C);let N=this instanceof yt();this._readableState=new we(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)),y.call(this,C),S.construct(this,()=>{this._readableState.needReadable&&K(this,this._readableState)})}ae.prototype.destroy=S.destroy,ae.prototype._undestroy=S.undestroy,ae.prototype._destroy=function(C,N){N(C)},ae.prototype[b.captureRejectionSymbol]=function(C){this.destroy(C)},ae.prototype[p]=function(){let C;return this.destroyed||(C=this.readableEnded?null:new X,this.destroy(C)),new u((N,ke)=>_(this,Se=>Se&&Se!==C?ke(Se):N(null)))},ae.prototype.push=function(C,N){return Le(this,C,N,!1)},ae.prototype.unshift=function(C,N){return Le(this,C,N,!0)};function Le(C,N,ke,Se){v("readableAddChunk",N);let Ae=C._readableState,Be;if((Ae.state&Y)===0&&(typeof N=="string"?(ke=ke||Ae.defaultEncoding,Ae.encoding!==ke&&(Se&&Ae.encoding?N=m.from(N,ke).toString(Ae.encoding):(N=m.from(N,ke),ke=""))):N instanceof m?ke="":y._isUint8Array(N)?(N=y._uint8ArrayToBuffer(N),ke=""):N!=null&&(Be=new j("chunk",["string","Buffer","Uint8Array"],N))),Be)L(C,Be);else if(N===null)Ae.state&=~ve,ee(C,Ae);else if((Ae.state&Y)!==0||N&&N.length>0)if(Se)if((Ae.state&te)!==0)L(C,new U);else{if(Ae.destroyed||Ae.errored)return!1;f(C,Ae,N,!0)}else if(Ae.ended)L(C,new $);else{if(Ae.destroyed||Ae.errored)return!1;Ae.state&=~ve,Ae.decoder&&!ke?(N=Ae.decoder.write(N),Ae.objectMode||N.length!==0?f(C,Ae,N,!1):K(C,Ae)):f(C,Ae,N,!1)}else Se||(Ae.state&=~ve,K(C,Ae));return!Ae.ended&&(Ae.length<Ae.highWaterMark||Ae.length===0)}function f(C,N,ke,Se){N.flowing&&N.length===0&&!N.sync&&C.listenerCount("data")>0?((N.state&fe)!==0?N.awaitDrainWriters.clear():N.awaitDrainWriters=null,N.dataEmitted=!0,C.emit("data",ke)):(N.length+=N.objectMode?1:ke.length,Se?N.buffer.unshift(ke):N.buffer.push(ke),(N.state&ie)!==0&&de(C)),K(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 ne(C);this._readableState.decoder=N,this._readableState.encoding=this._readableState.decoder.encoding;let ke=this._readableState.buffer,Se="";for(let Ae of ke)Se+=N.write(Ae);return ke.clear(),Se!==""&&ke.push(Se),this._readableState.length=Se.length,this};var x=1073741824;function A(C){if(C>x)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,N){return C<=0||N.length===0&&N.ended?0:(N.state&Y)!==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:i(C)||(C=s(C,10));let N=this._readableState,ke=C;if(C>N.highWaterMark&&(N.highWaterMark=A(C)),C!==0&&(N.state&=~V),C===0&&N.needReadable&&((N.highWaterMark!==0?N.length>=N.highWaterMark:N.length>0)||N.ended))return v("read: emitReadable",N.length,N.ended),N.length===0&&N.ended?at(this):de(this),null;if(C=B(C,N),C===0&&N.ended)return N.length===0&&at(this),null;let Se=(N.state&ie)!==0;if(v("need readable",Se),(N.length===0||N.length-C<N.highWaterMark)&&(Se=!0,v("length less than watermark",Se)),N.ended||N.reading||N.destroyed||N.errored||!N.constructed)Se=!1,v("reading, ended or constructing",Se);else if(Se){v("do read"),N.state|=ve|R,N.length===0&&(N.state|=ie);try{this._read(N.highWaterMark)}catch(Be){L(this,Be)}N.state&=~R,N.reading||(C=B(ke,N))}let Ae;return C>0?Ae=qt(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&&at(this)),Ae!==null&&!N.errorEmitted&&!N.closeEmitted&&(N.dataEmitted=!0,this.emit("data",Ae)),Ae};function ee(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,xe(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(xe,C))}function xe(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,ot(C)}function K(C,N){!N.readingMore&&N.constructed&&(N.readingMore=!0,t.nextTick(oe,C,N))}function oe(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,Se=this._readableState;Se.pipes.length===1&&(Se.multiAwaitDrain||(Se.multiAwaitDrain=!0,Se.awaitDrainWriters=new d(Se.awaitDrainWriters?[Se.awaitDrainWriters]:[]))),Se.pipes.push(C),v("pipe count=%d opts=%j",Se.pipes.length,N);let Ae=(!N||N.end!==!1)&&C!==t.stdout&&C!==t.stderr?Ge:Mt;Se.endEmitted?t.nextTick(Ae):ke.once("end",Ae),C.on("unpipe",Be);function Be(ct,ft){v("onunpipe"),ct===ke&&ft&&ft.hasUnpiped===!1&&(ft.hasUnpiped=!0,nr())}function Ge(){v("onend"),C.end()}let et,rr=!1;function nr(){v("cleanup"),C.removeListener("close",lt),C.removeListener("finish",St),et&&C.removeListener("drain",et),C.removeListener("error",Lt),C.removeListener("unpipe",Be),ke.removeListener("end",Ge),ke.removeListener("end",Mt),ke.removeListener("data",vr),rr=!0,et&&Se.awaitDrainWriters&&(!C._writableState||C._writableState.needDrain)&&et()}function ir(){rr||(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()),et||(et=Ie(ke,C),C.on("drain",et))}ke.on("data",vr);function vr(ct){v("ondata");let ft=C.write(ct);v("dest.write",ft),ft===!1&&ir()}function Lt(ct){if(v("onerror",ct),Mt(),C.removeListener("error",Lt),C.listenerCount("error")===0){let ft=C._writableState||C._readableState;ft&&!ft.errorEmitted?L(C,ct):C.emit("error",ct)}}w(C,"error",Lt);function lt(){C.removeListener("finish",St),Mt()}C.once("close",lt);function St(){v("onfinish"),C.removeListener("close",lt),Mt()}C.once("finish",St);function Mt(){v("unpipe"),ke.unpipe(C)}return C.emit("pipe",ke),C.writableNeedDrain===!0?ir():Se.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 Be=0;Be<Ae.length;Be++)Ae[Be].emit("unpipe",this,{hasUnpiped:!1});return this}let Se=r(N.pipes,C);return Se===-1?this:(N.pipes.splice(Se,1),N.pipes.length===0&&this.pause(),C.emit("unpipe",this,ke),this)},ae.prototype.on=function(C,N){let ke=y.prototype.on.call(this,C,N),Se=this._readableState;return C==="data"?(Se.readableListening=this.listenerCount("readable")>0,Se.flowing!==!1&&this.resume()):C==="readable"&&!Se.endEmitted&&!Se.readableListening&&(Se.readableListening=Se.needReadable=!0,Se.flowing=!1,Se.emittedReadable=!1,v("on readable",Se.length,Se.reading),Se.length?de(this):Se.reading||t.nextTick(Oe,this)),ke},ae.prototype.addListener=ae.prototype.on,ae.prototype.removeListener=function(C,N){let ke=y.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=y.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&t.nextTick(Te,this),N};function Te(C){let N=C._readableState;N.readableListening=C.listenerCount("readable")>0,N.resumeScheduled&&N[W]===!1?N.flowing=!0:C.listenerCount("data")>0?C.resume():N.readableListening||(N.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,N){N.resumeScheduled||(N.resumeScheduled=!0,t.nextTick(it,C,N))}function it(C,N){v("resume",N.reading),N.reading||C.read(0),N.resumeScheduled=!1,C.emit("resume"),ot(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 ot(C){let N=C._readableState;for(v("flow",N.flowing);N.flowing&&C.read()!==null;);}ae.prototype.wrap=function(C){let N=!1;C.on("data",Se=>{!this.push(Se)&&C.pause&&(N=!0,C.pause())}),C.on("end",()=>{this.push(null)}),C.on("error",Se=>{L(this,Se)}),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 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 He(this)},ae.prototype.iterator=function(C){return C!==void 0&&z(C,"options"),He(this,C)};function He(C,N){typeof C.read!="function"&&(C=ae.wrap(C,{objectMode:!0}));let ke=st(C,N);return ke.stream=C,ke}async function*st(C,N){let ke=G;function Se(Ge){this===C?(ke(),ke=G):ke=Ge}C.on("readable",Se);let Ae,Be=_(C,{writable:!1},Ge=>{Ae=Ge?O(Ae,Ge):null,ke(),ke=G});try{for(;;){let Ge=C.destroyed?null:C.read();if(Ge!==null)yield Ge;else{if(Ae)throw Ae;if(Ae===null)return;await new u(Se)}}}catch(Ge){throw Ae=O(Ae,Ge),Ae}finally{(Ae||N?.destroyOnReturn!==!1)&&(Ae===void 0||C._readableState.autoDestroy)?S.destroyer(C,null):(C.off("readable",Se),Be())}}a(ae.prototype,{readable:{__proto__:null,get(){let C=this._readableState;return!!C&&C.readable!==!1&&!C.destroyed&&!C.errorEmitted&&!C.endEmitted},set(C){this._readableState&&(this._readableState.readable=!!C)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(C){this._readableState&&(this._readableState.destroyed=C)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),a(we.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[W]!==!1},set(C){this[W]=!!C}}}),ae._fromList=qt;function qt(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 at(C){let N=C._readableState;v("endReadable",N.endEmitted),N.endEmitted||(N.ended=!0,t.nextTick(Xe,N,C))}function Xe(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(yr,N);else if(C.autoDestroy){let ke=N._writableState;(!ke||ke.autoDestroy&&(ke.finished||ke.writable===!1))&&N.destroy()}}}function yr(C){C.writable&&!C.writableEnded&&!C.destroyed&&C.end()}ae.from=function(C,N){return D(ae,C,N)};var Ht;function tr(){return Ht===void 0&&(Ht={}),Ht}ae.fromWeb=function(C,N){return tr().newStreamReadableFromReadableStream(C,N)},ae.toWeb=function(C,N){return tr().newReadableStreamFromStreamReadable(C,N)},ae.wrap=function(C,N){var ke,Se;return new ae({objectMode:(ke=(Se=C.readableObjectMode)!==null&&Se!==void 0?Se:C.objectMode)!==null&&ke!==void 0?ke:!0,...N,destroy(Ae,Be){S.destroyer(C,Ae),Be(Ae)}}).wrap(C)}}),Io=me((o,e)=>{le(),ue(),ce();var t=Bt(),{ArrayPrototypeSlice:r,Error:i,FunctionPrototypeSymbolHasInstance:n,ObjectDefineProperty:s,ObjectDefineProperties:a,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:c,Symbol:u,SymbolHasInstance:d}=Ue();e.exports=z,z.WritableState=U;var{EventEmitter:p}=(Ut(),Re(Pt)),g=Ao().Stream,{Buffer:h}=(qe(),Re(Fe)),b=Xt(),{addAbortSignal:y}=en(),{getHighWaterMark:w,getDefaultHighWaterMark:m}=tn(),{ERR_INVALID_ARG_TYPE:k,ERR_METHOD_NOT_IMPLEMENTED:_,ERR_MULTIPLE_CALLBACK:v,ERR_STREAM_CANNOT_PIPE:E,ERR_STREAM_DESTROYED:S,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:P,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:j}=Ye().codes,{errorOrDestroy:T}=b;l(z.prototype,g.prototype),l(z,g);function F(){}var $=u("kOnFinished");function U(M,q,re){typeof re!="boolean"&&(re=q instanceof yt()),this.objectMode=!!(M&&M.objectMode),re&&(this.objectMode=this.objectMode||!!(M&&M.writableObjectMode)),this.highWaterMark=M?w(this,M,"writableHighWaterMark",re):m(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let he=!!(M&&M.decodeStrings===!1);this.decodeStrings=!he,this.defaultEncoding=M&&M.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,X(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!M||M.emitClose!==!1,this.autoDestroy=!M||M.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[$]=[]}function X(M){M.buffered=[],M.bufferedIndex=0,M.allBuffers=!0,M.allNoop=!0}U.prototype.getBuffer=function(){return r(this.buffered,this.bufferedIndex)},s(U.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function z(M){let q=this instanceof yt();if(!q&&!n(z,this))return new z(M);this._writableState=new U(M,this,q),M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final),typeof M.construct=="function"&&(this._construct=M.construct),M.signal&&y(M.signal,this)),g.call(this,M),b.construct(this,()=>{let re=this._writableState;re.writing||ve(this,re),V(this,re)})}s(z,d,{__proto__:null,value:function(M){return n(this,M)?!0:this!==z?!1:M&&M._writableState instanceof U}}),z.prototype.pipe=function(){T(this,new E)};function W(M,q,re,he){let fe=M._writableState;if(typeof re=="function")he=re,re=fe.defaultEncoding;else{if(!re)re=fe.defaultEncoding;else if(re!=="buffer"&&!h.isEncoding(re))throw new j(re);typeof he!="function"&&(he=F)}if(q===null)throw new P;if(!fe.objectMode)if(typeof q=="string")fe.decodeStrings!==!1&&(q=h.from(q,re),re="buffer");else if(q instanceof h)re="buffer";else if(g._isUint8Array(q))q=g._uint8ArrayToBuffer(q),re="buffer";else throw new k("chunk",["string","Buffer","Uint8Array"],q);let ye;return fe.ending?ye=new O:fe.destroyed&&(ye=new S("write")),ye?(t.nextTick(he,ye),T(M,ye,!0),ye):(fe.pendingcb++,ne(M,fe,q,re,he))}z.prototype.write=function(M,q,re){return W(this,M,q,re)===!0},z.prototype.cork=function(){this._writableState.corked++},z.prototype.uncork=function(){let M=this._writableState;M.corked&&(M.corked--,M.writing||ve(this,M))},z.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=c(M)),!h.isEncoding(M))throw new j(M);return this._writableState.defaultEncoding=M,this};function ne(M,q,re,he,fe){let ye=q.objectMode?1:re.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:re,encoding:he,callback:fe}),q.allBuffers&&he!=="buffer"&&(q.allBuffers=!1),q.allNoop&&fe!==F&&(q.allNoop=!1)):(q.writelen=ye,q.writecb=fe,q.writing=!0,q.sync=!0,M._write(re,he,q.onwrite),q.sync=!1),H&&!q.errored&&!q.destroyed}function D(M,q,re,he,fe,ye,H){q.writelen=he,q.writecb=H,q.writing=!0,q.sync=!0,q.destroyed?q.onwrite(new S("write")):re?M._writev(fe,q.onwrite):M._write(fe,ye,q.onwrite),q.sync=!1}function G(M,q,re,he){--q.pendingcb,he(re),te(q),T(M,re)}function L(M,q){let re=M._writableState,he=re.sync,fe=re.writecb;if(typeof fe!="function"){T(M,new v);return}re.writing=!1,re.writecb=null,re.length-=re.writelen,re.writelen=0,q?(q.stack,re.errored||(re.errored=q),M._readableState&&!M._readableState.errored&&(M._readableState.errored=q),he?t.nextTick(G,M,re,q,fe):G(M,re,q,fe)):(re.buffered.length>re.bufferedIndex&&ve(M,re),he?re.afterWriteTickInfo!==null&&re.afterWriteTickInfo.cb===fe?re.afterWriteTickInfo.count++:(re.afterWriteTickInfo={count:1,cb:fe,stream:M,state:re},t.nextTick(Y,re.afterWriteTickInfo)):pe(M,re,1,fe))}function Y({stream:M,state:q,count:re,cb:he}){return q.afterWriteTickInfo=null,pe(M,q,re,he)}function pe(M,q,re,he){for(!q.ending&&!M.destroyed&&q.length===0&&q.needDrain&&(q.needDrain=!1,M.emit("drain"));re-- >0;)q.pendingcb--,he();q.destroyed&&te(q),V(M,q)}function te(M){if(M.writing)return;for(let fe=M.bufferedIndex;fe<M.buffered.length;++fe){var q;let{chunk:ye,callback:H}=M.buffered[fe],ge=M.objectMode?1:ye.length;M.length-=ge,H((q=M.errored)!==null&&q!==void 0?q:new S("write"))}let re=M[$].splice(0);for(let fe=0;fe<re.length;fe++){var he;re[fe]((he=M.errored)!==null&&he!==void 0?he:new S("end"))}X(M)}function ve(M,q){if(q.corked||q.bufferProcessing||q.destroyed||!q.constructed)return;let{buffered:re,bufferedIndex:he,objectMode:fe}=q,ye=re.length-he;if(!ye)return;let H=he;if(q.bufferProcessing=!0,ye>1&&M._writev){q.pendingcb-=ye-1;let ge=q.allNoop?F:ae=>{for(let Le=H;Le<re.length;++Le)re[Le].callback(ae)},we=q.allNoop&&H===0?re:r(re,H);we.allBuffers=q.allBuffers,D(M,q,!0,q.length,we,"",ge),X(q)}else{do{let{chunk:ge,encoding:we,callback:ae}=re[H];re[H++]=null;let Le=fe?1:ge.length;D(M,q,!1,Le,ge,we,ae)}while(H<re.length&&!q.writing);H===re.length?X(q):H>256?(re.splice(0,H),q.bufferedIndex=0):q.bufferedIndex=H}q.bufferProcessing=!1}z.prototype._write=function(M,q,re){if(this._writev)this._writev([{chunk:M,encoding:q}],re);else throw new _("_write()")},z.prototype._writev=null,z.prototype.end=function(M,q,re){let he=this._writableState;typeof M=="function"?(re=M,M=null,q=null):typeof q=="function"&&(re=q,q=null);let fe;if(M!=null){let ye=W(this,M,q);ye instanceof i&&(fe=ye)}return he.corked&&(he.corked=1,this.uncork()),fe||(!he.errored&&!he.ending?(he.ending=!0,V(this,he,!0),he.ended=!0):he.finished?fe=new I("end"):he.destroyed&&(fe=new S("end"))),typeof re=="function"&&(fe||he.finished?t.nextTick(re,fe):he[$].push(re)),this};function J(M){return M.ending&&!M.destroyed&&M.constructed&&M.length===0&&!M.errored&&M.buffered.length===0&&!M.finished&&!M.writing&&!M.errorEmitted&&!M.closeEmitted}function R(M,q){let re=!1;function he(fe){if(re){T(M,fe??v());return}if(re=!0,q.pendingcb--,fe){let ye=q[$].splice(0);for(let H=0;H<ye.length;H++)ye[H](fe);T(M,fe,q.sync)}else J(q)&&(q.prefinished=!0,M.emit("prefinish"),q.pendingcb++,t.nextTick(Q,M,q))}q.sync=!0,q.pendingcb++;try{M._final(he)}catch(fe){he(fe)}q.sync=!1}function ie(M,q){!q.prefinished&&!q.finalCalled&&(typeof M._final=="function"&&!q.destroyed?(q.finalCalled=!0,R(M,q)):(q.prefinished=!0,M.emit("prefinish")))}function V(M,q,re){J(q)&&(ie(M,q),q.pendingcb===0&&(re?(q.pendingcb++,t.nextTick((he,fe)=>{J(fe)?Q(he,fe):fe.pendingcb--},M,q)):J(q)&&(q.pendingcb++,Q(M,q))))}function Q(M,q){q.pendingcb--,q.finished=!0;let re=q[$].splice(0);for(let he=0;he<re.length;he++)re[he]();if(M.emit("finish"),q.autoDestroy){let he=M._readableState;(!he||he.autoDestroy&&(he.endEmitted||he.readable===!1))&&M.destroy()}}a(z.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(M){this._writableState&&(this._writableState.destroyed=M)}},writable:{__proto__:null,get(){let M=this._writableState;return!!M&&M.writable!==!1&&!M.destroyed&&!M.errored&&!M.ending&&!M.ended},set(M){this._writableState&&(this._writableState.writable=!!M)}},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 M=this._writableState;return M?!M.destroyed&&!M.ending&&M.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 Z=b.destroy;z.prototype.destroy=function(M,q){let re=this._writableState;return!re.destroyed&&(re.bufferedIndex<re.buffered.length||re[$].length)&&t.nextTick(te,re),Z.call(this,M,q),this},z.prototype._undestroy=b.undestroy,z.prototype._destroy=function(M,q){q(M)},z.prototype[p.captureRejectionSymbol]=function(M){this.destroy(M)};var be;function se(){return be===void 0&&(be={}),be}z.fromWeb=function(M,q){return se().newStreamWritableFromWritableStream(M,q)},z.toWeb=function(M){return se().newWritableStreamFromStreamWritable(M)}}),xu=me((o,e)=>{le(),ue(),ce();var t=Bt(),r=(qe(),Re(Fe)),{isReadable:i,isWritable:n,isIterable:s,isNodeStream:a,isReadableNodeStream:l,isWritableNodeStream:c,isDuplexNodeStream:u,isReadableStream:d,isWritableStream:p}=wt(),g=Ot(),{AbortError:h,codes:{ERR_INVALID_ARG_TYPE:b,ERR_INVALID_RETURN_VALUE:y}}=Ye(),{destroyer:w}=Xt(),m=yt(),k=rn(),_=Io(),{createDeferredPromise:v}=Je(),E=Ba(),S=globalThis.Blob||r.Blob,I=typeof S<"u"?function($){return $ instanceof S}:function($){return!1},P=globalThis.AbortController||pr().AbortController,{FunctionPrototypeCall:O}=Ue(),j=class extends m{constructor($){super($),$?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),$?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};e.exports=function $(U,X){if(u(U))return U;if(l(U))return F({readable:U});if(c(U))return F({writable:U});if(a(U))return F({writable:!1,readable:!1});if(d(U))return F({readable:k.fromWeb(U)});if(p(U))return F({writable:_.fromWeb(U)});if(typeof U=="function"){let{value:W,write:ne,final:D,destroy:G}=T(U);if(s(W))return E(j,W,{objectMode:!0,write:ne,final:D,destroy:G});let L=W?.then;if(typeof L=="function"){let Y,pe=O(L,W,te=>{if(te!=null)throw new y("nully","body",te)},te=>{w(Y,te)});return Y=new j({objectMode:!0,readable:!1,write:ne,final(te){D(async()=>{try{await pe,t.nextTick(te,null)}catch(ve){t.nextTick(te,ve)}})},destroy:G})}throw new y("Iterable, AsyncIterable or AsyncFunction",X,W)}if(I(U))return $(U.arrayBuffer());if(s(U))return E(j,U,{objectMode:!0,writable:!1});if(d(U?.readable)&&p(U?.writable))return j.fromWeb(U);if(typeof U?.writable=="object"||typeof U?.readable=="object"){let W=U!=null&&U.readable?l(U?.readable)?U?.readable:$(U.readable):void 0,ne=U!=null&&U.writable?c(U?.writable)?U?.writable:$(U.writable):void 0;return F({readable:W,writable:ne})}let z=U?.then;if(typeof z=="function"){let W;return O(z,U,ne=>{ne!=null&&W.push(ne),W.push(null)},ne=>{w(W,ne)}),W=new j({objectMode:!0,writable:!1,read(){}})}throw new b(X,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],U)};function T($){let{promise:U,resolve:X}=v(),z=new P,W=z.signal;return{value:$((async function*(){for(;;){let ne=U;U=null;let{chunk:D,done:G,cb:L}=await ne;if(t.nextTick(L),G)return;if(W.aborted)throw new h(void 0,{cause:W.reason});({promise:U,resolve:X}=v()),yield D}})(),{signal:W}),write(ne,D,G){let L=X;X=null,L({chunk:ne,done:!1,cb:G})},final(ne){let D=X;X=null,D({done:!0,cb:ne})},destroy(ne,D){z.abort(),D(ne)}}}function F($){let U=$.readable&&typeof $.readable.read!="function"?k.wrap($.readable):$.readable,X=$.writable,z=!!i(U),W=!!n(X),ne,D,G,L,Y;function pe(te){let ve=L;L=null,ve?ve(te):te&&Y.destroy(te)}return Y=new j({readableObjectMode:!!(U!=null&&U.readableObjectMode),writableObjectMode:!!(X!=null&&X.writableObjectMode),readable:z,writable:W}),W&&(g(X,te=>{W=!1,te&&w(U,te),pe(te)}),Y._write=function(te,ve,J){X.write(te,ve)?J():ne=J},Y._final=function(te){X.end(),D=te},X.on("drain",function(){if(ne){let te=ne;ne=null,te()}}),X.on("finish",function(){if(D){let te=D;D=null,te()}})),z&&(g(U,te=>{z=!1,te&&w(U,te),pe(te)}),U.on("readable",function(){if(G){let te=G;G=null,te()}}),U.on("end",function(){Y.push(null)}),Y._read=function(){for(;;){let te=U.read();if(te===null){G=Y._read;return}if(!Y.push(te))return}}),Y._destroy=function(te,ve){!te&&L!==null&&(te=new h),G=null,ne=null,D=null,L===null?ve(te):(L=ve,w(X,te),w(U,te))},Y}}),yt=me((o,e)=>{le(),ue(),ce();var{ObjectDefineProperties:t,ObjectGetOwnPropertyDescriptor:r,ObjectKeys:i,ObjectSetPrototypeOf:n}=Ue();e.exports=l;var s=rn(),a=Io();n(l.prototype,s.prototype),n(l,s);{let p=i(a.prototype);for(let g=0;g<p.length;g++){let h=p[g];l.prototype[h]||(l.prototype[h]=a.prototype[h])}}function l(p){if(!(this instanceof l))return new l(p);s.call(this,p),a.call(this,p),p?(this.allowHalfOpen=p.allowHalfOpen!==!1,p.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),p.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}t(l.prototype,{writable:{__proto__:null,...r(a.prototype,"writable")},writableHighWaterMark:{__proto__:null,...r(a.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...r(a.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...r(a.prototype,"writableBuffer")},writableLength:{__proto__:null,...r(a.prototype,"writableLength")},writableFinished:{__proto__:null,...r(a.prototype,"writableFinished")},writableCorked:{__proto__:null,...r(a.prototype,"writableCorked")},writableEnded:{__proto__:null,...r(a.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...r(a.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(p){this._readableState&&this._writableState&&(this._readableState.destroyed=p,this._writableState.destroyed=p)}}});var c;function u(){return c===void 0&&(c={}),c}l.fromWeb=function(p,g){return u().newStreamDuplexFromReadableWritablePair(p,g)},l.toWeb=function(p){return u().newReadableWritablePairFromDuplex(p)};var d;l.from=function(p){return d||(d=xu()),d(p,"body")}}),Fa=me((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t,Symbol:r}=Ue();e.exports=l;var{ERR_METHOD_NOT_IMPLEMENTED:i}=Ye().codes,n=yt(),{getHighWaterMark:s}=tn();t(l.prototype,n.prototype),t(l,n);var a=r("kCallback");function l(d){if(!(this instanceof l))return new l(d);let p=d?s(this,d,"readableHighWaterMark",!0):null;p===0&&(d={...d,highWaterMark:null,readableHighWaterMark:p,writableHighWaterMark:d.writableHighWaterMark||0}),n.call(this,d),this._readableState.sync=!1,this[a]=null,d&&(typeof d.transform=="function"&&(this._transform=d.transform),typeof d.flush=="function"&&(this._flush=d.flush)),this.on("prefinish",u)}function c(d){typeof this._flush=="function"&&!this.destroyed?this._flush((p,g)=>{if(p){d?d(p):this.destroy(p);return}g!=null&&this.push(g),this.push(null),d&&d()}):(this.push(null),d&&d())}function u(){this._final!==c&&c.call(this)}l.prototype._final=c,l.prototype._transform=function(d,p,g){throw new i("_transform()")},l.prototype._write=function(d,p,g){let h=this._readableState,b=this._writableState,y=h.length;this._transform(d,p,(w,m)=>{if(w){g(w);return}m!=null&&this.push(m),b.ended||y===h.length||h.length<h.highWaterMark?g():this[a]=g})},l.prototype._read=function(){if(this[a]){let d=this[a];this[a]=null,d()}}}),qa=me((o,e)=>{le(),ue(),ce();var{ObjectSetPrototypeOf:t}=Ue();e.exports=i;var r=Fa();t(i.prototype,r.prototype),t(i,r);function i(n){if(!(this instanceof i))return new i(n);r.call(this,n)}i.prototype._transform=function(n,s,a){a(null,n)}}),To=me((o,e)=>{le(),ue(),ce();var t=Bt(),{ArrayIsArray:r,Promise:i,SymbolAsyncIterator:n,SymbolDispose:s}=Ue(),a=Ot(),{once:l}=Je(),c=Xt(),u=yt(),{aggregateTwoErrors:d,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:g,ERR_MISSING_ARGS:h,ERR_STREAM_DESTROYED:b,ERR_STREAM_PREMATURE_CLOSE:y},AbortError:w}=Ye(),{validateFunction:m,validateAbortSignal:k}=gr(),{isIterable:_,isReadable:v,isReadableNodeStream:E,isNodeStream:S,isTransformStream:I,isWebStream:P,isReadableStream:O,isReadableFinished:j}=wt(),T=globalThis.AbortController||pr().AbortController,F,$,U;function X(te,ve,J){let R=!1;te.on("close",()=>{R=!0});let ie=a(te,{readable:ve,writable:J},V=>{R=!V});return{destroy:V=>{R||(R=!0,c.destroyer(te,V||new b("pipe")))},cleanup:ie}}function z(te){return m(te[te.length-1],"streams[stream.length - 1]"),te.pop()}function W(te){if(_(te))return te;if(E(te))return ne(te);throw new p("val",["Readable","Iterable","AsyncIterable"],te)}async function*ne(te){$||($=rn()),yield*$.prototype[n].call(te)}async function D(te,ve,J,{end:R}){let ie,V=null,Q=se=>{if(se&&(ie=se),V){let M=V;V=null,M()}},Z=()=>new i((se,M)=>{ie?M(ie):V=()=>{ie?M(ie):se()}});ve.on("drain",Q);let be=a(ve,{readable:!1},Q);try{ve.writableNeedDrain&&await Z();for await(let se of te)ve.write(se)||await Z();R&&(ve.end(),await Z()),J()}catch(se){J(ie!==se?d(ie,se):se)}finally{be(),ve.off("drain",Q)}}async function G(te,ve,J,{end:R}){I(ve)&&(ve=ve.writable);let ie=ve.getWriter();try{for await(let V of te)await ie.ready,ie.write(V).catch(()=>{});await ie.ready,R&&await ie.close(),J()}catch(V){try{await ie.abort(V),J(V)}catch(Q){J(Q)}}}function L(...te){return Y(te,l(z(te)))}function Y(te,ve,J){if(te.length===1&&r(te[0])&&(te=te[0]),te.length<2)throw new h("streams");let R=new T,ie=R.signal,V=J?.signal,Q=[];k(V,"options.signal");function Z(){fe(new w)}U=U||Je().addAbortListener;let be;V&&(be=U(V,Z));let se,M,q=[],re=0;function he(we){fe(we,--re===0)}function fe(we,ae){var Le;if(we&&(!se||se.code==="ERR_STREAM_PREMATURE_CLOSE")&&(se=we),!(!se&&!ae)){for(;q.length;)q.shift()(se);(Le=be)===null||Le===void 0||Le[s](),R.abort(),ae&&(se||Q.forEach(f=>f()),t.nextTick(ve,se,M))}}let ye;for(let we=0;we<te.length;we++){let ae=te[we],Le=we<te.length-1,f=we>0,x=Le||J?.end!==!1,A=we===te.length-1;if(S(ae)){let B=function(ee){ee&&ee.name!=="AbortError"&&ee.code!=="ERR_STREAM_PREMATURE_CLOSE"&&he(ee)};if(x){let{destroy:ee,cleanup:de}=X(ae,Le,f);q.push(ee),v(ae)&&A&&Q.push(de)}ae.on("error",B),v(ae)&&A&&Q.push(()=>{ae.removeListener("error",B)})}if(we===0)if(typeof ae=="function"){if(ye=ae({signal:ie}),!_(ye))throw new g("Iterable, AsyncIterable or Stream","source",ye)}else _(ae)||E(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:ie}),Le){if(!_(ye,!0))throw new g("AsyncIterable",`transform[${we-1}]`,ye)}else{var ge;F||(F=qa());let B=new F({objectMode:!0}),ee=(ge=ye)===null||ge===void 0?void 0:ge.then;if(typeof ee=="function")re++,ee.call(ye,K=>{M=K,K!=null&&B.write(K),x&&B.end(),t.nextTick(he)},K=>{B.destroy(K),t.nextTick(he,K)});else if(_(ye,!0))re++,D(ye,B,he,{end:x});else if(O(ye)||I(ye)){let K=ye.readable||ye;re++,D(K,B,he,{end:x})}else throw new g("AsyncIterable or Promise","destination",ye);ye=B;let{destroy:de,cleanup:xe}=X(ye,!1,!0);q.push(de),A&&Q.push(xe)}}else if(S(ae)){if(E(ye)){re+=2;let B=pe(ye,ae,he,{end:x});v(ae)&&A&&Q.push(B)}else if(I(ye)||O(ye)){let B=ye.readable||ye;re++,D(B,ae,he,{end:x})}else if(_(ye))re++,D(ye,ae,he,{end:x});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else if(P(ae)){if(E(ye))re++,G(W(ye),ae,he,{end:x});else if(O(ye)||_(ye))re++,G(ye,ae,he,{end:x});else if(I(ye))re++,G(ye.readable,ae,he,{end:x});else throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ye);ye=ae}else ye=u.from(ae)}return(ie!=null&&ie.aborted||V!=null&&V.aborted)&&t.nextTick(Z),ye}function pe(te,ve,J,{end:R}){let ie=!1;if(ve.on("close",()=>{ie||J(new y)}),te.pipe(ve,{end:!1}),R){let V=function(){ie=!0,ve.end()};j(te)?t.nextTick(V):te.once("end",V)}else J();return a(te,{readable:!0,writable:!1},V=>{let Q=te._readableState;V&&V.code==="ERR_STREAM_PREMATURE_CLOSE"&&Q&&Q.ended&&!Q.errored&&!Q.errorEmitted?te.once("end",J).once("error",J):J(V)}),a(ve,{readable:!1,writable:!0},J)}e.exports={pipelineImpl:Y,pipeline:L}}),Ha=me((o,e)=>{le(),ue(),ce();var{pipeline:t}=To(),r=yt(),{destroyer:i}=Xt(),{isNodeStream:n,isReadable:s,isWritable:a,isWebStream:l,isTransformStream:c,isWritableStream:u,isReadableStream:d}=wt(),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:g,ERR_MISSING_ARGS:h}}=Ye(),b=Ot();e.exports=function(...y){if(y.length===0)throw new h("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,_,v,E;function S(T){let F=v;v=null,F?F(T):T?E.destroy(T):!j&&!O&&E.destroy()}let I=y[0],P=t(y,S),O=!!(a(I)||u(I)||c(I)),j=!!(s(P)||d(P)||c(P));if(E=new r({writableObjectMode:!!(I!=null&&I.writableObjectMode),readableObjectMode:!!(P!=null&&P.readableObjectMode),writable:O,readable:j}),O){if(n(I))E._write=function(F,$,U){I.write(F,$)?U():m=U},E._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();E._write=async function($,U,X){try{await F.ready,F.write($).catch(()=>{}),X()}catch(z){X(z)}},E._final=async function($){try{await F.ready,F.close().catch(()=>{}),k=$}catch(U){$(U)}}}let T=c(P)?P.readable:P;b(T,()=>{if(k){let F=k;k=null,F()}})}if(j){if(n(P))P.on("readable",function(){if(_){let T=_;_=null,T()}}),P.on("end",function(){E.push(null)}),E._read=function(){for(;;){let T=P.read();if(T===null){_=E._read;return}if(!E.push(T))return}};else if(l(P)){let T=(c(P)?P.readable:P).getReader();E._read=async function(){for(;;)try{let{value:F,done:$}=await T.read();if(!E.push(F))return;if($){E.push(null);return}}catch{return}}}}return E._destroy=function(T,F){!T&&v!==null&&(T=new p),_=null,m=null,k=null,v===null?F(T):(v=F,n(P)&&i(P,T))},E}}),_u=me((o,e)=>{le(),ue(),ce();var t=globalThis.AbortController||pr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:r,ERR_INVALID_ARG_TYPE:i,ERR_MISSING_ARGS:n,ERR_OUT_OF_RANGE:s},AbortError:a}=Ye(),{validateAbortSignal:l,validateInteger:c,validateObject:u}=gr(),d=Ue().Symbol("kWeak"),p=Ue().Symbol("kResistStopPropagation"),{finished:g}=Ot(),h=Ha(),{addAbortSignalNoValidate:b}=en(),{isWritable:y,isNodeStream:w}=wt(),{deprecate:m}=Je(),{ArrayPrototypePush:k,Boolean:_,MathFloor:v,Number:E,NumberIsNaN:S,Promise:I,PromiseReject:P,PromiseResolve:O,PromisePrototypeThen:j,Symbol:T}=Ue(),F=T("kEmpty"),$=T("kEof");function U(V,Q){if(Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal"),w(V)&&!y(V))throw new r("stream",V,"must be writable");let Z=h(this,V);return Q!=null&&Q.signal&&b(Q.signal,Z),Z}function X(V,Q){if(typeof V!="function")throw new i("fn",["Function","AsyncFunction"],V);Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal");let Z=1;Q?.concurrency!=null&&(Z=v(Q.concurrency));let be=Z-1;return Q?.highWaterMark!=null&&(be=v(Q.highWaterMark)),c(Z,"options.concurrency",1),c(be,"options.highWaterMark",0),be+=Z,(async function*(){let se=Je().AbortSignalAny([Q?.signal].filter(_)),M=this,q=[],re={signal:se},he,fe,ye=!1,H=0;function ge(){ye=!0,we()}function we(){H-=1,ae()}function ae(){fe&&!ye&&H<Z&&q.length<be&&(fe(),fe=null)}async function Le(){try{for await(let f of M){if(ye)return;if(se.aborted)throw new a;try{if(f=V(f,re),f===F)continue;f=O(f)}catch(x){f=P(x)}H+=1,j(f,we,ge),q.push(f),he&&(he(),he=null),!ye&&(q.length>=be||H>=Z)&&await new I(x=>{fe=x})}q.push($)}catch(f){let x=P(f);j(x,we,ge),q.push(x)}finally{ye=!0,he&&(he(),he=null)}}Le();try{for(;;){for(;q.length>0;){let f=await q[0];if(f===$)return;if(se.aborted)throw new a;f!==F&&(yield f),q.shift(),ae()}await new I(f=>{he=f})}}finally{ye=!0,fe&&(fe(),fe=null)}}).call(this)}function z(V=void 0){return V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal"),(async function*(){let Q=0;for await(let be of this){var Z;if(V!=null&&(Z=V.signal)!==null&&Z!==void 0&&Z.aborted)throw new a({cause:V.signal.reason});yield[Q++,be]}}).call(this)}async function W(V,Q=void 0){for await(let Z of L.call(this,V,Q))return!0;return!1}async function ne(V,Q=void 0){if(typeof V!="function")throw new i("fn",["Function","AsyncFunction"],V);return!await W.call(this,async(...Z)=>!await V(...Z),Q)}async function D(V,Q){for await(let Z of L.call(this,V,Q))return Z}async function G(V,Q){if(typeof V!="function")throw new i("fn",["Function","AsyncFunction"],V);async function Z(be,se){return await V(be,se),F}for await(let be of X.call(this,Z,Q));}function L(V,Q){if(typeof V!="function")throw new i("fn",["Function","AsyncFunction"],V);async function Z(be,se){return await V(be,se)?be:F}return X.call(this,Z,Q)}var Y=class extends n{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function pe(V,Q,Z){var be;if(typeof V!="function")throw new i("reducer",["Function","AsyncFunction"],V);Z!=null&&u(Z,"options"),Z?.signal!=null&&l(Z.signal,"options.signal");let se=arguments.length>1;if(Z!=null&&(be=Z.signal)!==null&&be!==void 0&&be.aborted){let fe=new a(void 0,{cause:Z.signal.reason});throw this.once("error",()=>{}),await g(this.destroy(fe)),fe}let M=new t,q=M.signal;if(Z!=null&&Z.signal){let fe={once:!0,[d]:this,[p]:!0};Z.signal.addEventListener("abort",()=>M.abort(),fe)}let re=!1;try{for await(let fe of this){var he;if(re=!0,Z!=null&&(he=Z.signal)!==null&&he!==void 0&&he.aborted)throw new a;se?Q=await V(Q,fe,{signal:q}):(Q=fe,se=!0)}if(!re&&!se)throw new Y}finally{M.abort()}return Q}async function te(V){V!=null&&u(V,"options"),V?.signal!=null&&l(V.signal,"options.signal");let Q=[];for await(let be of this){var Z;if(V!=null&&(Z=V.signal)!==null&&Z!==void 0&&Z.aborted)throw new a(void 0,{cause:V.signal.reason});k(Q,be)}return Q}function ve(V,Q){let Z=X.call(this,V,Q);return(async function*(){for await(let be of Z)yield*be}).call(this)}function J(V){if(V=E(V),S(V))return 0;if(V<0)throw new s("number",">= 0",V);return V}function R(V,Q=void 0){return Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal"),V=J(V),(async function*(){var Z;if(Q!=null&&(Z=Q.signal)!==null&&Z!==void 0&&Z.aborted)throw new a;for await(let se of this){var be;if(Q!=null&&(be=Q.signal)!==null&&be!==void 0&&be.aborted)throw new a;V--<=0&&(yield se)}}).call(this)}function ie(V,Q=void 0){return Q!=null&&u(Q,"options"),Q?.signal!=null&&l(Q.signal,"options.signal"),V=J(V),(async function*(){var Z;if(Q!=null&&(Z=Q.signal)!==null&&Z!==void 0&&Z.aborted)throw new a;for await(let se of this){var be;if(Q!=null&&(be=Q.signal)!==null&&be!==void 0&&be.aborted)throw new a;if(V-- >0&&(yield se),V<=0)return}}).call(this)}e.exports.streamReturningOperators={asIndexedPairs:m(z,"readable.asIndexedPairs will be removed in a future version."),drop:R,filter:L,flatMap:ve,map:X,take:ie,compose:U},e.exports.promiseReturningOperators={every:ne,forEach:G,reduce:pe,toArray:te,some:W,find:D}}),Wa=me((o,e)=>{le(),ue(),ce();var{ArrayPrototypePop:t,Promise:r}=Ue(),{isIterable:i,isNodeStream:n,isWebStream:s}=wt(),{pipelineImpl:a}=To(),{finished:l}=Ot();za();function c(...u){return new r((d,p)=>{let g,h,b=u[u.length-1];if(b&&typeof b=="object"&&!n(b)&&!i(b)&&!s(b)){let y=t(u);g=y.signal,h=y.end}a(u,(y,w)=>{y?p(y):d(w)},{signal:g,end:h})})}e.exports={finished:l,pipeline:c}}),za=me((o,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Re(Fe)),{ObjectDefineProperty:r,ObjectKeys:i,ReflectApply:n}=Ue(),{promisify:{custom:s}}=Je(),{streamReturningOperators:a,promiseReturningOperators:l}=_u(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:c}}=Ye(),u=Ha(),{setDefaultHighWaterMark:d,getDefaultHighWaterMark:p}=tn(),{pipeline:g}=To(),{destroyer:h}=Xt(),b=Ot(),y=Wa(),w=wt(),m=e.exports=Ao().Stream;m.isDestroyed=w.isDestroyed,m.isDisturbed=w.isDisturbed,m.isErrored=w.isErrored,m.isReadable=w.isReadable,m.isWritable=w.isWritable,m.Readable=rn();for(let _ of i(a)){let v=function(...S){if(new.target)throw c();return m.Readable.from(n(E,this,S))},E=a[_];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,_,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}for(let _ of i(l)){let v=function(...S){if(new.target)throw c();return n(E,this,S)},E=l[_];r(v,"name",{__proto__:null,value:E.name}),r(v,"length",{__proto__:null,value:E.length}),r(m.Readable.prototype,_,{__proto__:null,value:v,enumerable:!1,configurable:!0,writable:!0})}m.Writable=Io(),m.Duplex=yt(),m.Transform=Fa(),m.PassThrough=qa(),m.pipeline=g;var{addAbortSignal:k}=en();m.addAbortSignal=k,m.finished=b,m.destroy=h,m.compose=u,m.setDefaultHighWaterMark=d,m.getDefaultHighWaterMark=p,r(m,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return y}}),r(g,s,{__proto__:null,enumerable:!0,get(){return y.pipeline}}),r(b,s,{__proto__:null,enumerable:!0,get(){return y.finished}}),m.Stream=m,m._isUint8Array=function(_){return _ instanceof Uint8Array},m._uint8ArrayToBuffer=function(_){return t.from(_.buffer,_.byteOffset,_.byteLength)}}),Ft=me((o,e)=>{le(),ue(),ce();var t=za(),r=Wa(),i=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=i,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get(){return r}}),e.exports.Stream=t.Stream,e.exports.default=e.exports}),Su=me((o,e)=>{le(),ue(),ce(),typeof Object.create=="function"?e.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(t,r){if(r){t.super_=r;var i=function(){};i.prototype=r.prototype,t.prototype=new i,t.prototype.constructor=t}}}),Eu=me((o,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Re(Fe)),r=Symbol.for("BufferList");function i(n){if(!(this instanceof i))return new i(n);i._init.call(this,n)}i._init=function(n){Object.defineProperty(this,r,{value:!0}),this._bufs=[],this.length=0,n&&this.append(n)},i.prototype._new=function(n){return new i(n)},i.prototype._offset=function(n){if(n===0)return[0,0];let s=0;for(let a=0;a<this._bufs.length;a++){let l=s+this._bufs[a].length;if(n<l||a===this._bufs.length-1)return[a,n-s];s=l}},i.prototype._reverseOffset=function(n){let s=n[0],a=n[1];for(let l=0;l<s;l++)a+=this._bufs[l].length;return a},i.prototype.getBuffers=function(){return this._bufs},i.prototype.get=function(n){if(n>this.length||n<0)return;let s=this._offset(n);return this._bufs[s[0]][s[1]]},i.prototype.slice=function(n,s){return typeof n=="number"&&n<0&&(n+=this.length),typeof s=="number"&&s<0&&(s+=this.length),this.copy(null,0,n,s)},i.prototype.copy=function(n,s,a,l){if((typeof a!="number"||a<0)&&(a=0),(typeof l!="number"||l>this.length)&&(l=this.length),a>=this.length||l<=0)return n||t.alloc(0);let c=!!n,u=this._offset(a),d=l-a,p=d,g=c&&s||0,h=u[1];if(a===0&&l===this.length){if(!c)return this._bufs.length===1?this._bufs[0]:t.concat(this._bufs,this.length);for(let b=0;b<this._bufs.length;b++)this._bufs[b].copy(n,g),g+=this._bufs[b].length;return n}if(p<=this._bufs[u[0]].length-h)return c?this._bufs[u[0]].copy(n,s,h,h+p):this._bufs[u[0]].slice(h,h+p);c||(n=t.allocUnsafe(d));for(let b=u[0];b<this._bufs.length;b++){let y=this._bufs[b].length-h;if(p>y)this._bufs[b].copy(n,g,h),g+=y;else{this._bufs[b].copy(n,g,h,h+p),g+=y;break}p-=y,h&&(h=0)}return n.length>g?n.slice(0,g):n},i.prototype.shallowSlice=function(n,s){if(n=n||0,s=typeof s!="number"?this.length:s,n<0&&(n+=this.length),s<0&&(s+=this.length),n===s)return this._new();let a=this._offset(n),l=this._offset(s),c=this._bufs.slice(a[0],l[0]+1);return l[1]===0?c.pop():c[c.length-1]=c[c.length-1].slice(0,l[1]),a[1]!==0&&(c[0]=c[0].slice(a[1])),this._new(c)},i.prototype.toString=function(n,s,a){return this.slice(s,a).toString(n)},i.prototype.consume=function(n){if(n=Math.trunc(n),Number.isNaN(n)||n<=0)return this;for(;this._bufs.length;)if(n>=this._bufs[0].length)n-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(n),this.length-=n;break}return this},i.prototype.duplicate=function(){let n=this._new();for(let s=0;s<this._bufs.length;s++)n.append(this._bufs[s]);return n},i.prototype.append=function(n){return this._attach(n,i.prototype._appendBuffer)},i.prototype.prepend=function(n){return this._attach(n,i.prototype._prependBuffer,!0)},i.prototype._attach=function(n,s,a){if(n==null)return this;if(n.buffer)s.call(this,t.from(n.buffer,n.byteOffset,n.byteLength));else if(Array.isArray(n)){let[l,c]=a?[n.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n.length;u+=c)this._attach(n[u],s,a)}else if(this._isBufferList(n)){let[l,c]=a?[n._bufs.length-1,-1]:[0,1];for(let u=l;u>=0&&u<n._bufs.length;u+=c)this._attach(n._bufs[u],s,a)}else typeof n=="number"&&(n=n.toString()),s.call(this,t.from(n));return this},i.prototype._appendBuffer=function(n){this._bufs.push(n),this.length+=n.length},i.prototype._prependBuffer=function(n){this._bufs.unshift(n),this.length+=n.length},i.prototype.indexOf=function(n,s,a){if(a===void 0&&typeof s=="string"&&(a=s,s=void 0),typeof n=="function"||Array.isArray(n))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof n=="number"?n=t.from([n]):typeof n=="string"?n=t.from(n,a):this._isBufferList(n)?n=n.slice():Array.isArray(n.buffer)?n=t.from(n.buffer,n.byteOffset,n.byteLength):t.isBuffer(n)||(n=t.from(n)),s=Number(s||0),isNaN(s)&&(s=0),s<0&&(s=this.length+s),s<0&&(s=0),n.length===0)return s>this.length?this.length:s;let l=this._offset(s),c=l[0],u=l[1];for(;c<this._bufs.length;c++){let d=this._bufs[c];for(;u<d.length;)if(d.length-u>=n.length){let p=d.indexOf(n,u);if(p!==-1)return this._reverseOffset([c,p]);u=d.length-n.length+1}else{let p=this._reverseOffset([c,u]);if(this._match(p,n))return p;u++}u=0}return-1},i.prototype._match=function(n,s){if(this.length-n<s.length)return!1;for(let a=0;a<s.length;a++)if(this.get(n+a)!==s[a])return!1;return!0},(function(){let n={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let s in n)(function(a){n[a]===null?i.prototype[a]=function(l,c){return this.slice(l,l+c)[a](0,c)}:i.prototype[a]=function(l=0){return this.slice(l,l+n[a])[a](0)}})(s)})(),i.prototype._isBufferList=function(n){return n instanceof i||i.isBufferList(n)},i.isBufferList=function(n){return n!=null&&n[r]},e.exports=i}),Au=me((o,e)=>{le(),ue(),ce();var t=Ft().Duplex,r=Su(),i=Eu();function n(s){if(!(this instanceof n))return new n(s);if(typeof s=="function"){this._callback=s;let a=(function(l){this._callback&&(this._callback(l),this._callback=null)}).bind(this);this.on("pipe",function(l){l.on("error",a)}),this.on("unpipe",function(l){l.removeListener("error",a)}),s=null}i._init.call(this,s),t.call(this)}r(n,t),Object.assign(n.prototype,i.prototype),n.prototype._new=function(s){return new n(s)},n.prototype._write=function(s,a,l){this._appendBuffer(s),typeof l=="function"&&l()},n.prototype._read=function(s){if(!this.length)return this.push(null);s=Math.min(s,this.length),this.push(this.slice(0,s)),this.consume(s)},n.prototype.end=function(s){t.prototype.end.call(this,s),this._callback&&(this._callback(null,this.slice()),this._callback=null)},n.prototype._destroy=function(s,a){this._bufs.length=0,this.length=0,a(s)},n.prototype._isBufferList=function(s){return s instanceof n||s instanceof i||n.isBufferList(s)},n.isBufferList=i.isBufferList,e.exports=n,e.exports.BufferListStream=n,e.exports.BufferList=i}),Iu=me((o,e)=>{le(),ue(),ce();var t=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};e.exports=t}),Va=me((o,e)=>{le(),ue(),ce();var t=e.exports,{Buffer:r}=(qe(),Re(Fe));t.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},t.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},t.requiredHeaderFlagsErrors={};for(let n in t.requiredHeaderFlags){let s=t.requiredHeaderFlags[n];t.requiredHeaderFlagsErrors[n]="Invalid header flag bits, must be 0x"+s.toString(16)+" for "+t.types[n]+" packet"}t.codes={};for(let n in t.types){let s=t.types[n];t.codes[s]=n}t.CMD_SHIFT=4,t.CMD_MASK=240,t.DUP_MASK=8,t.QOS_MASK=3,t.QOS_SHIFT=1,t.RETAIN_MASK=1,t.VARBYTEINT_MASK=127,t.VARBYTEINT_FIN_MASK=128,t.VARBYTEINT_MAX=268435455,t.SESSIONPRESENT_MASK=1,t.SESSIONPRESENT_HEADER=r.from([t.SESSIONPRESENT_MASK]),t.CONNACK_HEADER=r.from([t.codes.connack<<t.CMD_SHIFT]),t.USERNAME_MASK=128,t.PASSWORD_MASK=64,t.WILL_RETAIN_MASK=32,t.WILL_QOS_MASK=24,t.WILL_QOS_SHIFT=3,t.WILL_FLAG_MASK=4,t.CLEAN_SESSION_MASK=2,t.CONNECT_HEADER=r.from([t.codes.connect<<t.CMD_SHIFT]),t.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},t.propertiesCodes={};for(let n in t.properties){let s=t.properties[n];t.propertiesCodes[s]=n}t.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"};function i(n){return[0,1,2].map(s=>[0,1].map(a=>[0,1].map(l=>{let c=r.alloc(1);return c.writeUInt8(t.codes[n]<<t.CMD_SHIFT|(a?t.DUP_MASK:0)|s<<t.QOS_SHIFT|l,0,!0),c})))}t.PUBLISH_HEADER=i("publish"),t.SUBSCRIBE_HEADER=i("subscribe"),t.SUBSCRIBE_OPTIONS_QOS_MASK=3,t.SUBSCRIBE_OPTIONS_NL_MASK=1,t.SUBSCRIBE_OPTIONS_NL_SHIFT=2,t.SUBSCRIBE_OPTIONS_RAP_MASK=1,t.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,t.SUBSCRIBE_OPTIONS_RH_MASK=3,t.SUBSCRIBE_OPTIONS_RH_SHIFT=4,t.SUBSCRIBE_OPTIONS_RH=[0,16,32],t.SUBSCRIBE_OPTIONS_NL=4,t.SUBSCRIBE_OPTIONS_RAP=8,t.SUBSCRIBE_OPTIONS_QOS=[0,1,2],t.UNSUBSCRIBE_HEADER=i("unsubscribe"),t.ACKS={unsuback:i("unsuback"),puback:i("puback"),pubcomp:i("pubcomp"),pubrel:i("pubrel"),pubrec:i("pubrec")},t.SUBACK_HEADER=r.from([t.codes.suback<<t.CMD_SHIFT]),t.VERSION3=r.from([3]),t.VERSION4=r.from([4]),t.VERSION5=r.from([5]),t.VERSION131=r.from([131]),t.VERSION132=r.from([132]),t.QOS=[0,1,2].map(n=>r.from([n])),t.EMPTY={pingreq:r.from([t.codes.pingreq<<4,0]),pingresp:r.from([t.codes.pingresp<<4,0]),disconnect:r.from([t.codes.disconnect<<4,0])},t.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},t.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},t.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},t.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},t.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}}),Tu=me((o,e)=>{le(),ue(),ce();var t=1e3,r=t*60,i=r*60,n=i*24,s=n*7,a=n*365.25;e.exports=function(p,g){g=g||{};var h=typeof p;if(h==="string"&&p.length>0)return l(p);if(h==="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 h=parseFloat(g[1]),b=(g[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return h*a;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*n;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*r;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}}}function c(p){var g=Math.abs(p);return g>=n?Math.round(p/n)+"d":g>=i?Math.round(p/i)+"h":g>=r?Math.round(p/r)+"m":g>=t?Math.round(p/t)+"s":p+"ms"}function u(p){var g=Math.abs(p);return g>=n?d(p,g,n,"day"):g>=i?d(p,g,i,"hour"):g>=r?d(p,g,r,"minute"):g>=t?d(p,g,t,"second"):p+" ms"}function d(p,g,h,b){var y=g>=h*1.5;return Math.round(p/h)+" "+b+(y?"s":"")}}),Cu=me((o,e)=>{le(),ue(),ce();function t(r){n.debug=n,n.default=n,n.coerce=d,n.disable=c,n.enable=a,n.enabled=u,n.humanize=Tu(),n.destroy=p,Object.keys(r).forEach(g=>{n[g]=r[g]}),n.names=[],n.skips=[],n.formatters={};function i(g){let h=0;for(let b=0;b<g.length;b++)h=(h<<5)-h+g.charCodeAt(b),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=i;function n(g){let h,b=null,y,w;function m(...k){if(!m.enabled)return;let _=m,v=Number(new Date),E=v-(h||v);_.diff=E,_.prev=h,_.curr=v,h=v,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let S=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(I,P)=>{if(I==="%%")return"%";S++;let O=n.formatters[P];if(typeof O=="function"){let j=k[S];I=O.call(_,j),k.splice(S,1),S--}return I}),n.formatArgs.call(_,k),(_.log||n.log).apply(_,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,h){let b=n(this.namespace+(typeof h>"u"?":":h)+g);return b.log=this.log,b}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let h=(typeof g=="string"?g:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of h)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function l(g,h){let b=0,y=0,w=-1,m=0;for(;b<g.length;)if(y<h.length&&(h[y]===g[b]||h[y]==="*"))h[y]==="*"?(w=y,m=b,y++):(b++,y++);else if(w!==-1)y=w+1,m++,b=m;else return!1;for(;y<h.length&&h[y]==="*";)y++;return y===h.length}function c(){let g=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),g}function u(g){for(let h of n.skips)if(l(g,h))return!1;for(let h of n.names)if(l(g,h))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}),vt=me((o,e)=>{le(),ue(),ce(),o.formatArgs=r,o.save=i,o.load=n,o.useColors=t,o.storage=s(),o.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),o.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;let c="color: "+this.color;l.splice(1,0,c,"color: inherit");let u=0,d=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(u++,p==="%c"&&(d=u))}),l.splice(d,0,c)}o.log=console.debug||console.log||(()=>{});function i(l){try{l?o.storage.setItem("debug",l):o.storage.removeItem("debug")}catch{}}function n(){let l;try{l=o.storage.getItem("debug")||o.storage.getItem("DEBUG")}catch{}return!l&&typeof je<"u"&&"env"in je&&(l=je.env.DEBUG),l}function s(){try{return localStorage}catch{}}e.exports=Cu()(o);var{formatters:a}=e.exports;a.j=function(l){try{return JSON.stringify(l)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}}),Pu=me((o,e)=>{le(),ue(),ce();var t=Au(),{EventEmitter:r}=(Ut(),Re(Pt)),i=Iu(),n=Va(),s=vt()("mqtt-packet:parser"),a=class Ci extends r{constructor(){super(),this.parser=this.constructor.parser}static parser(c){return this instanceof Ci?(this.settings=c||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new Ci().parser(c)}_resetState(){s("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new i,this.error=null,this._list=t(),this._stateCounter=0}parse(c){for(this.error&&this._resetState(),this._list.append(c),s("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,s("parse: state complete. _stateCounter is now: %d",this._stateCounter),s("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return s("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let c=this._list.readUInt8(0),u=c>>n.CMD_SHIFT;this.packet.cmd=n.types[u];let d=c&15,p=n.requiredHeaderFlags[u];return p!=null&&d!==p?this._emitError(new Error(n.requiredHeaderFlagsErrors[u])):(this.packet.retain=(c&n.RETAIN_MASK)!==0,this.packet.qos=c>>n.QOS_SHIFT&n.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(c&n.DUP_MASK)!==0,s("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let c=this._parseVarByteNum(!0);return c&&(this.packet.length=c.value,this._list.consume(c.bytes)),s("_parseLength %d",c.value),!!c}_parsePayload(){s("_parsePayload: payload %O",this._list);let c=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}c=!0}return s("_parsePayload complete result: %s",c),c}_parseConnect(){s("_parseConnect");let c,u,d,p,g={},h=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(h.protocolId=b,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(h.protocolVersion=this._list.readUInt8(this._pos),h.protocolVersion>=128&&(h.bridgeMode=!0,h.protocolVersion=h.protocolVersion-128),h.protocolVersion!==3&&h.protocolVersion!==4&&h.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)h.will={},h.will.retain=y,h.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(h.clean=(this._list.readUInt8(this._pos)&n.CLEAN_SESSION_MASK)!==0,this._pos++,h.keepalive=this._parseNum(),h.keepalive===-1)return this._emitError(new Error("Packet too short"));if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.properties=k)}let m=this._parseString();if(m===null)return this._emitError(new Error("Packet too short"));if(h.clientId=m,s("_parseConnect: packet.clientId: %s",h.clientId),g.will){if(h.protocolVersion===5){let k=this._parseProperties();Object.getOwnPropertyNames(k).length&&(h.will.properties=k)}if(c=this._parseString(),c===null)return this._emitError(new Error("Cannot parse will topic"));if(h.will.topic=c,s("_parseConnect: packet.will.topic: %s",h.will.topic),u=this._parseBuffer(),u===null)return this._emitError(new Error("Cannot parse will payload"));h.will.payload=u,s("_parseConnect: packet.will.paylaod: %s",h.will.payload)}if(g.username){if(p=this._parseString(),p===null)return this._emitError(new Error("Cannot parse username"));h.username=p,s("_parseConnect: packet.username: %s",h.username)}if(g.password){if(d=this._parseBuffer(),d===null)return this._emitError(new Error("Cannot parse password"));h.password=d}return this.settings=h,s("_parseConnect: complete"),h}_parseConnack(){s("_parseConnack");let c=this.packet;if(this._list.length<1)return null;let u=this._list.readUInt8(this._pos++);if(u>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(c.sessionPresent=!!(u&n.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?c.reasonCode=this._list.readUInt8(this._pos++):c.reasonCode=0;else{if(this._list.length<2)return null;c.returnCode=this._list.readUInt8(this._pos++)}if(c.returnCode===-1||c.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(c.properties=d)}s("_parseConnack: complete")}_parsePublish(){s("_parsePublish");let c=this.packet;if(c.topic=this._parseString(),c.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(c.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}c.payload=this._list.slice(this._pos,c.length),s("_parsePublish: payload from buffer list: %o",c.payload)}}_parseSubscribe(){s("_parseSubscribe");let c=this.packet,u,d,p,g,h,b,y;if(c.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let w=this._parseProperties();Object.getOwnPropertyNames(w).length&&(c.properties=w)}if(c.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<c.length;){if(u=this._parseString(),u===null)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=c.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(d=this._parseByte(),this.settings.protocolVersion===5){if(d&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(d&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(p=d&n.SUBSCRIBE_OPTIONS_QOS_MASK,p>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(b=(d>>n.SUBSCRIBE_OPTIONS_NL_SHIFT&n.SUBSCRIBE_OPTIONS_NL_MASK)!==0,h=(d>>n.SUBSCRIBE_OPTIONS_RAP_SHIFT&n.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,g=d>>n.SUBSCRIBE_OPTIONS_RH_SHIFT&n.SUBSCRIBE_OPTIONS_RH_MASK,g>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));y={topic:u,qos:p},this.settings.protocolVersion===5?(y.nl=b,y.rap=h,y.rh=g):this.settings.bridgeMode&&(y.rh=0,y.rap=!0,y.nl=!0),s("_parseSubscribe: push subscription `%s` to subscription",y),c.subscriptions.push(y)}}}_parseSuback(){s("_parseSuback");let c=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){let u=this._list.readUInt8(this._pos++);if(this.settings.protocolVersion===5){if(!n.MQTT5_SUBACK_CODES[u])return this._emitError(new Error("Invalid suback code"))}else if(u>2&&u!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(u)}}}_parseUnsubscribe(){s("_parseUnsubscribe");let c=this.packet;if(c.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}if(c.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<c.length;){let u=this._parseString();if(u===null)return this._emitError(new Error("Cannot parse topic"));s("_parseUnsubscribe: push topic `%s` to unsubscriptions",u),c.unsubscriptions.push(u)}}}_parseUnsuback(){s("_parseUnsuback");let c=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((this.settings.protocolVersion===3||this.settings.protocolVersion===4)&&c.length!==2)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(c.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(this.settings.protocolVersion===5){let u=this._parseProperties();for(Object.getOwnPropertyNames(u).length&&(c.properties=u),c.granted=[];this._pos<this.packet.length;){let d=this._list.readUInt8(this._pos++);if(!n.MQTT5_UNSUBACK_CODES[d])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(d)}}}_parseConfirmation(){s("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);let c=this.packet;if(this._parseMessageId(),this.settings.protocolVersion===5){if(c.length>2){switch(c.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!n.MQTT5_PUBACK_PUBREC_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!n.MQTT5_PUBREL_PUBCOMP_CODES[c.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}s("_parseConfirmation: packet.reasonCode `%d`",c.reasonCode)}else c.reasonCode=0;if(c.length>3){let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}}return!0}_parseDisconnect(){let c=this.packet;if(s("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(c.reasonCode=this._parseByte(),n.MQTT5_DISCONNECT_CODES[c.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):c.reasonCode=0;let u=this._parseProperties();Object.getOwnPropertyNames(u).length&&(c.properties=u)}return s("_parseDisconnect result: true"),!0}_parseAuth(){s("_parseAuth");let c=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(c.reasonCode=this._parseByte(),!n.MQTT5_AUTH_CODES[c.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let u=this._parseProperties();return Object.getOwnPropertyNames(u).length&&(c.properties=u),s("_parseAuth: result: true"),!0}_parseMessageId(){let c=this.packet;return c.messageId=this._parseNum(),c.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(s("_parseMessageId: packet.messageId %d",c.messageId),!0)}_parseString(c){let u=this._parseNum(),d=u+this._pos;if(u===-1||d>this._list.length||d>this.packet.length)return null;let p=this._list.toString("utf8",this._pos,d);return this._pos+=u,s("_parseString: result: %s",p),p}_parseStringPair(){return s("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let c=this._parseNum(),u=c+this._pos;if(c===-1||u>this._list.length||u>this.packet.length)return null;let d=this._list.slice(this._pos,u);return this._pos+=c,s("_parseBuffer: result: %o",d),d}_parseNum(){if(this._list.length-this._pos<2)return-1;let c=this._list.readUInt16BE(this._pos);return this._pos+=2,s("_parseNum: result: %s",c),c}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let c=this._list.readUInt32BE(this._pos);return this._pos+=4,s("_parse4ByteNum: result: %s",c),c}_parseVarByteNum(c){s("_parseVarByteNum");let u=4,d=0,p=1,g=0,h=!1,b,y=this._pos?this._pos:0;for(;d<u&&y+d<this._list.length;){if(b=this._list.readUInt8(y+d++),g+=p*(b&n.VARBYTEINT_MASK),p*=128,(b&n.VARBYTEINT_FIN_MASK)===0){h=!0;break}if(this._list.length<=d)break}return!h&&d===u&&this._list.length>=d&&this._emitError(new Error("Invalid variable byte integer")),y&&(this._pos+=d),h?c?h={bytes:d,value:g}:h=g:h=!1,s("_parseVarByteNum: result: %o",h),h}_parseByte(){let c;return this._pos<this._list.length&&(c=this._list.readUInt8(this._pos),this._pos++),s("_parseByte: result: %o",c),c}_parseByType(c){switch(s("_parseByType: type: %s",c),c){case"byte":return this._parseByte()!==0;case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){s("_parseProperties");let c=this._parseVarByteNum(),u=this._pos+c,d={};for(;this._pos<u;){let p=this._parseByte();if(!p)return this._emitError(new Error("Cannot parse property code type")),!1;let g=n.propertiesCodes[p];if(!g)return this._emitError(new Error("Unknown property")),!1;if(g==="userProperties"){d[g]||(d[g]=Object.create(null));let h=this._parseByType(n.propertiesTypes[g]);if(d[g][h.name])if(Array.isArray(d[g][h.name]))d[g][h.name].push(h.value);else{let b=d[g][h.name];d[g][h.name]=[b],d[g][h.name].push(h.value)}else d[g][h.name]=h.value;continue}d[g]?Array.isArray(d[g])?d[g].push(this._parseByType(n.propertiesTypes[g])):(d[g]=[d[g]],d[g].push(this._parseByType(n.propertiesTypes[g]))):d[g]=this._parseByType(n.propertiesTypes[g])}return d}_newPacket(){return s("_newPacket"),this.packet&&(this._list.consume(this.packet.length),s("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),s("_newPacket: new packet"),this.packet=new i,this._pos=0,!0}_emitError(c){s("_emitError",c),this.error=c,this.emit("error",c)}};e.exports=a}),Ou=me((o,e)=>{le(),ue(),ce();var{Buffer:t}=(qe(),Re(Fe)),r=65536,i={},n=t.isBuffer(t.from([1,2]).subarray(0,1));function s(u){let d=t.allocUnsafe(2);return d.writeUInt8(u>>8,0),d.writeUInt8(u&255,1),d}function a(){for(let u=0;u<r;u++)i[u]=s(u)}function l(u){let d=0,p=0,g=t.allocUnsafe(4);do d=u%128|0,u=u/128|0,u>0&&(d=d|128),g.writeUInt8(d,p++);while(u>0&&p<4);return u>0&&(p=0),n?g.subarray(0,p):g.slice(0,p)}function c(u){let d=t.allocUnsafe(4);return d.writeUInt32BE(u,0),d}e.exports={cache:i,generateCache:a,generateNumber:s,genBufVariableByteInt:l,generate4ByteBuffer:c}}),Lu=me((o,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,i,n,s){if(typeof r!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,l,c;switch(a){case 0:case 1:return je.nextTick(r);case 2:return je.nextTick(function(){r.call(null,i)});case 3:return je.nextTick(function(){r.call(null,i,n)});case 4:return je.nextTick(function(){r.call(null,i,n,s)});default:for(l=new Array(a-1),c=0;c<l.length;)l[c++]=arguments[c];return je.nextTick(function(){r.apply(null,l)})}}}),Ka=me((o,e)=>{le(),ue(),ce();var t=Va(),{Buffer:r}=(qe(),Re(Fe)),i=r.allocUnsafe(0),n=r.from([0]),s=Ou(),a=Lu().nextTick,l=vt()("mqtt-packet:writeToStream"),c=s.cache,u=s.generateNumber,d=s.generateCache,p=s.genBufVariableByteInt,g=s.generate4ByteBuffer,h=z,b=!0;function y(J,R,ie){switch(l("generate called"),R.cork&&(R.cork(),a(w,R)),b&&(b=!1,d()),l("generate: packet.cmd: %s",J.cmd),J.cmd){case"connect":return m(J,R);case"connack":return k(J,R,ie);case"publish":return _(J,R,ie);case"puback":case"pubrec":case"pubrel":case"pubcomp":return v(J,R,ie);case"subscribe":return E(J,R,ie);case"suback":return S(J,R,ie);case"unsubscribe":return I(J,R,ie);case"unsuback":return P(J,R,ie);case"pingreq":case"pingresp":return O(J,R);case"disconnect":return j(J,R,ie);case"auth":return T(J,R,ie);default:return R.destroy(new Error("Unknown command")),!1}}Object.defineProperty(y,"cacheNumbers",{get(){return h===z},set(J){J?((!c||Object.keys(c).length===0)&&(b=!0),h=z):(b=!1,h=W)}});function w(J){J.uncork()}function m(J,R,ie){let V=J||{},Q=V.protocolId||"MQTT",Z=V.protocolVersion||4,be=V.will,se=V.clean,M=V.keepalive||0,q=V.clientId||"",re=V.username,he=V.password,fe=V.properties;se===void 0&&(se=!0);let ye=0;if(typeof Q!="string"&&!r.isBuffer(Q))return R.destroy(new Error("Invalid protocolId")),!1;if(ye+=Q.length+2,Z!==3&&Z!==4&&Z!==5)return R.destroy(new Error("Invalid protocol version")),!1;if(ye+=1,(typeof q=="string"||r.isBuffer(q))&&(q||Z>=4)&&(q||se))ye+=r.byteLength(q)+2;else{if(Z<4)return R.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(se*1===0)return R.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof M!="number"||M<0||M>65535||M%1!==0)return R.destroy(new Error("Invalid keepalive")),!1;ye+=2,ye+=1;let H,ge;if(Z===5){if(H=G(R,fe),!H)return!1;ye+=H.length}if(be){if(typeof be!="object")return R.destroy(new Error("Invalid will")),!1;if(!be.topic||typeof be.topic!="string")return R.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 R.destroy(new Error("Invalid will payload")),!1;if(ge={},Z===5){if(ge=G(R,be.properties),!ge)return!1;ye+=ge.length}}let we=!1;if(re!=null)if(ve(re))we=!0,ye+=r.byteLength(re)+2;else return R.destroy(new Error("Invalid username")),!1;if(he!=null){if(!we)return R.destroy(new Error("Username is required to use password")),!1;if(ve(he))ye+=te(he)+2;else return R.destroy(new Error("Invalid password")),!1}R.write(t.CONNECT_HEADER),$(R,ye),D(R,Q),V.bridgeMode&&(Z+=128),R.write(Z===131?t.VERSION131:Z===132?t.VERSION132:Z===4?t.VERSION4:Z===5?t.VERSION5:t.VERSION3);let ae=0;return ae|=re!=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,R.write(r.from([ae])),h(R,M),Z===5&&H.write(),D(R,q),be&&(Z===5&&ge.write(),U(R,be.topic),D(R,be.payload)),re!=null&&D(R,re),he!=null&&D(R,he),!0}function k(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=V===5?Q.reasonCode:Q.returnCode,be=Q.properties,se=2;if(typeof Z!="number")return R.destroy(new Error("Invalid return code")),!1;let M=null;if(V===5){if(M=G(R,be),!M)return!1;se+=M.length}return R.write(t.CONNACK_HEADER),$(R,se),R.write(Q.sessionPresent?t.SESSIONPRESENT_HEADER:n),R.write(r.from([Z])),M?.write(),!0}function _(J,R,ie){l("publish: packet: %o",J);let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.qos||0,be=Q.retain?t.RETAIN_MASK:0,se=Q.topic,M=Q.payload||i,q=Q.messageId,re=Q.properties,he=0;if(typeof se=="string")he+=r.byteLength(se)+2;else if(r.isBuffer(se))he+=se.length+2;else return R.destroy(new Error("Invalid topic")),!1;if(r.isBuffer(M)?he+=M.length:he+=r.byteLength(M),Z&&typeof q!="number")return R.destroy(new Error("Invalid messageId")),!1;Z&&(he+=2);let fe=null;if(V===5){if(fe=G(R,re),!fe)return!1;he+=fe.length}return R.write(t.PUBLISH_HEADER[Z][Q.dup?1:0][be?1:0]),$(R,he),h(R,te(se)),R.write(se),Z>0&&h(R,q),fe?.write(),l("publish: payload: %o",M),R.write(M)}function v(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.cmd||"puback",be=Q.messageId,se=Q.dup&&Z==="pubrel"?t.DUP_MASK:0,M=0,q=Q.reasonCode,re=Q.properties,he=V===5?3:2;if(Z==="pubrel"&&(M=1),typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;let fe=null;if(V===5&&typeof re=="object"){if(fe=L(R,re,ie,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[Z][M][se][0]),he===3&&(he+=q!==0?1:-1),$(R,he),h(R,be),V===5&&he!==2&&R.write(r.from([q])),fe!==null?fe.write():he===4&&R.write(r.from([0])),!0}function E(J,R,ie){l("subscribe: packet: ");let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.dup?t.DUP_MASK:0,be=Q.messageId,se=Q.subscriptions,M=Q.properties,q=0;if(typeof be!="number")return R.destroy(new Error("Invalid messageId")),!1;q+=2;let re=null;if(V===5){if(re=G(R,M),!re)return!1;q+=re.length}if(typeof se=="object"&&se.length)for(let fe=0;fe<se.length;fe+=1){let ye=se[fe].topic,H=se[fe].qos;if(typeof ye!="string")return R.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if(typeof H!="number")return R.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(V===5){if(typeof(se[fe].nl||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if(typeof(se[fe].rap||!1)!="boolean")return R.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;let ge=se[fe].rh||0;if(typeof ge!="number"||ge>2)return R.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}q+=r.byteLength(ye)+2+1}else return R.destroy(new Error("Invalid subscriptions")),!1;l("subscribe: writing to stream: %o",t.SUBSCRIBE_HEADER),R.write(t.SUBSCRIBE_HEADER[1][Z?1:0][0]),$(R,q),h(R,be),re!==null&&re.write();let he=!0;for(let fe of se){let ye=fe.topic,H=fe.qos,ge=+fe.nl,we=+fe.rap,ae=fe.rh,Le;U(R,ye),Le=t.SUBSCRIBE_OPTIONS_QOS[H],V===5&&(Le|=ge?t.SUBSCRIBE_OPTIONS_NL:0,Le|=we?t.SUBSCRIBE_OPTIONS_RAP:0,Le|=ae?t.SUBSCRIBE_OPTIONS_RH[ae]:0),he=R.write(r.from([Le]))}return he}function S(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.messageId,be=Q.granted,se=Q.properties,M=0;if(typeof Z!="number")return R.destroy(new Error("Invalid messageId")),!1;if(M+=2,typeof be=="object"&&be.length)for(let re=0;re<be.length;re+=1){if(typeof be[re]!="number")return R.destroy(new Error("Invalid qos vector")),!1;M+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let q=null;if(V===5){if(q=L(R,se,ie,M),!q)return!1;M+=q.length}return R.write(t.SUBACK_HEADER),$(R,M),h(R,Z),q!==null&&q.write(),R.write(r.from(be))}function I(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.messageId,be=Q.dup?t.DUP_MASK:0,se=Q.unsubscriptions,M=Q.properties,q=0;if(typeof Z!="number")return R.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 R.destroy(new Error("Invalid unsubscriptions")),!1;q+=r.byteLength(se[fe])+2}else return R.destroy(new Error("Invalid unsubscriptions")),!1;let re=null;if(V===5){if(re=G(R,M),!re)return!1;q+=re.length}R.write(t.UNSUBSCRIBE_HEADER[1][be?1:0][0]),$(R,q),h(R,Z),re!==null&&re.write();let he=!0;for(let fe=0;fe<se.length;fe++)he=U(R,se[fe]);return he}function P(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.messageId,be=Q.dup?t.DUP_MASK:0,se=Q.granted,M=Q.properties,q=Q.cmd,re=0,he=2;if(typeof Z!="number")return R.destroy(new Error("Invalid messageId")),!1;if(V===5)if(typeof se=="object"&&se.length)for(let ye=0;ye<se.length;ye+=1){if(typeof se[ye]!="number")return R.destroy(new Error("Invalid qos vector")),!1;he+=1}else return R.destroy(new Error("Invalid qos vector")),!1;let fe=null;if(V===5){if(fe=L(R,M,ie,he),!fe)return!1;he+=fe.length}return R.write(t.ACKS[q][re][be][0]),$(R,he),h(R,Z),fe!==null&&fe.write(),V===5&&R.write(r.from(se)),!0}function O(J,R,ie){return R.write(t.EMPTY[J.cmd])}function j(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.reasonCode,be=Q.properties,se=V===5?1:0,M=null;if(V===5){if(M=L(R,be,ie,se),!M)return!1;se+=M.length}return R.write(r.from([t.codes.disconnect<<4])),$(R,se),V===5&&R.write(r.from([Z])),M!==null&&M.write(),!0}function T(J,R,ie){let V=ie?ie.protocolVersion:4,Q=J||{},Z=Q.reasonCode,be=Q.properties,se=V===5?1:0;V!==5&&R.destroy(new Error("Invalid mqtt version for auth packet"));let M=L(R,be,ie,se);return M?(se+=M.length,R.write(r.from([t.codes.auth<<4])),$(R,se),R.write(r.from([Z])),M!==null&&M.write(),!0):!1}var F={};function $(J,R){if(R>t.VARBYTEINT_MAX)return J.destroy(new Error(`Invalid variable byte integer: ${R}`)),!1;let ie=F[R];return ie||(ie=p(R),R<16384&&(F[R]=ie)),l("writeVarByteInt: writing to stream: %o",ie),J.write(ie)}function U(J,R){let ie=r.byteLength(R);return h(J,ie),l("writeString: %s",R),J.write(R,"utf8")}function X(J,R,ie){U(J,R),U(J,ie)}function z(J,R){return l("writeNumberCached: number: %d",R),l("writeNumberCached: %o",c[R]),J.write(c[R])}function W(J,R){let ie=u(R);return l("writeNumberGenerated: %o",ie),J.write(ie)}function ne(J,R){let ie=g(R);return l("write4ByteNumber: %o",ie),J.write(ie)}function D(J,R){typeof R=="string"?U(J,R):R?(h(J,R.length),J.write(R)):h(J,0)}function G(J,R){if(typeof R!="object"||R.length!=null)return{length:1,write(){pe(J,{},0)}};let ie=0;function V(Q,Z){let be=t.propertiesTypes[Q],se=0;switch(be){case"byte":{if(typeof Z!="boolean")return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=2;break}case"int8":{if(typeof Z!="number"||Z<0||Z>255)return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=2;break}case"binary":{if(Z&&Z===null)return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=1+r.byteLength(Z)+2;break}case"int16":{if(typeof Z!="number"||Z<0||Z>65535)return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=3;break}case"int32":{if(typeof Z!="number"||Z<0||Z>4294967295)return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=5;break}case"var":{if(typeof Z!="number"||Z<0||Z>268435455)return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=1+r.byteLength(p(Z));break}case"string":{if(typeof Z!="string")return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=3+r.byteLength(Z.toString());break}case"pair":{if(typeof Z!="object")return J.destroy(new Error(`Invalid ${Q}: ${Z}`)),!1;se+=Object.getOwnPropertyNames(Z).reduce((M,q)=>{let re=Z[q];return Array.isArray(re)?M+=re.reduce((he,fe)=>(he+=3+r.byteLength(q.toString())+2+r.byteLength(fe.toString()),he),0):M+=3+r.byteLength(q.toString())+2+r.byteLength(Z[q].toString()),M},0);break}default:return J.destroy(new Error(`Invalid property ${Q}: ${Z}`)),!1}return se}if(R)for(let Q in R){let Z=0,be=0,se=R[Q];if(se!==void 0){if(Array.isArray(se))for(let M=0;M<se.length;M++){if(be=V(Q,se[M]),!be)return!1;Z+=be}else{if(be=V(Q,se),!be)return!1;Z=be}if(!Z)return!1;ie+=Z}}return{length:r.byteLength(p(ie))+ie,write(){pe(J,R,ie)}}}function L(J,R,ie,V){let Q=["reasonString","userProperties"],Z=ie&&ie.properties&&ie.properties.maximumPacketSize?ie.properties.maximumPacketSize:0,be=G(J,R);if(Z)for(;V+be.length>Z;){let se=Q.shift();if(se&&R[se])delete R[se],be=G(J,R);else return!1}return be}function Y(J,R,ie){switch(t.propertiesTypes[R]){case"byte":{J.write(r.from([t.properties[R]])),J.write(r.from([+ie]));break}case"int8":{J.write(r.from([t.properties[R]])),J.write(r.from([ie]));break}case"binary":{J.write(r.from([t.properties[R]])),D(J,ie);break}case"int16":{J.write(r.from([t.properties[R]])),h(J,ie);break}case"int32":{J.write(r.from([t.properties[R]])),ne(J,ie);break}case"var":{J.write(r.from([t.properties[R]])),$(J,ie);break}case"string":{J.write(r.from([t.properties[R]])),U(J,ie);break}case"pair":{Object.getOwnPropertyNames(ie).forEach(V=>{let Q=ie[V];Array.isArray(Q)?Q.forEach(Z=>{J.write(r.from([t.properties[R]])),X(J,V.toString(),Z.toString())}):(J.write(r.from([t.properties[R]])),X(J,V.toString(),Q.toString()))});break}default:return J.destroy(new Error(`Invalid property ${R} value: ${ie}`)),!1}}function pe(J,R,ie){$(J,ie);for(let V in R)if(Object.prototype.hasOwnProperty.call(R,V)&&R[V]!=null){let Q=R[V];if(Array.isArray(Q))for(let Z=0;Z<Q.length;Z++)Y(J,V,Q[Z]);else Y(J,V,Q)}}function te(J){return J?J instanceof r?J.length:r.byteLength(J):0}function ve(J){return typeof J=="string"||J instanceof r}e.exports=y}),Mu=me((o,e)=>{le(),ue(),ce();var t=Ka(),{EventEmitter:r}=(Ut(),Re(Pt)),{Buffer:i}=(qe(),Re(Fe));function n(a,l){let c=new s;return t(a,c,l),c.concat()}var s=class extends r{constructor(){super(),this._array=new Array(20),this._i=0}write(a){return this._array[this._i++]=a,!0}concat(){let a=0,l=new Array(this._array.length),c=this._array,u=0,d;for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?l[d]=c[d].length:l[d]=i.byteLength(c[d]),a+=l[d];let p=i.allocUnsafe(a);for(d=0;d<c.length&&c[d]!==void 0;d++)typeof c[d]!="string"?(c[d].copy(p,u),u+=l[d]):(p.write(c[d],u),u+=l[d]);return p}destroy(a){a&&this.emit("error",a)}};e.exports=n}),Nu=me(o=>{le(),ue(),ce(),o.parser=Pu().parser,o.generate=Mu(),o.writeToStream=Ka()}),Ru=me((o,e)=>{le(),ue(),ce(),e.exports=r;function t(n){return n instanceof Jr?Jr.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length)}function r(n){if(n=n||{},n.circles)return i(n);let s=new Map;if(s.set(Date,d=>new Date(d)),s.set(Map,(d,p)=>new Map(l(Array.from(d),p))),s.set(Set,(d,p)=>new Set(l(Array.from(d),p))),n.constructorHandlers)for(let d of n.constructorHandlers)s.set(d[0],d[1]);let a=null;return n.proto?u:c;function l(d,p){let g=Object.keys(d),h=new Array(g.length);for(let b=0;b<g.length;b++){let y=g[b],w=d[y];typeof w!="object"||w===null?h[y]=w:w.constructor!==Object&&(a=s.get(w.constructor))?h[y]=a(w,p):ArrayBuffer.isView(w)?h[y]=t(w):h[y]=p(w)}return h}function c(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,c);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,c);let p={};for(let g in d){if(Object.hasOwnProperty.call(d,g)===!1)continue;let h=d[g];typeof h!="object"||h===null?p[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?p[g]=a(h,c):ArrayBuffer.isView(h)?p[g]=t(h):p[g]=c(h)}return p}function u(d){if(typeof d!="object"||d===null)return d;if(Array.isArray(d))return l(d,u);if(d.constructor!==Object&&(a=s.get(d.constructor)))return a(d,u);let p={};for(let g in d){let h=d[g];typeof h!="object"||h===null?p[g]=h:h.constructor!==Object&&(a=s.get(h.constructor))?p[g]=a(h,u):ArrayBuffer.isView(h)?p[g]=t(h):p[g]=u(h)}return p}}function i(n){let s=[],a=[],l=new Map;if(l.set(Date,g=>new Date(g)),l.set(Map,(g,h)=>new Map(u(Array.from(g),h))),l.set(Set,(g,h)=>new Set(u(Array.from(g),h))),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,h){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,h);else if(ArrayBuffer.isView(k))y[m]=t(k);else{let _=s.indexOf(k);_!==-1?y[m]=a[_]:y[m]=h(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 h={};s.push(g),a.push(h);for(let b in g){if(Object.hasOwnProperty.call(g,b)===!1)continue;let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,d);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=d(y)}}return s.pop(),a.pop(),h}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 h={};s.push(g),a.push(h);for(let b in g){let y=g[b];if(typeof y!="object"||y===null)h[b]=y;else if(y.constructor!==Object&&(c=l.get(y.constructor)))h[b]=c(y,p);else if(ArrayBuffer.isView(y))h[b]=t(y);else{let w=s.indexOf(y);w!==-1?h[b]=a[w]:h[b]=p(y)}}return s.pop(),a.pop(),h}}}),ju=me((o,e)=>{le(),ue(),ce(),e.exports=Ru()()}),Ga=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.validateTopic=e,o.validateTopics=t;function e(r){let i=r.split("/");for(let n=0;n<i.length;n++)if(i[n]!=="+"){if(i[n]==="#")return n===i.length-1;if(i[n].indexOf("+")!==-1||i[n].indexOf("#")!==-1)return!1}return!0}function t(r){if(r.length===0)return"empty_topic_list";for(let i=0;i<r.length;i++)if(!e(r[i]))return r[i];return null}}),Ya=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Ft(),t={objectMode:!0},r={clean:!0},i=class{options;_inflights;constructor(n){this.options=n||{},this.options={...r,...n},this._inflights=new Map}put(n,s){return this._inflights.set(n.messageId,n),s&&s(),this}createStream(){let n=new e.Readable(t),s=[],a=!1,l=0;return this._inflights.forEach((c,u)=>{s.push(c)}),n._read=()=>{!a&&l<s.length?n.push(s[l++]):n.push(null)},n.destroy=c=>{if(!a)return a=!0,setTimeout(()=>{n.emit("close")},0),n},n}del(n,s){let a=this._inflights.get(n.messageId);return a?(this._inflights.delete(n.messageId),s(null,a)):s&&s(new Error("missing packet")),this}get(n,s){let a=this._inflights.get(n.messageId);return a?s(null,a):s&&s(new Error("missing packet")),this}close(n){this.options.clean&&(this._inflights=null),n&&n()}};o.default=i}),Du=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=[0,16,128,131,135,144,145,151,153],t=(r,i,n)=>{r.log("handlePublish: packet %o",i),n=typeof n<"u"?n:r.noop;let s=i.topic.toString(),a=i.payload,{qos:l}=i,{messageId:c}=i,{options:u}=r;if(r.options.protocolVersion===5){let d;if(i.properties&&(d=i.properties.topicAlias),typeof d<"u")if(s.length===0)if(d>0&&d<=65535){let p=r.topicAliasRecv.getTopicByAlias(d);if(p)s=p,r.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",s,d);else{r.log("handlePublish :: unregistered topic alias. alias: %d",d),r.emit("error",new Error("Received unregistered Topic Alias"));return}}else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}else if(r.topicAliasRecv.put(s,d))r.log("handlePublish :: registered topic: %s - alias: %d",s,d);else{r.log("handlePublish :: topic alias out of range. alias: %d",d),r.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(r.log("handlePublish: qos %d",l),l){case 2:{u.customHandleAcks(s,a,i,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for pubrec"));p?r._sendPacket({cmd:"pubrec",messageId:c,reasonCode:p},n):r.incomingStore.put(i,()=>{r._sendPacket({cmd:"pubrec",messageId:c},n)})});break}case 1:{u.customHandleAcks(s,a,i,(d,p)=>{if(typeof d=="number"&&(p=d,d=null),d)return r.emit("error",d);if(e.indexOf(p)===-1)return r.emit("error",new Error("Wrong reason code for puback"));p||r.emit("message",s,a,i),r.handleMessage(i,g=>{if(g)return n&&n(g);r._sendPacket({cmd:"puback",messageId:c,reasonCode:p},n)})});break}case 0:r.emit("message",s,a,i),r.handleMessage(i,n);break;default:r.log("handlePublish: unknown QoS. Doing nothing.");break}};o.default=t}),$u=me((o,e)=>{e.exports={version:"5.15.0"}}),Zt=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.MQTTJS_VERSION=o.nextTick=o.ErrorWithSubackPacket=o.ErrorWithReasonCode=void 0,o.applyMixin=r;var e=class Ja extends Error{code;constructor(n,s){super(n),this.code=s,Object.setPrototypeOf(this,Ja.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};o.ErrorWithReasonCode=e;var t=class Qa extends Error{packet;constructor(n,s){super(n),this.packet=s,Object.setPrototypeOf(this,Qa.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};o.ErrorWithSubackPacket=t;function r(i,n,s=!1){let a=[n];for(;;){let l=a[0],c=Object.getPrototypeOf(l);if(c?.prototype)a.unshift(c);else break}for(let l of a)for(let c of Object.getOwnPropertyNames(l.prototype))(s||c!=="constructor")&&Object.defineProperty(i.prototype,c,Object.getOwnPropertyDescriptor(l.prototype,c)??Object.create(null))}o.nextTick=typeof je?.nextTick=="function"?je.nextTick:i=>{setTimeout(i,0)},o.MQTTJS_VERSION=$u().version}),nn=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=void 0;var e=Zt();o.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var t=(r,i)=>{let{messageId:n}=i,s=i.cmd,a=null,l=r.outgoing[n]?r.outgoing[n].cb:null,c=null;if(!l){r.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(r.log("_handleAck :: packet type",s),s){case"pubcomp":case"puback":{let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._removeOutgoingAndStoreMessage(n,l);break}case"pubrec":{a={cmd:"pubrel",qos:2,messageId:n};let u=i.reasonCode;u&&u>0&&u!==16?(c=new e.ErrorWithReasonCode(`Publish error: ${o.ReasonCodes[u]}`,u),r._removeOutgoingAndStoreMessage(n,()=>{l(c,i)})):r._sendPacket(a);break}case"suback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n);let u=i.granted;for(let d=0;d<u.length;d++){let p=u[d];if((p&128)!==0){c=new Error(`Subscribe error: ${o.ReasonCodes[p]}`),c.code=p;let g=r.messageIdToTopic[n];g&&g.forEach(h=>{delete r._resubscribeTopics[h]})}}delete r.messageIdToTopic[n],r._invokeStoreProcessingQueue(),l(c,i);break}case"unsuback":{delete r.outgoing[n],r.messageIdProvider.deallocate(n),r._invokeStoreProcessingQueue(),l(null,i);break}default:r.emit("error",new Error("unrecognized packet type"))}r.disconnecting&&Object.keys(r.outgoing).length===0&&r.emit("outgoingEmpty")};o.default=t}),Uu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Zt(),t=nn(),r=(i,n)=>{let{options:s}=i,a=s.protocolVersion,l=a===5?n.reasonCode:n.returnCode;if(a!==5){let c=new e.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${a}`,l);i.emit("error",c);return}i.handleAuth(n,(c,u)=>{if(c){i.emit("error",c);return}if(l===24)i.reconnecting=!1,i._sendPacket(u);else{let d=new e.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[l]}`,l);i.emit("error",d)}})};o.default=r}),Bu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.LRUCache=void 0;var e=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,t=new Set,r=typeof je=="object"&&je?je:{},i=(g,h,b,y)=>{typeof r.emitWarning=="function"?r.emitWarning(g,h,b,y):console.error(`[${b}] ${h}: ${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(){h()}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",h=()=>{g&&(g=!1,i("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",h))}}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 ur{heap;length;static#l=!1;static create(h){let b=c(h);if(!b)return[];ur.#l=!0;let y=new ur(h,b);return ur.#l=!1,y}constructor(h,b){if(!ur.#l)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new b(h),this.length=0}push(h){this.heap[this.length++]=h}pop(){return this.heap[--this.length]}},p=class Xa{#l;#d;#m;#g;#P;#O;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#c;#h;#a;#o;#y;#s;#v;#w;#f;#k;#A;#u;static unsafeExposeInternals(h){return{starts:h.#w,ttls:h.#f,sizes:h.#v,keyMap:h.#n,keyList:h.#r,valList:h.#e,next:h.#c,prev:h.#h,get head(){return h.#a},get tail(){return h.#o},free:h.#y,isBackgroundFetch:b=>h.#t(b),backgroundFetch:(b,y,w,m)=>h.#N(b,y,w,m),moveToTail:b=>h.#C(b),indexes:b=>h.#x(b),rindexes:b=>h.#_(b),isStale:b=>h.#p(b)}}get max(){return this.#l}get maxSize(){return this.#d}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#P}get memoMethod(){return this.#O}get dispose(){return this.#m}get disposeAfter(){return this.#g}constructor(h){let{max:b=0,ttl:y,ttlResolution:w=1,ttlAutopurge:m,updateAgeOnGet:k,updateAgeOnHas:_,allowStale:v,dispose:E,disposeAfter:S,noDisposeOnSet:I,noUpdateTTL:P,maxSize:O=0,maxEntrySize:j=0,sizeCalculation:T,fetchMethod:F,memoMethod:$,noDeleteOnFetchRejection:U,noDeleteOnStaleGet:X,allowStaleOnFetchRejection:z,allowStaleOnFetchAbort:W,ignoreFetchAbort:ne}=h;if(b!==0&&!l(b))throw new TypeError("max option must be a nonnegative integer");let D=b?c(b):Array;if(!D)throw new Error("invalid max value: "+b);if(this.#l=b,this.#d=O,this.maxEntrySize=j||this.#d,this.sizeCalculation=T,this.sizeCalculation){if(!this.#d&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if($!==void 0&&typeof $!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#O=$,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 D(b),this.#h=new D(b),this.#a=0,this.#o=0,this.#y=d.create(b),this.#i=0,this.#b=0,typeof E=="function"&&(this.#m=E),typeof S=="function"?(this.#g=S,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#k=!!this.#m,this.#u=!!this.#g,this.noDisposeOnSet=!!I,this.noUpdateTTL=!!P,this.noDeleteOnFetchRejection=!!U,this.allowStaleOnFetchRejection=!!z,this.allowStaleOnFetchAbort=!!W,this.ignoreFetchAbort=!!ne,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=!!X,this.updateAgeOnGet=!!k,this.updateAgeOnHas=!!_,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 G="LRU_CACHE_UNBOUNDED";a(G)&&(t.add(G),i("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",G,Xa))}}getRemainingTTL(h){return this.#n.has(h)?1/0:0}#R(){let h=new u(this.#l),b=new u(this.#l);this.#f=h,this.#w=b,this.#j=(m,k,_=e.now())=>{if(b[m]=k!==0?_:0,h[m]=k,k!==0&&this.ttlAutopurge){let v=setTimeout(()=>{this.#p(m)&&this.#S(this.#r[m],"expire")},k+1);v.unref&&v.unref()}},this.#I=m=>{b[m]=h[m]!==0?e.now():0},this.#E=(m,k)=>{if(h[k]){let _=h[k],v=b[k];if(!_||!v)return;m.ttl=_,m.start=v,m.now=y||w();let E=m.now-v;m.remainingTTL=_-E}};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 _=h[k],v=b[k];if(!_||!v)return 1/0;let E=(y||w())-v;return _-E},this.#p=m=>{let k=b[m],_=h[m];return!!_&&!!k&&(y||w())-k>_}}#I=()=>{};#E=()=>{};#j=()=>{};#p=()=>!1;#F(){let h=new u(this.#l);this.#b=0,this.#v=h,this.#T=b=>{this.#b-=h[b],h[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(h[b]=y,this.#d){let m=this.#d-h[b];for(;this.#b>m;)this.#M(!0)}this.#b+=h[b],w&&(w.entrySize=y,w.totalCalculatedSize=this.#b)}}#T=h=>{};#L=(h,b,y)=>{};#D=(h,b,y,w)=>{if(y||w)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#x({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#o;!(!this.#$(b)||((h||!this.#p(b))&&(yield b),b===this.#a));)b=this.#h[b]}*#_({allowStale:h=this.allowStale}={}){if(this.#i)for(let b=this.#a;!(!this.#$(b)||((h||!this.#p(b))&&(yield b),b===this.#o));)b=this.#c[b]}#$(h){return h!==void 0&&this.#n.get(this.#r[h])===h}*entries(){for(let h of this.#x())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*rentries(){for(let h of this.#_())this.#e[h]!==void 0&&this.#r[h]!==void 0&&!this.#t(this.#e[h])&&(yield[this.#r[h],this.#e[h]])}*keys(){for(let h of this.#x()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*rkeys(){for(let h of this.#_()){let b=this.#r[h];b!==void 0&&!this.#t(this.#e[h])&&(yield b)}}*values(){for(let h of this.#x())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}*rvalues(){for(let h of this.#_())this.#e[h]!==void 0&&!this.#t(this.#e[h])&&(yield this.#e[h])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(h,b={}){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;if(m!==void 0&&h(m,this.#r[y],this))return this.get(this.#r[y],b)}}forEach(h,b=this){for(let y of this.#x()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}rforEach(h,b=this){for(let y of this.#_()){let w=this.#e[y],m=this.#t(w)?w.__staleWhileFetching:w;m!==void 0&&h.call(b,m,this.#r[y],this)}}purgeStale(){let h=!1;for(let b of this.#_({allowStale:!0}))this.#p(b)&&(this.#S(this.#r[b],"expire"),h=!0);return h}info(h){let b=this.#n.get(h);if(b===void 0)return;let y=this.#e[b],w=this.#t(y)?y.__staleWhileFetching:y;if(w===void 0)return;let m={value:w};if(this.#f&&this.#w){let k=this.#f[b],_=this.#w[b];if(k&&_){let v=k-(e.now()-_);m.ttl=v,m.start=Date.now()}}return this.#v&&(m.size=this.#v[b]),m}dump(){let h=[];for(let b of this.#x({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.#f&&this.#w){k.ttl=this.#f[b];let _=e.now()-this.#w[b];k.start=Math.floor(Date.now()-_)}this.#v&&(k.size=this.#v[b]),h.unshift([y,k])}return h}load(h){this.clear();for(let[b,y]of h){if(y.start){let w=Date.now()-y.start;y.start=e.now()-w}this.set(b,y.value,y)}}set(h,b,y={}){if(b===void 0)return this.delete(h),this;let{ttl:w=this.ttl,start:m,noDisposeOnSet:k=this.noDisposeOnSet,sizeCalculation:_=this.sizeCalculation,status:v}=y,{noUpdateTTL:E=this.noUpdateTTL}=y,S=this.#D(h,b,y.size||0,_);if(this.maxEntrySize&&S>this.maxEntrySize)return v&&(v.set="miss",v.maxEntrySizeExceeded=!0),this.#S(h,"set"),this;let I=this.#i===0?void 0:this.#n.get(h);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]=h,this.#e[I]=b,this.#n.set(h,I),this.#c[this.#o]=I,this.#h[I]=this.#o,this.#o=I,this.#i++,this.#L(I,S,v),v&&(v.set="add"),E=!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,h,"set"),this.#u&&this.#s?.push([O,h,"set"]))}else k||(this.#k&&this.#m?.(P,h,"set"),this.#u&&this.#s?.push([P,h,"set"]));if(this.#T(I),this.#L(I,S,v),this.#e[I]=b,v){v.set="replace";let O=P&&this.#t(P)?P.__staleWhileFetching:P;O!==void 0&&(v.oldValue=O)}}else v&&(v.set="update")}if(w!==0&&!this.#f&&this.#R(),this.#f&&(E||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 h=this.#e[this.#a];if(this.#M(!0),this.#t(h)){if(h.__staleWhileFetching)return h.__staleWhileFetching}else if(h!==void 0)return h}}finally{if(this.#u&&this.#s){let h=this.#s,b;for(;b=h?.shift();)this.#g?.(...b)}}}#M(h){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),h&&(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(h,b={}){let{updateAgeOnHas:y=this.updateAgeOnHas,status:w}=b,m=this.#n.get(h);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 y&&this.#I(m),w&&(w.has="hit",this.#E(w,m)),!0}else w&&(w.has="miss");return!1}peek(h,b={}){let{allowStale:y=this.allowStale}=b,w=this.#n.get(h);if(w===void 0||!y&&this.#p(w))return;let m=this.#e[w];return this.#t(m)?m.__staleWhileFetching:m}#N(h,b,y,w){let m=b===void 0?void 0:this.#e[b];if(this.#t(m))return m;let k=new n,{signal:_}=y;_?.addEventListener("abort",()=>k.abort(_.reason),{signal:k.signal});let v={signal:k.signal,options:y,context:w},E=(T,F=!1)=>{let{aborted:$}=k.signal,U=y.ignoreFetchAbort&&T!==void 0;if(y.status&&($&&!F?(y.status.fetchAborted=!0,y.status.fetchError=k.signal.reason,U&&(y.status.fetchAbortIgnored=!0)):y.status.fetchResolved=!0),$&&!U&&!F)return I(k.signal.reason);let X=O;return this.#e[b]===O&&(T===void 0?X.__staleWhileFetching?this.#e[b]=X.__staleWhileFetching:this.#S(h,"fetch"):(y.status&&(y.status.fetchUpdated=!0),this.set(h,T,v.options))),T},S=T=>(y.status&&(y.status.fetchRejected=!0,y.status.fetchError=T),I(T)),I=T=>{let{aborted:F}=k.signal,$=F&&y.allowStaleOnFetchAbort,U=$||y.allowStaleOnFetchRejection,X=U||y.noDeleteOnFetchRejection,z=O;if(this.#e[b]===O&&(!X||z.__staleWhileFetching===void 0?this.#S(h,"fetch"):$||(this.#e[b]=z.__staleWhileFetching)),U)return y.status&&z.__staleWhileFetching!==void 0&&(y.status.returnedStale=!0),z.__staleWhileFetching;if(z.__returned===z)throw T},P=(T,F)=>{let $=this.#P?.(h,m,v);$&&$ instanceof Promise&&$.then(U=>T(U===void 0?void 0:U),F),k.signal.addEventListener("abort",()=>{(!y.ignoreFetchAbort||y.allowStaleOnFetchAbort)&&(T(void 0),y.allowStaleOnFetchAbort&&(T=U=>E(U,!0)))})};y.status&&(y.status.fetchDispatched=!0);let O=new Promise(P).then(E,S),j=Object.assign(O,{__abortController:k,__staleWhileFetching:m,__returned:void 0});return b===void 0?(this.set(h,j,{...v.options,status:void 0}),b=this.#n.get(h)):this.#e[b]=j,j}#t(h){if(!this.#A)return!1;let b=h;return!!b&&b instanceof Promise&&b.hasOwnProperty("__staleWhileFetching")&&b.__abortController instanceof n}async fetch(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,ttl:k=this.ttl,noDisposeOnSet:_=this.noDisposeOnSet,size:v=0,sizeCalculation:E=this.sizeCalculation,noUpdateTTL:S=this.noUpdateTTL,noDeleteOnFetchRejection:I=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:P=this.allowStaleOnFetchRejection,ignoreFetchAbort:O=this.ignoreFetchAbort,allowStaleOnFetchAbort:j=this.allowStaleOnFetchAbort,context:T,forceRefresh:F=!1,status:$,signal:U}=b;if(!this.#A)return $&&($.fetch="get"),this.get(h,{allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,status:$});let X={allowStale:y,updateAgeOnGet:w,noDeleteOnStaleGet:m,ttl:k,noDisposeOnSet:_,size:v,sizeCalculation:E,noUpdateTTL:S,noDeleteOnFetchRejection:I,allowStaleOnFetchRejection:P,allowStaleOnFetchAbort:j,ignoreFetchAbort:O,status:$,signal:U},z=this.#n.get(h);if(z===void 0){$&&($.fetch="miss");let W=this.#N(h,z,X,T);return W.__returned=W}else{let W=this.#e[z];if(this.#t(W)){let L=y&&W.__staleWhileFetching!==void 0;return $&&($.fetch="inflight",L&&($.returnedStale=!0)),L?W.__staleWhileFetching:W.__returned=W}let ne=this.#p(z);if(!F&&!ne)return $&&($.fetch="hit"),this.#C(z),w&&this.#I(z),$&&this.#E($,z),W;let D=this.#N(h,z,X,T),G=D.__staleWhileFetching!==void 0&&y;return $&&($.fetch=ne?"stale":"refresh",G&&ne&&($.returnedStale=!0)),G?D.__staleWhileFetching:D.__returned=D}}async forceFetch(h,b={}){let y=await this.fetch(h,b);if(y===void 0)throw new Error("fetch() returned undefined");return y}memo(h,b={}){let y=this.#O;if(!y)throw new Error("no memoMethod provided to constructor");let{context:w,forceRefresh:m,...k}=b,_=this.get(h,k);if(!m&&_!==void 0)return _;let v=y(h,_,{options:k,context:w});return this.set(h,v,k),v}get(h,b={}){let{allowStale:y=this.allowStale,updateAgeOnGet:w=this.updateAgeOnGet,noDeleteOnStaleGet:m=this.noDeleteOnStaleGet,status:k}=b,_=this.#n.get(h);if(_!==void 0){let v=this.#e[_],E=this.#t(v);return k&&this.#E(k,_),this.#p(_)?(k&&(k.get="stale"),E?(k&&y&&v.__staleWhileFetching!==void 0&&(k.returnedStale=!0),y?v.__staleWhileFetching:void 0):(m||this.#S(h,"expire"),k&&y&&(k.returnedStale=!0),y?v:void 0)):(k&&(k.get="hit"),E?v.__staleWhileFetching:(this.#C(_),w&&this.#I(_),v))}else k&&(k.get="miss")}#U(h,b){this.#h[b]=h,this.#c[h]=b}#C(h){h!==this.#o&&(h===this.#a?this.#a=this.#c[h]:this.#U(this.#h[h],this.#c[h]),this.#U(this.#o,h),this.#o=h)}delete(h){return this.#S(h,"delete")}#S(h,b){let y=!1;if(this.#i!==0){let w=this.#n.get(h);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,h,b),this.#u&&this.#s?.push([m,h,b])),this.#n.delete(h),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 _=this.#c[w];this.#h[_]=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(h){for(let b of this.#_({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,h),this.#u&&this.#s?.push([y,w,h])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#f&&this.#w&&(this.#f.fill(0),this.#w.fill(0)),this.#v&&this.#v.fill(0),this.#a=0,this.#o=0,this.#y.length=0,this.#b=0,this.#i=0,this.#u&&this.#s){let b=this.#s,y;for(;y=b?.shift();)this.#g?.(...y)}}};o.LRUCache=p}),kt=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.ContainerIterator=o.Container=o.Base=void 0;var e=class{constructor(i=0){this.iteratorType=i}equals(i){return this.o===i.o}};o.ContainerIterator=e;var t=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};o.Base=t;var r=class extends t{};o.Container=r}),Fu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=kt(),t=class extends e.Base{constructor(i=[]){super(),this.S=[];let n=this;i.forEach(function(s){n.push(s)})}clear(){this.i=0,this.S=[]}push(i){return this.S.push(i),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},r=t;o.default=r}),qu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=kt(),t=class extends e.Base{constructor(i=[]){super(),this.j=0,this.q=[];let n=this;i.forEach(function(s){n.push(s)})}clear(){this.q=[],this.i=this.j=0}push(i){let n=this.q.length;if(this.j/n>.5&&this.j+this.i>=n&&n>4096){let s=this.i;for(let a=0;a<s;++a)this.q[a]=this.q[this.j+a];this.j=0,this.q[this.i]=i}else this.q[this.j+this.i]=i;return++this.i}pop(){if(this.i===0)return;let i=this.q[this.j++];return this.i-=1,i}front(){if(this.i!==0)return this.q[this.j]}},r=t;o.default=r}),Hu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=kt(),t=class extends e.Base{constructor(i=[],n=function(a,l){return a>l?-1:a<l?1:0},s=!0){if(super(),this.v=n,Array.isArray(i))this.C=s?[...i]:i;else{this.C=[];let l=this;i.forEach(function(c){l.C.push(c)})}this.i=this.C.length;let a=this.i>>1;for(let l=this.i-1>>1;l>=0;--l)this.k(l,a)}m(i){let n=this.C[i];for(;i>0;){let s=i-1>>1,a=this.C[s];if(this.v(a,n)<=0)break;this.C[i]=a,i=s}this.C[i]=n}k(i,n){let s=this.C[i];for(;i<n;){let a=i<<1|1,l=a+1,c=this.C[a];if(l<this.i&&this.v(c,this.C[l])>0&&(a=l,c=this.C[l]),this.v(c,s)>=0)break;this.C[i]=c,i=a}this.C[i]=s}clear(){this.i=0,this.C.length=0}push(i){this.C.push(i),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let i=this.C[0],n=this.C.pop();return this.i-=1,this.i&&(this.C[0]=n,this.k(0,this.i>>1)),i}top(){return this.C[0]}find(i){return this.C.indexOf(i)>=0}remove(i){let n=this.C.indexOf(i);return n<0?!1:(n===0?this.pop():n===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(n,1,this.C.pop()),this.i-=1,this.m(n),this.k(n,this.i>>1)),!0)}updateItem(i){let n=this.C.indexOf(i);return n<0?!1:(this.m(n),this.k(n,this.i>>1),!0)}toArray(){return[...this.C]}},r=t;o.default=r}),Co=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=kt(),t=class extends e.Container{},r=t;o.default=r}),xt=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.throwIteratorAccessError=e;function e(){throw new RangeError("Iterator access denied!")}}),Za=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.RandomIterator=void 0;var e=kt(),t=xt(),r=class extends e.ContainerIterator{constructor(i,n){super(n),this.o=i,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,t.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,t.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,t.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,t.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(i){this.container.setElementByPos(this.o,i)}};o.RandomIterator=r}),Wu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(Co()),t=Za();function r(a){return a&&a.t?a:{default:a}}var i=class el extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new el(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=!0){if(super(),Array.isArray(a))this.J=l?[...a]:a,this.i=a.length;else{this.J=[];let c=this;a.forEach(function(u){c.pushBack(u)})}}clear(){this.i=0,this.J.length=0}begin(){return new i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J[a]}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;return this.J.splice(a,1),this.i-=1,this.i}eraseElementByValue(a){let l=0;for(let c=0;c<this.i;++c)this.J[c]!==a&&(this.J[l++]=this.J[c]);return this.i=this.J.length=l,this.i}eraseElementByIterator(a){let l=a.o;return a=a.next(),this.eraseElementByPos(l),a}pushBack(a){return this.J.push(a),this.i+=1,this.i}popBack(){if(this.i!==0)return this.i-=1,this.J.pop()}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;this.J[a]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;return this.J.splice(a,0,...new Array(c).fill(l)),this.i+=c,this.i}find(a){for(let l=0;l<this.i;++l)if(this.J[l]===a)return new i(l,this);return this.end()}reverse(){this.J.reverse()}unique(){let a=1;for(let l=1;l<this.i;++l)this.J[l]!==this.J[l-1]&&(this.J[a++]=this.J[l]);return this.i=this.J.length=a,this.i}sort(a){this.J.sort(a)}forEach(a){for(let l=0;l<this.i;++l)a(this.J[l],l,this)}[Symbol.iterator](){return(function*(){yield*this.J}).bind(this)()}},s=n;o.default=s}),zu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(Co()),t=kt(),r=xt();function i(l){return l&&l.t?l:{default:l}}var n=class tl 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 tl(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let c=this;l.forEach(function(u){c.pushBack(u)})}V(l){let{L:c,B:u}=l;c.B=u,u.L=c,l===this.p&&(this.p=u),l===this._&&(this._=c),this.i-=1}G(l,c){let u=c.B,d={l,L:c,B:u};c.B=d,u.L=d,c===this.h&&(this.p=d),u===this.h&&(this._=d),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return c.l}eraseElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return this.V(c),this.i}eraseElementByValue(l){let c=this.p;for(;c!==this.h;)c.l===l&&this.V(c),c=c.B;return this.i}eraseElementByIterator(l){let c=l.o;return c===this.h&&(0,r.throwIteratorAccessError)(),l=l.next(),this.V(c),l}pushBack(l){return this.G(l,this._),this.i}popBack(){if(this.i===0)return;let l=this._.l;return this.V(this._),l}pushFront(l){return this.G(l,this.h),this.i}popFront(){if(this.i===0)return;let l=this.p.l;return this.V(this.p),l}setElementByPos(l,c){if(l<0||l>this.i-1)throw new RangeError;let u=this.p;for(;l--;)u=u.B;u.l=c}insert(l,c,u=1){if(l<0||l>this.i)throw new RangeError;if(u<=0)return this.i;if(l===0)for(;u--;)this.pushFront(c);else if(l===this.i)for(;u--;)this.pushBack(c);else{let d=this.p;for(let g=1;g<l;++g)d=d.B;let p=d.B;for(this.i+=u;u--;)d.B={l:c,L:d},d.B.L=d,d=d.B;d.B=p,p.L=d}return this.i}find(l){let c=this.p;for(;c!==this.h;){if(c.l===l)return new n(c,this.h,this);c=c.B}return this.end()}reverse(){if(this.i<=1)return;let l=this.p,c=this._,u=0;for(;u<<1<this.i;){let d=l.l;l.l=c.l,c.l=d,l=l.B,c=c.L,u+=1}}unique(){if(this.i<=1)return this.i;let l=this.p;for(;l!==this.h;){let c=l;for(;c.B!==this.h&&c.l===c.B.l;)c=c.B,this.i-=1;l.B=c.B,l.B.L=l,l=l.B}return this.i}sort(l){if(this.i<=1)return;let c=[];this.forEach(function(d){c.push(d)}),c.sort(l);let u=this.p;c.forEach(function(d){u.l=d,u=u.B})}merge(l){let c=this;if(this.i===0)l.forEach(function(u){c.pushBack(u)});else{let u=this.p;l.forEach(function(d){for(;u!==c.h&&u.l<=d;)u=u.B;c.G(d,u.L)})}return this.i}forEach(l){let c=this.p,u=0;for(;c!==this.h;)l(c.l,u++,this),c=c.B}[Symbol.iterator](){return(function*(){if(this.i===0)return;let l=this.p;for(;l!==this.h;)yield l.l,l=l.B}).bind(this)()}},a=s;o.default=a}),Vu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=r(Co()),t=Za();function r(a){return a&&a.t?a:{default:a}}var i=class rl extends t.RandomIterator{constructor(l,c,u){super(l,u),this.container=c}copy(){return new rl(this.o,this.container,this.iteratorType)}},n=class extends e.default{constructor(a=[],l=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let c=(()=>{if(typeof a.length=="number")return a.length;if(typeof a.size=="number")return a.size;if(typeof a.size=="function")return a.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=l,this.P=Math.max(Math.ceil(c/this.F),1);for(let p=0;p<this.P;++p)this.A.push(new Array(this.F));let u=Math.ceil(c/this.F);this.j=this.R=(this.P>>1)-(u>>1),this.D=this.N=this.F-c%this.F>>1;let d=this;a.forEach(function(p){d.pushBack(p)})}T(){let a=[],l=Math.max(this.P>>1,1);for(let c=0;c<l;++c)a[c]=new Array(this.F);for(let c=this.j;c<this.P;++c)a[a.length]=this.A[c];for(let c=0;c<this.R;++c)a[a.length]=this.A[c];a[a.length]=[...this.A[this.R]],this.j=l,this.R=a.length-1;for(let c=0;c<l;++c)a[a.length]=new Array(this.F);this.A=a,this.P=a.length}O(a){let l=this.D+a+1,c=l%this.F,u=c-1,d=this.j+(l-c)/this.F;return c===0&&(d-=1),d%=this.P,u<0&&(u+=this.F),{curNodeBucketIndex:d,curNodePointerIndex:u}}clear(){this.A=[new Array(this.F)],this.P=1,this.j=this.R=this.i=0,this.D=this.N=this.F>>1}begin(){return new i(0,this)}end(){return new i(this.i,this)}rBegin(){return new i(this.i-1,this,1)}rEnd(){return new i(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(a){return this.i&&(this.N<this.F-1?this.N+=1:this.R<this.P-1?(this.R+=1,this.N=0):(this.R=0,this.N=0),this.R===this.j&&this.N===this.D&&this.T()),this.i+=1,this.A[this.R][this.N]=a,this.i}popBack(){if(this.i===0)return;let a=this.A[this.R][this.N];return this.i!==1&&(this.N>0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,a}pushFront(a){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=a,this.i}popFront(){if(this.i===0)return;let a=this.A[this.j][this.D];return this.i!==1&&(this.D<this.F-1?this.D+=1:this.j<this.P-1?(this.j+=1,this.D=0):(this.j=0,this.D=0)),this.i-=1,a}getElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.A[l][c]}setElementByPos(a,l){if(a<0||a>this.i-1)throw new RangeError;let{curNodeBucketIndex:c,curNodePointerIndex:u}=this.O(a);this.A[c][u]=l}insert(a,l,c=1){if(a<0||a>this.i)throw new RangeError;if(a===0)for(;c--;)this.pushFront(l);else if(a===this.i)for(;c--;)this.pushBack(l);else{let u=[];for(let d=a;d<this.i;++d)u.push(this.getElementByPos(d));this.cut(a-1);for(let d=0;d<c;++d)this.pushBack(l);for(let d=0;d<u.length;++d)this.pushBack(u[d])}return this.i}cut(a){if(a<0)return this.clear(),0;let{curNodeBucketIndex:l,curNodePointerIndex:c}=this.O(a);return this.R=l,this.N=c,this.i=a+1,this.i}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;if(a===0)this.popFront();else if(a===this.i-1)this.popBack();else{let l=[];for(let u=a+1;u<this.i;++u)l.push(this.getElementByPos(u));this.cut(a),this.popBack();let c=this;l.forEach(function(u){c.pushBack(u)})}return this.i}eraseElementByValue(a){if(this.i===0)return 0;let l=[];for(let u=0;u<this.i;++u){let d=this.getElementByPos(u);d!==a&&l.push(d)}let c=l.length;for(let u=0;u<c;++u)this.setElementByPos(u,l[u]);return this.cut(c-1)}eraseElementByIterator(a){let l=a.o;return this.eraseElementByPos(l),a=a.next(),a}find(a){for(let l=0;l<this.i;++l)if(this.getElementByPos(l)===a)return new i(l,this);return this.end()}reverse(){let a=0,l=this.i-1;for(;a<l;){let c=this.getElementByPos(a);this.setElementByPos(a,this.getElementByPos(l)),this.setElementByPos(l,c),a+=1,l-=1}}unique(){if(this.i<=1)return this.i;let a=1,l=this.getElementByPos(0);for(let c=1;c<this.i;++c){let u=this.getElementByPos(c);u!==l&&(l=u,this.setElementByPos(a++,u))}for(;this.i>a;)this.popBack();return this.i}sort(a){let l=[];for(let c=0;c<this.i;++c)l.push(this.getElementByPos(c));l.sort(a);for(let c=0;c<this.i;++c)this.setElementByPos(c,l[c])}shrinkToFit(){if(this.i===0)return;let a=[];this.forEach(function(l){a.push(l)}),this.P=Math.max(Math.ceil(this.i/this.F),1),this.i=this.j=this.R=this.D=this.N=0,this.A=[];for(let l=0;l<this.P;++l)this.A.push(new Array(this.F));for(let l=0;l<a.length;++l)this.pushBack(a[l])}forEach(a){for(let l=0;l<this.i;++l)a(this.getElementByPos(l),l,this)}[Symbol.iterator](){return(function*(){for(let a=0;a<this.i;++a)yield this.getElementByPos(a)}).bind(this)()}},s=n;o.default=s}),Ku=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.TreeNodeEnableIndex=o.TreeNode=void 0;var e=class{constructor(r,i){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=r,this.l=i}L(){let r=this;if(r.ee===1&&r.tt.tt===r)r=r.W;else if(r.U)for(r=r.U;r.W;)r=r.W;else{let i=r.tt;for(;i.U===r;)r=i,i=r.tt;r=i}return r}B(){let r=this;if(r.W){for(r=r.W;r.U;)r=r.U;return r}else{let i=r.tt;for(;i.W===r;)r=i,i=r.tt;return r.W!==i?i:r}}te(){let r=this.tt,i=this.W,n=i.U;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.U=this,this.tt=i,this.W=n,n&&(n.tt=this),i}se(){let r=this.tt,i=this.U,n=i.W;return r.tt===this?r.tt=i:r.U===this?r.U=i:r.W=i,i.tt=r,i.W=this,this.tt=i,this.U=n,n&&(n.tt=this),i}};o.TreeNode=e;var t=class extends e{constructor(){super(...arguments),this.rt=1}te(){let r=super.te();return this.ie(),r.ie(),r}se(){let r=super.se();return this.ie(),r.ie(),r}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};o.TreeNodeEnableIndex=t}),nl=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=Ku(),t=kt(),r=xt(),i=class extends t.Container{constructor(s=function(l,c){return l<c?-1:l>c?1:0},a=!1){super(),this.Y=void 0,this.v=s,a?(this.re=e.TreeNodeEnableIndex,this.M=function(l,c,u){let d=this.ne(l,c,u);if(d){let p=d.tt;for(;p!==this.h;)p.rt+=1,p=p.tt;let g=this.he(d);if(g){let{parentNode:h,grandParent:b,curNode:y}=g;h.ie(),b.ie(),y.ie()}}return this.i},this.V=function(l){let c=this.fe(l);for(;c!==this.h;)c.rt-=1,c=c.tt}):(this.re=e.TreeNode,this.M=function(l,c,u){let d=this.ne(l,c,u);return d&&this.he(d),this.i},this.V=this.fe),this.h=new this.re}X(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)s=s.W;else if(c>0)l=s,s=s.U;else return s}return l}Z(s,a){let l=this.h;for(;s;)this.v(s.u,a)<=0?s=s.W:(l=s,s=s.U);return l}$(s,a){let l=this.h;for(;s;){let c=this.v(s.u,a);if(c<0)l=s,s=s.W;else if(c>0)s=s.U;else return s}return l}rr(s,a){let l=this.h;for(;s;)this.v(s.u,a)<0?(l=s,s=s.W):s=s.U;return l}ue(s){for(;;){let a=s.tt;if(a===this.h)return;if(s.ee===1){s.ee=0;return}if(s===a.U){let l=a.W;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.te():a.te();else if(l.W&&l.W.ee===1){l.ee=a.ee,a.ee=0,l.W.ee=0,a===this.Y?this.Y=a.te():a.te();return}else l.U&&l.U.ee===1?(l.ee=1,l.U.ee=0,l.se()):(l.ee=1,s=a)}else{let l=a.U;if(l.ee===1)l.ee=0,a.ee=1,a===this.Y?this.Y=a.se():a.se();else if(l.U&&l.U.ee===1){l.ee=a.ee,a.ee=0,l.U.ee=0,a===this.Y?this.Y=a.se():a.se();return}else l.W&&l.W.ee===1?(l.ee=1,l.W.ee=0,l.te()):(l.ee=1,s=a)}}}fe(s){if(this.i===1)return this.clear(),this.h;let a=s;for(;a.U||a.W;){if(a.W)for(a=a.W;a.U;)a=a.U;else a=a.U;[s.u,a.u]=[a.u,s.u],[s.l,a.l]=[a.l,s.l],s=a}this.h.U===a?this.h.U=a.tt:this.h.W===a&&(this.h.W=a.tt),this.ue(a);let l=a.tt;return a===l.U?l.U=void 0:l.W=void 0,this.i-=1,this.Y.ee=0,l}oe(s,a){return s===void 0?!1:this.oe(s.U,a)||a(s)?!0:this.oe(s.W,a)}he(s){for(;;){let a=s.tt;if(a.ee===0)return;let l=a.tt;if(a===l.U){let c=l.W;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.W){if(s.ee=0,s.U&&(s.U.tt=a),s.W&&(s.W.tt=l),a.W=s.U,l.U=s.W,s.U=a,s.W=l,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.se():l.se(),l.ee=1}else{let c=l.U;if(c&&c.ee===1){if(c.ee=a.ee=0,l===this.Y)return;l.ee=1,s=l;continue}else if(s===a.U){if(s.ee=0,s.U&&(s.U.tt=l),s.W&&(s.W.tt=a),l.W=s.U,a.U=s.W,s.U=l,s.W=a,l===this.Y)this.Y=s,this.h.tt=s;else{let u=l.tt;u.U===l?u.U=s:u.W=s}return s.tt=l.tt,a.tt=s,l.tt=s,l.ee=1,{parentNode:a,grandParent:l,curNode:s}}else a.ee=0,l===this.Y?this.Y=l.te():l.te(),l.ee=1}return}}ne(s,a,l){if(this.Y===void 0){this.i+=1,this.Y=new this.re(s,a),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let c,u=this.h.U,d=this.v(u.u,s);if(d===0){u.l=a;return}else if(d>0)u.U=new this.re(s,a),u.U.tt=u,c=u.U,this.h.U=c;else{let p=this.h.W,g=this.v(p.u,s);if(g===0){p.l=a;return}else if(g<0)p.W=new this.re(s,a),p.W.tt=p,c=p.W,this.h.W=c;else{if(l!==void 0){let h=l.o;if(h!==this.h){let b=this.v(h.u,s);if(b===0){h.l=a;return}else if(b>0){let y=h.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):(h.U=c,c.tt=h))}}}if(c===void 0)for(c=this.Y;;){let h=this.v(c.u,s);if(h>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(h<0){if(c.W===void 0){c.W=new this.re(s,a),c.W.tt=c,c=c.W;break}c=c.W}else{c.l=a;return}}}}return this.i+=1,c}I(s,a){for(;s;){let l=this.v(s.u,a);if(l<0)s=s.W;else if(l>0)s=s.U;else return s}return s||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(s,a){let l=s.o;if(l===this.h&&(0,r.throwIteratorAccessError)(),this.i===1)return l.u=a,!0;if(l===this.h.U)return this.v(l.B().u,a)>0?(l.u=a,!0):!1;if(l===this.h.W)return this.v(l.L().u,a)<0?(l.u=a,!0):!1;let c=l.L().u;if(this.v(c,a)>=0)return!1;let u=l.B().u;return this.v(u,a)<=0?!1:(l.u=a,!0)}eraseElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=0,l=this;return this.oe(this.Y,function(c){return s===a?(l.V(c),!0):(a+=1,!1)}),this.i}eraseElementByKey(s){if(this.i===0)return!1;let a=this.I(this.Y,s);return a===this.h?!1:(this.V(a),!0)}eraseElementByIterator(s){let a=s.o;a===this.h&&(0,r.throwIteratorAccessError)();let l=a.W===void 0;return s.iteratorType===0?l&&s.next():(!l||a.U===void 0)&&s.next(),this.V(a),s}forEach(s){let a=0;for(let l of this)s(l,a++,this)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a,l=0;for(let c of this){if(l===s){a=c;break}l+=1}return a}getHeight(){if(this.i===0)return 0;let s=function(a){return a?Math.max(s(a.U),s(a.W))+1:0};return s(this.Y)}},n=i;o.default=n}),il=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=kt(),t=xt(),r=class extends e.ContainerIterator{constructor(n,s,a){super(a),this.o=n,this.h=s,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,t.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,t.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let n=this.o,s=this.h.tt;if(n===this.h)return s?s.rt-1:0;let a=0;for(n.U&&(a+=n.U.rt);n!==s;){let l=n.tt;n===l.W&&(a+=1,l.U&&(a+=l.U.rt)),n=l}return a}},i=r;o.default=i}),Gu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(nl()),t=i(il()),r=xt();function i(l){return l&&l.t?l:{default:l}}var n=class ol 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 ol(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.insert(p)})}*K(l){l!==void 0&&(yield*this.K(l.U),yield l.u,yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(l,c){return this.M(l,void 0,c)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}union(l){let c=this;return l.forEach(function(u){c.insert(u)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;o.default=a}),Yu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=i(nl()),t=i(il()),r=xt();function i(l){return l&&l.t?l:{default:l}}var n=class sl 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 sl(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.default{constructor(l=[],c,u){super(c,u);let d=this;l.forEach(function(p){d.setElement(p[0],p[1])})}*K(l){l!==void 0&&(yield*this.K(l.U),yield[l.u,l.l],yield*this.K(l.W))}begin(){return new n(this.h.U||this.h,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this.h.W||this.h,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i===0)return;let l=this.h.U;return[l.u,l.l]}back(){if(this.i===0)return;let l=this.h.W;return[l.u,l.l]}lowerBound(l){let c=this.X(this.Y,l);return new n(c,this.h,this)}upperBound(l){let c=this.Z(this.Y,l);return new n(c,this.h,this)}reverseLowerBound(l){let c=this.$(this.Y,l);return new n(c,this.h,this)}reverseUpperBound(l){let c=this.rr(this.Y,l);return new n(c,this.h,this)}setElement(l,c,u){return this.M(l,c,u)}find(l){let c=this.I(this.Y,l);return new n(c,this.h,this)}getElementByKey(l){return this.I(this.Y,l).l}union(l){let c=this;return l.forEach(function(u){c.setElement(u[0],u[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},a=s;o.default=a}),al=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=e;function e(t){let r=typeof t;return r==="object"&&t!==null||r==="function"}}),ll=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.HashContainerIterator=o.HashContainer=void 0;var e=kt(),t=i(al()),r=xt();function i(a){return a&&a.t?a:{default:a}}var n=class extends e.ContainerIterator{constructor(a,l,c){super(c),this.o=a,this.h=l,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,r.throwIteratorAccessError)(),this.o=this.o.L,this})}};o.HashContainerIterator=n;var s=class extends e.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(a){let{L:l,B:c}=a;l.B=c,c.L=l,a===this.p&&(this.p=c),a===this._&&(this._=l),this.i-=1}M(a,l,c){c===void 0&&(c=(0,t.default)(a));let u;if(c){let d=a[this.HASH_TAG];if(d!==void 0)return this.H[d].l=l,this.i;Object.defineProperty(a,this.HASH_TAG,{value:this.H.length,configurable:!0}),u={u:a,l,L:this._,B:this.h},this.H.push(u)}else{let d=this.g[a];if(d)return d.l=l,this.i;u={u:a,l,L:this._,B:this.h},this.g[a]=u}return this.i===0?(this.p=u,this.h.B=u):this._.B=u,this._=u,this.h.L=u,++this.i}I(a,l){if(l===void 0&&(l=(0,t.default)(a)),l){let c=a[this.HASH_TAG];return c===void 0?this.h:this.H[c]}else return this.g[a]||this.h}clear(){let a=this.HASH_TAG;this.H.forEach(function(l){delete l.u[a]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(a,l){let c;if(l===void 0&&(l=(0,t.default)(a)),l){let u=a[this.HASH_TAG];if(u===void 0)return!1;delete a[this.HASH_TAG],c=this.H[u],delete this.H[u]}else{if(c=this.g[a],c===void 0)return!1;delete this.g[a]}return this.V(c),!0}eraseElementByIterator(a){let l=a.o;return l===this.h&&(0,r.throwIteratorAccessError)(),this.V(l),a.next()}eraseElementByPos(a){if(a<0||a>this.i-1)throw new RangeError;let l=this.p;for(;a--;)l=l.B;return this.V(l),this.i}};o.HashContainer=s}),Ju=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=ll(),t=xt(),r=class cl 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 cl(this.o,this.h,this.container,this.iteratorType)}},i=class extends e.HashContainer{constructor(s=[]){super();let a=this;s.forEach(function(l){a.insert(l)})}begin(){return new r(this.p,this.h,this)}end(){return new r(this.h,this.h,this)}rBegin(){return new r(this._,this.h,this,1)}rEnd(){return new r(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(s,a){return this.M(s,void 0,a)}getElementByPos(s){if(s<0||s>this.i-1)throw new RangeError;let a=this.p;for(;s--;)a=a.B;return a.u}find(s,a){let l=this.I(s,a);return new r(l,this.h,this)}forEach(s){let a=0,l=this.p;for(;l!==this.h;)s(l.u,a++,this),l=l.B}[Symbol.iterator](){return(function*(){let s=this.p;for(;s!==this.h;)yield s.u,s=s.B}).bind(this)()}},n=i;o.default=n}),Qu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),o.default=void 0;var e=ll(),t=i(al()),r=xt();function i(l){return l&&l.t?l:{default:l}}var n=class ul 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 ul(this.o,this.h,this.container,this.iteratorType)}},s=class extends e.HashContainer{constructor(l=[]){super();let c=this;l.forEach(function(u){c.setElement(u[0],u[1])})}begin(){return new n(this.p,this.h,this)}end(){return new n(this.h,this.h,this)}rBegin(){return new n(this._,this.h,this,1)}rEnd(){return new n(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(l,c,u){return this.M(l,c,u)}getElementByKey(l,c){if(c===void 0&&(c=(0,t.default)(l)),c){let d=l[this.HASH_TAG];return d!==void 0?this.H[d].l:void 0}let u=this.g[l];return u?u.l:void 0}getElementByPos(l){if(l<0||l>this.i-1)throw new RangeError;let c=this.p;for(;l--;)c=c.B;return[c.u,c.l]}find(l,c){let u=this.I(l,c);return new n(u,this.h,this)}forEach(l){let c=0,u=this.p;for(;u!==this.h;)l([u.u,u.l],c++,this),u=u.B}[Symbol.iterator](){return(function*(){let l=this.p;for(;l!==this.h;)yield[l.u,l.l],l=l.B}).bind(this)()}},a=s;o.default=a}),Xu=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"t",{value:!0}),Object.defineProperty(o,"Deque",{enumerable:!0,get:function(){return s.default}}),Object.defineProperty(o,"HashMap",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(o,"HashSet",{enumerable:!0,get:function(){return c.default}}),Object.defineProperty(o,"LinkList",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(o,"OrderedMap",{enumerable:!0,get:function(){return l.default}}),Object.defineProperty(o,"OrderedSet",{enumerable:!0,get:function(){return a.default}}),Object.defineProperty(o,"PriorityQueue",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(o,"Queue",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(o,"Stack",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(o,"Vector",{enumerable:!0,get:function(){return i.default}});var e=d(Fu()),t=d(qu()),r=d(Hu()),i=d(Wu()),n=d(zu()),s=d(Vu()),a=d(Gu()),l=d(Yu()),c=d(Ju()),u=d(Qu());function d(p){return p&&p.t?p:{default:p}}}),Zu=me((o,e)=>{le(),ue(),ce();var t=Xu().OrderedSet,r=vt()("number-allocator:trace"),i=vt()("number-allocator:error");function n(a,l){this.low=a,this.high=l}n.prototype.equals=function(a){return this.low===a.low&&this.high===a.high},n.prototype.compare=function(a){return this.low<a.low&&this.high<a.low?-1:a.low<this.low&&a.high<this.low?1:0};function s(a,l){if(!(this instanceof s))return new s(a,l);this.min=a,this.max=l,this.ss=new t([],(c,u)=>c.compare(u)),r("Create"),this.clear()}s.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low},s.prototype.alloc=function(){if(this.ss.size()===0)return r("alloc():empty"),null;let a=this.ss.begin(),l=a.pointer.low,c=a.pointer.high,u=l;return u+1<=c?this.ss.updateKeyByIterator(a,new n(l+1,c)):this.ss.eraseElementByPos(0),r("alloc():"+u),u},s.prototype.use=function(a){let l=new n(a,a),c=this.ss.lowerBound(l);if(!c.equals(this.ss.end())){let u=c.pointer.low,d=c.pointer.high;return c.pointer.equals(l)?(this.ss.eraseElementByIterator(c),r("use():"+a),!0):u>a?!1:u===a?(this.ss.updateKeyByIterator(c,new n(u+1,d)),r("use():"+a),!0):d===a?(this.ss.updateKeyByIterator(c,new n(u,d-1)),r("use():"+a),!0):(this.ss.updateKeyByIterator(c,new n(a+1,d)),this.ss.insert(new n(u,a-1)),r("use():"+a),!0)}return r("use():failed"),!1},s.prototype.free=function(a){if(a<this.min||a>this.max){i("free():"+a+" is out of range");return}let l=new n(a,a),c=this.ss.upperBound(l);if(c.equals(this.ss.end())){if(c.equals(this.ss.begin())){this.ss.insert(l);return}c.pre();let u=c.pointer.high;c.pointer.high+1===a?this.ss.updateKeyByIterator(c,new n(u,a)):this.ss.insert(l)}else if(c.equals(this.ss.begin()))if(a+1===c.pointer.low){let u=c.pointer.high;this.ss.updateKeyByIterator(c,new n(a,u))}else this.ss.insert(l);else{let u=c.pointer.low,d=c.pointer.high;c.pre();let p=c.pointer.low;c.pointer.high+1===a?a+1===u?(this.ss.eraseElementByIterator(c),this.ss.updateKeyByIterator(c,new n(p,d))):this.ss.updateKeyByIterator(c,new n(p,a)):a+1===u?(this.ss.eraseElementByIterator(c.next()),this.ss.insert(new n(a,d))):this.ss.insert(l)}r("free():"+a)},s.prototype.clear=function(){r("clear()"),this.ss.clear(),this.ss.insert(new n(this.min,this.max))},s.prototype.intervalCount=function(){return this.ss.size()},s.prototype.dump=function(){console.log("length:"+this.ss.size());for(let a of this.ss)console.log(a)},e.exports=s}),dl=me((o,e)=>{le(),ue(),ce();var t=Zu();e.exports.NumberAllocator=t}),ed=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=Bu(),t=dl(),r=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(i){i>0&&(this.aliasToTopic=new e.LRUCache({max:i}),this.topicToAlias={},this.numberAllocator=new t.NumberAllocator(1,i),this.max=i,this.length=0)}put(i,n){if(n===0||n>this.max)return!1;let s=this.aliasToTopic.get(n);return s&&delete this.topicToAlias[s],this.aliasToTopic.set(n,i),this.topicToAlias[i]=n,this.numberAllocator.use(n),this.length=this.aliasToTopic.size,!0}getTopicByAlias(i){return this.aliasToTopic.get(i)}getAliasByTopic(i){let n=this.topicToAlias[i];return typeof n<"u"&&this.aliasToTopic.get(n),n}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){return this.numberAllocator.firstVacant()||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};o.default=r}),td=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(o,"__esModule",{value:!0});var t=nn(),r=e(ed()),i=Zt(),n=(s,a)=>{s.log("_handleConnack");let{options:l}=s,c=l.protocolVersion===5?a.reasonCode:a.returnCode;if(clearTimeout(s.connackTimer),delete s.topicAliasSend,a.properties){if(a.properties.topicAliasMaximum){if(a.properties.topicAliasMaximum>65535){s.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}a.properties.topicAliasMaximum>0&&(s.topicAliasSend=new r.default(a.properties.topicAliasMaximum))}a.properties.serverKeepAlive&&l.keepalive&&(l.keepalive=a.properties.serverKeepAlive),a.properties.maximumPacketSize&&(l.properties||(l.properties={}),l.properties.maximumPacketSize=a.properties.maximumPacketSize)}if(c===0)s.reconnecting=!1,s._onConnect(a);else if(c>0){let u=new i.ErrorWithReasonCode(`Connection refused: ${t.ReasonCodes[c]}`,c);s.emit("error",u),s.options.reconnectOnConnackError&&s._cleanUp(!0)}};o.default=n}),rd=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(t,r,i)=>{t.log("handling pubrel packet");let n=typeof i<"u"?i:t.noop,{messageId:s}=r,a={cmd:"pubcomp",messageId:s};t.incomingStore.get(r,(l,c)=>{l?t._sendPacket(a,n):(t.emit("message",c.topic,c.payload,c),t.handleMessage(c,u=>{if(u)return n(u);t.incomingStore.del(c,t.noop),t._sendPacket(a,n)}))})};o.default=e}),nd=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(Du()),r=e(Uu()),i=e(td()),n=e(nn()),s=e(rd()),a=(l,c,u)=>{let{options:d}=l;if(d.protocolVersion===5&&d.properties&&d.properties.maximumPacketSize&&d.properties.maximumPacketSize<c.length)return l.emit("error",new Error(`exceeding packets size ${c.cmd}`)),l.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),l;switch(l.log("_handlePacket :: emitting packetreceive"),l.emit("packetreceive",c),c.cmd){case"publish":(0,t.default)(l,c,u);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":l.reschedulePing(),(0,n.default)(l,c),u();break;case"pubrel":l.reschedulePing(),(0,s.default)(l,c,u);break;case"connack":(0,i.default)(l,c),u();break;case"auth":l.reschedulePing(),(0,r.default)(l,c),u();break;case"pingresp":l.log("_handlePacket :: received pingresp"),l.reschedulePing(!0),u();break;case"disconnect":l.emit("disconnect",c),u();break;default:l.log("_handlePacket :: unknown command"),u();break}};o.default=a}),hl=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let t=this.nextId++;return this.nextId===65536&&(this.nextId=1),t}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(t){return!0}deallocate(t){}clear(){}};o.default=e}),id=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=class{aliasToTopic;max;length;constructor(t){this.aliasToTopic={},this.max=t}put(t,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=t,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(t){return this.aliasToTopic[t]}clear(){this.aliasToTopic={}}};o.default=e}),od=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(o,"__esModule",{value:!0}),o.TypedEventEmitter=void 0;var t=e((Ut(),Re(Pt))),r=Zt(),i=class{};o.TypedEventEmitter=i,(0,r.applyMixin)(i,t.default)}),on=me((o,e)=>{le(),ue(),ce();function t(r){"@babel/helpers - typeof";return e.exports=t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),sd=me((o,e)=>{le(),ue(),ce();var t=on().default;function r(i,n){if(t(i)!="object"||!i)return i;var s=i[Symbol.toPrimitive];if(s!==void 0){var a=s.call(i,n||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),ad=me((o,e)=>{le(),ue(),ce();var t=on().default,r=sd();function i(n){var s=r(n,"string");return t(s)=="symbol"?s:s+""}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),ld=me((o,e)=>{le(),ue(),ce();var t=ad();function r(i,n,s){return(n=t(n))in i?Object.defineProperty(i,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):i[n]=s,i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),cd=me((o,e)=>{le(),ue(),ce();function t(r){if(Array.isArray(r))return r}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ud=me((o,e)=>{le(),ue(),ce();function t(r,i){var n=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(n!=null){var s,a,l,c,u=[],d=!0,p=!1;try{if(l=(n=n.call(r)).next,i===0){if(Object(n)!==n)return;d=!1}else for(;!(d=(s=l.call(n)).done)&&(u.push(s.value),u.length!==i);d=!0);}catch(g){p=!0,a=g}finally{try{if(!d&&n.return!=null&&(c=n.return(),Object(c)!==c))return}finally{if(p)throw a}}return u}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),dd=me((o,e)=>{le(),ue(),ce();function t(r,i){(i==null||i>r.length)&&(i=r.length);for(var n=0,s=Array(i);n<i;n++)s[n]=r[n];return s}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),hd=me((o,e)=>{le(),ue(),ce();var t=dd();function r(i,n){if(i){if(typeof i=="string")return t(i,n);var s={}.toString.call(i).slice(8,-1);return s==="Object"&&i.constructor&&(s=i.constructor.name),s==="Map"||s==="Set"?Array.from(i):s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?t(i,n):void 0}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),fd=me((o,e)=>{le(),ue(),ce();function t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),pd=me((o,e)=>{le(),ue(),ce();var t=cd(),r=ud(),i=hd(),n=fd();function s(a,l){return t(a)||r(a,l)||i(a,l)||n()}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}),fl=me((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o):typeof define=="function"&&define.amd?define(["exports"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.fastUniqueNumbers={}))})(o,function(t){var r=function(g){return function(h){var b=g(h);return h.add(b),b}},i=function(g){return function(h,b){return g.set(h,b),b}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,s=536870912,a=s*2,l=function(g,h){return function(b){var y=h.get(b),w=y===void 0?b.size:y<a?y+1:0;if(!b.has(w))return g(b,w);if(b.size<s){for(;b.has(w);)w=Math.floor(Math.random()*a);return g(b,w)}if(b.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;b.has(w);)w=Math.floor(Math.random()*n);return g(b,w)}},c=new WeakMap,u=i(c),d=l(u,c),p=r(d);t.addUniqueNumber=p,t.generateUniqueNumber=d})}),md=me((o,e)=>{le(),ue(),ce();function t(i,n,s,a,l,c,u){try{var d=i[c](u),p=d.value}catch(g){return void s(g)}d.done?n(p):Promise.resolve(p).then(a,l)}function r(i){return function(){var n=this,s=arguments;return new Promise(function(a,l){var c=i.apply(n,s);function u(p){t(c,a,l,u,d,"next",p)}function d(p){t(c,a,l,u,d,"throw",p)}u(void 0)})}}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),pl=me((o,e)=>{le(),ue(),ce();function t(r,i){this.v=r,this.k=i}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),ml=me((o,e)=>{le(),ue(),ce();function t(r,i,n,s){var a=Object.defineProperty;try{a({},"",{})}catch{a=0}e.exports=t=function(l,c,u,d){function p(g,h){t(l,g,function(b){return this._invoke(g,h,b)})}c?a?a(l,c,{value:u,enumerable:!d,configurable:!d,writable:!d}):l[c]=u:(p("next",0),p("throw",1),p("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,i,n,s)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),gl=me((o,e)=>{le(),ue(),ce();var t=ml();function r(){var i,n,s=typeof Symbol=="function"?Symbol:{},a=s.iterator||"@@iterator",l=s.toStringTag||"@@toStringTag";function c(w,m,k,_){var v=m&&m.prototype instanceof d?m:d,E=Object.create(v.prototype);return t(E,"_invoke",(function(S,I,P){var O,j,T,F=0,$=P||[],U=!1,X={p:0,n:0,v:i,a:z,f:z.bind(i,4),d:function(W,ne){return O=W,j=0,T=i,X.n=ne,u}};function z(W,ne){for(j=W,T=ne,n=0;!U&&F&&!D&&n<$.length;n++){var D,G=$[n],L=X.p,Y=G[2];W>3?(D=Y===ne)&&(T=G[(j=G[4])?5:(j=3,3)],G[4]=G[5]=i):G[0]<=L&&((D=W<2&&L<G[1])?(j=0,X.v=ne,X.n=G[1]):L<Y&&(D=W<3||G[0]>ne||ne>Y)&&(G[4]=W,G[5]=ne,X.n=Y,j=0))}if(D||W>1)return u;throw U=!0,ne}return function(W,ne,D){if(F>1)throw TypeError("Generator is already running");for(U&&ne===1&&z(ne,D),j=ne,T=D;(n=j<2?i:T)||!U;){O||(j?j<3?(j>1&&(X.n=-1),z(j,T)):X.n=T:X.v=T);try{if(F=2,O){if(j||(W="next"),n=O[W]){if(!(n=n.call(O,T)))throw TypeError("iterator result is not an object");if(!n.done)return n;T=n.value,j<2&&(j=0)}else j===1&&(n=O.return)&&n.call(O),j<2&&(T=TypeError("The iterator does not provide a '"+W+"' method"),j=1);O=i}else if((n=(U=X.n<0)?T:S.call(I,X))!==u)break}catch(G){O=i,j=1,T=G}finally{F=1}}return{value:n,done:U}}})(w,k,_),!0),E}var u={};function d(){}function p(){}function g(){}n=Object.getPrototypeOf;var h=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),b=g.prototype=d.prototype=Object.create(h);function y(w){return Object.setPrototypeOf?Object.setPrototypeOf(w,g):(w.__proto__=g,t(w,l,"GeneratorFunction")),w.prototype=Object.create(b),w}return p.prototype=g,t(b,"constructor",g),t(g,"constructor",p),p.displayName="GeneratorFunction",t(g,l,"GeneratorFunction"),t(b),t(b,l,"Generator"),t(b,a,function(){return this}),t(b,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:y}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),bl=me((o,e)=>{le(),ue(),ce();var t=pl(),r=ml();function i(n,s){function a(c,u,d,p){try{var g=n[c](u),h=g.value;return h instanceof t?s.resolve(h.v).then(function(b){a("next",b,d,p)},function(b){a("throw",b,d,p)}):s.resolve(h).then(function(b){g.value=b,d(g)},function(b){return a("throw",b,d,p)})}catch(b){p(b)}}var l;this.next||(r(i.prototype),r(i.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(c,u,d){function p(){return new s(function(g,h){a(c,d,g,h)})}return l=l?l.then(p,p):p()},!0)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),yl=me((o,e)=>{le(),ue(),ce();var t=gl(),r=bl();function i(n,s,a,l,c){return new r(t().w(n,s,a,l),c||Promise)}e.exports=i,e.exports.__esModule=!0,e.exports.default=e.exports}),gd=me((o,e)=>{le(),ue(),ce();var t=yl();function r(i,n,s,a,l){var c=t(i,n,s,a,l);return c.next().then(function(u){return u.done?u.value:c.next()})}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),bd=me((o,e)=>{le(),ue(),ce();function t(r){var i=Object(r),n=[];for(var s in i)n.unshift(s);return function a(){for(;n.length;)if((s=n.pop())in i)return a.value=s,a.done=!1,a;return a.done=!0,a}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}),yd=me((o,e)=>{le(),ue(),ce();var t=on().default;function r(i){if(i!=null){var n=i[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],s=0;if(n)return n.call(i);if(typeof i.next=="function")return i;if(!isNaN(i.length))return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}}}throw new TypeError(t(i)+" is not iterable")}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}),vd=me((o,e)=>{le(),ue(),ce();var t=pl(),r=gl(),i=gd(),n=yl(),s=bl(),a=bd(),l=yd();function c(){var u=r(),d=u.m(c),p=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function g(y){var w=typeof y=="function"&&y.constructor;return!!w&&(w===p||(w.displayName||w.name)==="GeneratorFunction")}var h={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(_,v){return m(k.a,h[_],v)},delegateYield:function(_,v,E){return w.resultName=v,m(k.d,l(_),E)},finish:function(_){return m(k.f,_)}},m=function(_,v,E){k.p=w.prev,k.n=w.next;try{return _(v,E)}finally{w.next=k.n}}),w.resultName&&(w[w.resultName]=k.v,w.resultName=void 0),w.sent=k.v,w.next=k.n;try{return 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,_){return(g(w)?n:i)(b(y),w,m,k,_)},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}),wd=me((o,e)=>{le(),ue(),ce();var t=vd()();e.exports=t;try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}}),kd=me((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,ld(),pd(),fl(),md(),wd()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(o,function(t,r,i,n,s,a){var l=function(m){return typeof m.start=="function"},c=new WeakMap;function u(m,k){var _=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),_.push.apply(_,v)}return _}function d(m){for(var k=1;k<arguments.length;k++){var _=arguments[k]!=null?arguments[k]:{};k%2?u(Object(_),!0).forEach(function(v){r(m,v,_[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(_)):u(Object(_)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(_,v))})}return m}var p=function(m){return d(d({},m),{},{connect:function(k){var _=k.call;return s(a.mark(function v(){var E,S,I,P;return a.wrap(function(O){for(;;)switch(O.prev=O.next){case 0:return E=new MessageChannel,S=E.port1,I=E.port2,O.next=1,_("connect",{port:S},[S]);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 _=k.call;return(function(){var v=s(a.mark(function E(S){var I;return a.wrap(function(P){for(;;)switch(P.prev=P.next){case 0:if(I=c.get(S),I!==void 0){P.next=1;break}throw new Error("The given port is not connected.");case 1:return P.next=2,_("disconnect",{portId:I});case 2:case"end":return P.stop()}},E)}));return function(E){return v.apply(this,arguments)}})()},isSupported:function(k){var _=k.call;return function(){return _("isSupported")}}})};function g(m,k){var _=Object.keys(m);if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(m);k&&(v=v.filter(function(E){return Object.getOwnPropertyDescriptor(m,E).enumerable})),_.push.apply(_,v)}return _}function h(m){for(var k=1;k<arguments.length;k++){var _=arguments[k]!=null?arguments[k]:{};k%2?g(Object(_),!0).forEach(function(v){r(m,v,_[v])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(_)):g(Object(_)).forEach(function(v){Object.defineProperty(m,v,Object.getOwnPropertyDescriptor(_,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=p(m);return function(_){var v=y(_);_.addEventListener("message",function($){var U=$.data,X=U.id;if(X!==null&&v.has(X)){var z=v.get(X),W=z.reject,ne=z.resolve;v.delete(X),U.error===void 0?ne(U.result):W(new Error(U.error.message))}}),l(_)&&_.start();for(var E=function($){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,X=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(z,W){var ne=n.generateUniqueNumber(v);v.set(ne,{reject:W,resolve:z}),U===null?_.postMessage({id:ne,method:$},X):_.postMessage({id:ne,method:$,params:U},X)})},S=function($,U){var X=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];_.postMessage({id:null,method:$,params:U},X)},I={},P=0,O=Object.entries(k);P<O.length;P++){var j=i(O[P],2),T=j[0],F=j[1];I=h(h({},I),{},r({},T,F({call:E,notify:S})))}return h({},I)}};t.createBroker=w})}),xd=me((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,on(),kd(),fl()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(o,function(t,r,i,n){var s=new Map([[0,null]]),a=new Map([[0,null]]),l=i.createBroker({clearInterval:function(u){var d=u.call;return function(p){r(s.get(p))==="symbol"&&(s.set(p,null),d("clear",{timerId:p,timerType:"interval"}).then(function(){s.delete(p)}))}},clearTimeout:function(u){var d=u.call;return function(p){r(a.get(p))==="symbol"&&(a.set(p,null),d("clear",{timerId:p,timerType:"timeout"}).then(function(){a.delete(p)}))}},setInterval:function(u){var d=u.call;return function(p){for(var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;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 _=s.get(m);if(_===void 0)throw new Error("The timer is in an undefined state.");_===w&&(p.apply(void 0,b),s.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,h=arguments.length,b=new Array(h>2?h-2:0),y=2;y<h;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),p.apply(void 0,b))}),m}}}),c=function(u){var d=new Worker(u);return l(d)};t.load=c,t.wrap=l})}),_d=me((o,e)=>{le(),ue(),ce(),(function(t,r){typeof o=="object"&&typeof e<"u"?r(o,xd()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],r):(t=typeof globalThis<"u"?globalThis:t||self,r(t.workerTimers={},t.workerTimersBroker))})(o,function(t,r){var i=function(d,p){var g=null;return function(){if(g!==null)return g;var h=new Blob([p],{type:"application/javascript; charset=utf-8"}),b=URL.createObjectURL(h);return g=d(b),setTimeout(function(){return URL.revokeObjectURL(b)}),g}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n},e.exports.__esModule=!0,e.exports.default=e.exports},122:(e,t,r)=>{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<u?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*u);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?d(Object(r),!0).forEach((function(t){n(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):d(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var x=new Map,y=function(e,n,u){return v(v({},n),{},{connect:function(t){var r=t.port;r.start();var u=e(r,n),a=o.generateUniqueNumber(x);return x.set(a,(function(){u(),r.close(),x.delete(a)})),{result:a}},disconnect:function(e){var t=e.portId,r=x.get(t);if(void 0===r)throw f(t);return r(),{result:null}},isSupported:function(){var e=t(r.mark((function e(){var t,n,o;return r.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,p();case 1:if(!e.sent){e.next=5;break}if(!((t=u())instanceof Promise)){e.next=3;break}return e.next=2,t;case 2:o=e.sent,e.next=4;break;case 3:o=t;case 4:return n=o,e.abrupt("return",{result:n});case 5:return e.abrupt("return",{result:!1});case 6:case"end":return e.stop()}}),e)})));function n(){return e.apply(this,arguments)}return n}()})},b=function(e,t){var r=y(b,t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r<f.length;r++){var o,u=f[r],d=p.p,v=u[2];e>3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&d<u[1])?(a=0,p.v=n,p.n=u[1]):d<v&&(o=e<3||u[0]>n||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,s=i(r.load,n),a=function(d){return s().clearInterval(d)},l=function(d){return s().clearTimeout(d)},c=function(){var d;return(d=s()).setInterval.apply(d,arguments)},u=function(){var d;return(d=s()).setTimeout.apply(d,arguments)};t.clearInterval=a,t.clearTimeout=l,t.setInterval=c,t.setTimeout=u})}),sn=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.isReactNativeBrowser=o.isWebWorker=void 0;var e=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&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",i=e()||t()||r();o.isWebWorker=t(),o.isReactNativeBrowser=r(),o.default=i}),Sd=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(c,u,d,p){p===void 0&&(p=d);var g=Object.getOwnPropertyDescriptor(u,d);(!g||("get"in g?!u.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return u[d]}}),Object.defineProperty(c,p,g)}:function(c,u,d,p){p===void 0&&(p=d),c[p]=u[d]}),t=o&&o.__setModuleDefault||(Object.create?function(c,u){Object.defineProperty(c,"default",{enumerable:!0,value:u})}:function(c,u){c.default=u}),r=o&&o.__importStar||(function(){var c=function(u){return c=Object.getOwnPropertyNames||function(d){var p=[];for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(p[p.length]=g);return p},c(u)};return function(u){if(u&&u.__esModule)return u;var d={};if(u!=null)for(var p=c(u),g=0;g<p.length;g++)p[g]!=="default"&&e(d,u,p[g]);return t(d,u),d}})();Object.defineProperty(o,"__esModule",{value:!0});var i=_d(),n=r(sn()),s={set:i.setInterval,clear:i.clearInterval},a={set:(c,u)=>setInterval(c,u),clear:c=>clearInterval(c)},l=c=>{switch(c){case"native":return a;case"worker":return s;default:return n.default&&!n.isWebWorker&&!n.isReactNativeBrowser?s:a}};o.default=l}),vl=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(o,"__esModule",{value:!0});var t=e(Sd()),r=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(i,n){this.client=i,this.timer=typeof n=="object"&&"set"in n&&"clear"in n?n:(0,t.default)(n),this.setKeepalive(i.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(i){if(i*=1e3,isNaN(i)||i<=0||i>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${i}`);this._keepalive=i,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${i}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let i=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+i,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};o.default=r}),Pi=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(v,E,S,I){I===void 0&&(I=S);var P=Object.getOwnPropertyDescriptor(E,S);(!P||("get"in P?!E.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return E[S]}}),Object.defineProperty(v,I,P)}:function(v,E,S,I){I===void 0&&(I=S),v[I]=E[S]}),t=o&&o.__setModuleDefault||(Object.create?function(v,E){Object.defineProperty(v,"default",{enumerable:!0,value:E})}:function(v,E){v.default=E}),r=o&&o.__importStar||(function(){var v=function(E){return v=Object.getOwnPropertyNames||function(S){var I=[];for(var P in S)Object.prototype.hasOwnProperty.call(S,P)&&(I[I.length]=P);return I},v(E)};return function(E){if(E&&E.__esModule)return E;var S={};if(E!=null)for(var I=v(E),P=0;P<I.length;P++)I[P]!=="default"&&e(S,E,I[P]);return t(S,E),S}})(),i=o&&o.__importDefault||function(v){return v&&v.__esModule?v:{default:v}};Object.defineProperty(o,"__esModule",{value:!0});var n=i(Nu()),s=Ft(),a=i(ju()),l=i(vt()),c=r(Ga()),u=i(Ya()),d=i(nd()),p=i(hl()),g=i(id()),h=Zt(),b=od(),y=i(vl()),w=r(sn()),m=globalThis.setImmediate||((...v)=>{let E=v.shift();(0,h.nextTick)(()=>{E(...v)})}),k={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},_=class Oi extends b.TypedEventEmitter{static VERSION=h.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(E,S){super(),this.options=S||{};for(let I in k)typeof this.options[I]>"u"?this.options[I]=k[I]:this.options[I]=S[I];this.log=this.options.log||(0,l.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",Oi.VERSION),w.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",w.default?"browser":"node"),this.log("MqttClient :: options.protocol",S.protocol),this.log("MqttClient :: options.protocolVersion",S.protocolVersion),this.log("MqttClient :: options.username",S.username),this.log("MqttClient :: options.keepalive",S.keepalive),this.log("MqttClient :: options.reconnectPeriod",S.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",S.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",S.properties?S.properties.topicAliasMaximum:void 0),this.options.clientId=typeof S.clientId=="string"?S.clientId:Oi.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=S.protocolVersion===5&&S.customHandleAcks?S.customHandleAcks:(...I)=>{I[3](null,0)},this.options.writeCache||(n.default.writeToStream.cacheNumbers=!1),this.streamBuilder=E,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new p.default:this.options.messageIdProvider,this.outgoingStore=S.outgoingStore||new u.default,this.incomingStore=S.incomingStore||new u.default,this.queueQoSZero=S.queueQoSZero===void 0?!0:S.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,S.properties&&S.properties.topicAliasMaximum>0&&(S.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new g.default(S.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:I}=this,P=()=>{let O=I.shift();this.log("deliver :: entry %o",O);let j=null;if(!O){this._resubscribe();return}j=O.packet,this.log("deliver :: call _sendPacket for %o",j);let T=!0;j.messageId&&j.messageId!==0&&(this.messageIdProvider.register(j.messageId)||(T=!1)),T?this._sendPacket(j,F=>{O.cb&&O.cb(F),P()}):(this.log("messageId: %d has already used. The message is skipped and removed.",j.messageId),P())};this.log("connect :: sending queued packets"),P()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(E,S){S()}handleMessage(E,S){S()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let E=new s.Writable,S=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),S.on("packet",$=>{this.log("parser :: on packet push to packets array."),P.push($)});let O=()=>{this.log("work :: getting next packet in queue");let $=P.shift();if($)this.log("work :: packet pulled from queue"),(0,d.default)(this,$,j);else{this.log("work :: no packets in queue");let U=I;I=null,this.log("work :: done flag is %s",!!U),U&&U()}},j=()=>{if(P.length)(0,h.nextTick)(O);else{let $=I;I=null,$()}};E._write=($,U,X)=>{I=X,this.log("writable stream :: parsing buffer"),S.parse($),O()};let T=$=>{this.log("streamErrorHandler :: error",$.message),$.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",$)):this.noop($)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(E),this.stream.on("error",T),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let 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),S.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let $={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket($)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(E,S,I,P){this.log("publish :: message `%s` to topic `%s`",S,E);let{options:O}=this;typeof I=="function"&&(P=I,I=null),I=I||{},I={qos:0,retain:!1,dup:!1,...I};let{qos:j,retain:T,dup:F,properties:$,cbStorePut:U}=I;if(this._checkDisconnecting(P))return this;let X=()=>{let z=0;if((j===1||j===2)&&(z=this._nextId(),z===null))return this.log("No messageId left"),!1;let W={cmd:"publish",topic:E,payload:S,qos:j,retain:T,messageId:z,dup:F};switch(O.protocolVersion===5&&(W.properties=$),this.log("publish :: qos",j),j){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||!X())&&this._storeProcessingQueue.push({invoke:X,cbStorePut:I.cbStorePut,callback:P}),this}publishAsync(E,S,I){return new Promise((P,O)=>{this.publish(E,S,I,(j,T)=>{j?O(j):P(T)})})}subscribe(E,S,I){let P=this.options.protocolVersion;typeof S=="function"&&(I=S),I=I||this.noop;let O=!1,j=[];typeof E=="string"?(E=[E],j=E):Array.isArray(E)?j=E:typeof E=="object"&&(O=E.resubscribe,delete E.resubscribe,j=Object.keys(E));let T=c.validateTopics(j);if(T!==null)return m(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),S={...F,...S};let{properties:$}=S,U=[],X=(ne,D)=>{if(D=D||S,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,ne)||this._resubscribeTopics[ne].qos<D.qos||O){let G={topic:ne,qos:D.qos};P===5&&(G.nl=D.nl,G.rap=D.rap,G.rh=D.rh,G.properties=$),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",G.topic,G.qos),U.push(G)}};if(Array.isArray(E)?E.forEach(ne=>{this.log("subscribe: array topic %s",ne),X(ne)}):Object.keys(E).forEach(ne=>{this.log("subscribe: object topic %s, %o",ne,E[ne]),X(ne,E[ne])}),!U.length)return I(null,[]),this;let z=(ne,D)=>{let G={cmd:"subscribe",subscriptions:ne,messageId:D};if($&&(G.properties=$),this.options.resubscribe){this.log("subscribe :: resubscribe true");let Y=[];ne.forEach(pe=>{if(this.options.reconnectPeriod>0){let te={qos:pe.qos};P===5&&(te.nl=pe.nl||!1,te.rap=pe.rap||!1,te.rh=pe.rh||0,te.properties=pe.properties),this._resubscribeTopics[pe.topic]=te,Y.push(pe.topic)}}),this.messageIdToTopic[G.messageId]=Y}let L=new Promise((Y,pe)=>{this.outgoing[G.messageId]={volatile:!0,cb(te,ve){if(!te){let{granted:J}=ve;for(let R=0;R<J.length;R+=1)ne[R].qos=J[R]}te?pe(new h.ErrorWithSubackPacket(te.message,ve)):Y(ve)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(G),L},W=()=>{let ne=this.options.subscribeBatchSize??U.length,D=[];for(let G=0;G<U.length;G+=ne){let L=U.slice(G,G+ne),Y=this._nextId();if(Y===null)return this.log("No messageId left"),!1;D.push(z(L,Y))}return Promise.all(D).then(G=>{I(null,U,G.at(-1))}).catch(G=>{I(G,U,G.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!W())&&this._storeProcessingQueue.push({invoke:W,callback:I}),this}subscribeAsync(E,S){return new Promise((I,P)=>{this.subscribe(E,S,(O,j)=>{O?P(O):I(j)})})}unsubscribe(E,S,I){typeof E=="string"&&(E=[E]),typeof S=="function"&&(I=S),I=I||this.noop;let P=c.validateTopics(E);if(P!==null)return m(I,new Error(`Invalid topic ${P}`)),this;if(this._checkDisconnecting(I))return this;let O=()=>{let j=this._nextId();if(j===null)return this.log("No messageId left"),!1;let T={cmd:"unsubscribe",messageId:j,unsubscriptions:[]};return typeof E=="string"?T.unsubscriptions=[E]:Array.isArray(E)&&(T.unsubscriptions=E),this.options.resubscribe&&T.unsubscriptions.forEach(F=>{delete this._resubscribeTopics[F]}),typeof S=="object"&&S.properties&&(T.properties=S.properties),this.outgoing[T.messageId]={volatile:!0,cb:I},this.log("unsubscribe: call _sendPacket"),this._sendPacket(T),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!O())&&this._storeProcessingQueue.push({invoke:O,callback:I}),this}unsubscribeAsync(E,S){return new Promise((I,P)=>{this.unsubscribe(E,S,(O,j)=>{O?P(O):I(j)})})}end(E,S,I){this.log("end :: (%s)",this.options.clientId),(E==null||typeof E!="boolean")&&(I=I||S,S=E,E=!1),typeof S!="object"&&(I=I||S,S=null),this.log("end :: cb? %s",!!I),(!I||typeof I!="function")&&(I=this.noop);let P=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(j=>{this.outgoingStore.close(T=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),I){let F=j||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,E),this._cleanUp(E,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,h.nextTick)(P)},S)};return this.disconnecting?(I(),this):(this._clearReconnect(),this.disconnecting=!0,!E&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,O,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),O()),this)}endAsync(E,S){return new Promise((I,P)=>{this.end(E,S,O=>{O?P(O):I()})})}removeOutgoingMessage(E){if(this.outgoing[E]){let{cb:S}=this.outgoing[E];this._removeOutgoingAndStoreMessage(E,()=>{S(new Error("Message removed"))})}return this}reconnect(E){this.log("client reconnect");let S=()=>{E?(this.options.incomingStore=E.incomingStore,this.options.outgoingStore=E.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new u.default,this.outgoingStore=this.options.outgoingStore||new u.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=S:S(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(E=>{this.outgoing[E].volatile&&typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(E=>{typeof this.outgoing[E].cb=="function"&&(this.outgoing[E].cb(new Error("Connection closed")),delete this.outgoing[E])}))}_removeTopicAliasAndRecoverTopicName(E){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",S,I),I.length===0){if(typeof S>"u")return new Error("Unregistered Topic Alias");if(I=this.topicAliasSend.getTopicByAlias(S),typeof I>"u")return new Error("Unregistered Topic Alias");E.topic=I}S&&delete E.properties.topicAlias}_checkDisconnecting(E){return this.disconnecting&&(E&&E!==this.noop?E(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(E,S,I={}){if(S&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",S)),this.log("_cleanUp :: forced? %s",E),E)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let 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(),S&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",S),S())}_storeAndSend(E,S,I){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",E.cmd);let P=E,O;if(P.cmd==="publish"&&(P=(0,a.default)(E),O=this._removeTopicAliasAndRecoverTopicName(P),O))return S&&S(O);this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I(),this._writePacket(E,S)})}_applyTopicAlias(E){if(this.options.protocolVersion===5&&E.cmd==="publish"){let S;E.properties&&(S=E.properties.topicAlias);let I=E.topic.toString();if(this.topicAliasSend)if(S){if(I.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",I,S),!this.topicAliasSend.put(I,S)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}else I.length!==0&&(this.options.autoAssignTopicAlias?(S=this.topicAliasSend.getAliasByTopic(I),S?(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",I,S)):(S=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(I,S),E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",I,S))):this.options.autoUseTopicAlias&&(S=this.topicAliasSend.getAliasByTopic(I),S&&(E.topic="",E.properties={...E.properties,topicAlias:S},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",I,S))));else if(S)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",I,S),new Error("Sending Topic Alias out of range")}}_noop(E){this.log("noop ::",E)}_writePacket(E,S){this.log("_writePacket :: packet: %O",E),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",E),this.log("_writePacket :: writing to stream");let I=n.default.writeToStream(E,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",I),!I&&S&&S!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",S)):S&&(this.log("_writePacket :: invoking cb"),S())}_sendPacket(E,S,I,P){this.log("_sendPacket :: (%s) :: start",this.options.clientId),I=I||this.noop,S=S||this.noop;let O=this._applyTopicAlias(E);if(O){S(O);return}if(!this.connected){if(E.cmd==="auth"){this._writePacket(E,S);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(E,S,I);return}if(P){this._writePacket(E,S);return}switch(E.cmd){case"publish":break;case"pubrel":this._storeAndSend(E,S,I);return;default:this._writePacket(E,S);return}switch(E.qos){case 2:case 1:this._storeAndSend(E,S,I);break;default:this._writePacket(E,S);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(E,S,I){this.log("_storePacket :: packet: %o",E),this.log("_storePacket :: cb? %s",!!S),I=I||this.noop;let P=E;if(P.cmd==="publish"){P=(0,a.default)(E);let j=this._removeTopicAliasAndRecoverTopicName(P);if(j)return S&&S(j)}let O=P.qos||0;O===0&&this.queueQoSZero||P.cmd!=="publish"?this.queue.push({packet:P,cb:S}):O>0?(S=this.outgoing[P.messageId]?this.outgoing[P.messageId].cb:null,this.outgoingStore.put(P,j=>{if(j)return S&&S(j);I()})):S&&S(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new y.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(E=!1){this.keepaliveManager&&this.options.keepalive&&(E||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let E=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&E.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let S=0;S<E.length;S++){let I={};I[E[S]]=this._resubscribeTopics[E[S]],I.resubscribe=!0,this.subscribe(I,{properties:I[E[S]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(E){if(this.disconnected){this.emit("connect",E);return}this.connackPacket=E,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;let S=()=>{let I=this.outgoingStore.createStream(),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 j=()=>{if(!I)return;let T=I.read(1),F;if(!T){I.once("readable",j);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[T.messageId]){j();return}!this.disconnecting&&!this.reconnectTimer?(F=this.outgoing[T.messageId]?this.outgoing[T.messageId].cb:null,this.outgoing[T.messageId]={volatile:!1,cb($,U){F&&F($,U),j()}},this._packetIdsDuringStoreProcessing[T.messageId]=!0,this.messageIdProvider.register(T.messageId)?this._sendPacket(T,void 0,void 0,!0):this.log("messageId: %d has already used.",T.messageId)):I.destroy&&I.destroy()};I.on("end",()=>{let T=!0;for(let F in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[F]){T=!1;break}this.removeListener("close",P),T?(O(),this._invokeAllStoreProcessingQueue(),this.emit("connect",E)):S()}),j()};S()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let E=this._storeProcessingQueue[0];if(E&&E.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let E of this._storeProcessingQueue)E.cbStorePut&&E.cbStorePut(new Error("Connection closed")),E.callback&&E.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(E,S){delete this.outgoing[E],this.outgoingStore.del({messageId:E},(I,P)=>{S(I,P),this.messageIdProvider.deallocate(E),this._invokeStoreProcessingQueue()})}};o.default=_}),Ed=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=dl(),t=class{numberAllocator;lastId;constructor(){this.numberAllocator=new e.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(r){return this.numberAllocator.use(r)}deallocate(r){this.numberAllocator.free(r)}clear(){this.numberAllocator.clear()}};o.default=t});function Ad(){if(Li)return Ar;Li=!0;let o=2147483647,e=36,t=1,r=26,i=38,n=700,s=72,a=128,l="-",c=/^xn--/,u=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},g=e-t,h=Math.floor,b=String.fromCharCode;function y(O){throw new RangeError(p[O])}function w(O,j){let T=[],F=O.length;for(;F--;)T[F]=j(O[F]);return T}function m(O,j){let T=O.split("@"),F="";T.length>1&&(F=T[0]+"@",O=T[1]),O=O.replace(d,".");let $=O.split("."),U=w($,j).join(".");return F+U}function k(O){let j=[],T=0,F=O.length;for(;T<F;){let $=O.charCodeAt(T++);if($>=55296&&$<=56319&&T<F){let U=O.charCodeAt(T++);(U&64512)==56320?j.push((($&1023)<<10)+(U&1023)+65536):(j.push($),T--)}else j.push($)}return j}let _=O=>String.fromCodePoint(...O),v=function(O){return O>=48&&O<58?26+(O-48):O>=65&&O<91?O-65:O>=97&&O<123?O-97:e},E=function(O,j){return O+22+75*(O<26)-((j!=0)<<5)},S=function(O,j,T){let F=0;for(O=T?h(O/n):O>>1,O+=h(O/j);O>g*r>>1;F+=e)O=h(O/g);return h(F+(g+1)*O/(O+i))},I=function(O){let j=[],T=O.length,F=0,$=a,U=s,X=O.lastIndexOf(l);X<0&&(X=0);for(let z=0;z<X;++z)O.charCodeAt(z)>=128&&y("not-basic"),j.push(O.charCodeAt(z));for(let z=X>0?X+1:0;z<T;){let W=F;for(let D=1,G=e;;G+=e){z>=T&&y("invalid-input");let L=v(O.charCodeAt(z++));L>=e&&y("invalid-input"),L>h((o-F)/D)&&y("overflow"),F+=L*D;let Y=G<=U?t:G>=U+r?r:G-U;if(L<Y)break;let pe=e-Y;D>h(o/pe)&&y("overflow"),D*=pe}let ne=j.length+1;U=S(F-W,ne,W==0),h(F/ne)>o-$&&y("overflow"),$+=h(F/ne),F%=ne,j.splice(F++,0,$)}return String.fromCodePoint(...j)},P=function(O){let j=[];O=k(O);let T=O.length,F=a,$=0,U=s;for(let W of O)W<128&&j.push(b(W));let X=j.length,z=X;for(X&&j.push(l);z<T;){let W=o;for(let D of O)D>=F&&D<W&&(W=D);let ne=z+1;W-F>h((o-$)/ne)&&y("overflow"),$+=(W-F)*ne,F=W;for(let D of O)if(D<F&&++$>o&&y("overflow"),D===F){let G=$;for(let L=e;;L+=e){let Y=L<=U?t:L>=U+r?r:L-U;if(G<Y)break;let pe=G-Y,te=e-Y;j.push(b(E(Y+pe%te,0))),G=h(pe/te)}j.push(b(E(G,0))),U=S($,ne,z===X),$=0,++z}++$,++F}return j.join("")};return Ar={version:"2.3.1",ucs2:{decode:k,encode:_},decode:I,encode:P,toASCII:function(O){return m(O,function(j){return u.test(j)?"xn--"+P(j):j})},toUnicode:function(O){return m(O,function(j){return c.test(j)?I(j.slice(4).toLowerCase()):j})}},Ar}var Ar,Li,Tt,Id=Qe(()=>{le(),ue(),ce(),Ar={},Li=!1,Tt=Ad(),Tt.decode,Tt.encode,Tt.toASCII,Tt.toUnicode,Tt.ucs2,Tt.version});function Td(){return Ni||(Ni=!0,Mi=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var o={},e=Symbol("test"),t=Object(e);if(typeof e=="string"||Object.prototype.toString.call(e)!=="[object Symbol]"||Object.prototype.toString.call(t)!=="[object Symbol]")return!1;var r=42;o[e]=r;for(e in o)return!1;if(typeof Object.keys=="function"&&Object.keys(o).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(o).length!==0)return!1;var i=Object.getOwnPropertySymbols(o);if(i.length!==1||i[0]!==e||!Object.prototype.propertyIsEnumerable.call(o,e))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var n=Object.getOwnPropertyDescriptor(o,e);if(n.value!==r||n.enumerable!==!0)return!1}return!0}),Mi}function Cd(){return ji||(ji=!0,Ri=Error),Ri}function Pd(){return $i||($i=!0,Di=EvalError),Di}function Od(){return Bi||(Bi=!0,Ui=RangeError),Ui}function Ld(){return qi||(qi=!0,Fi=ReferenceError),Fi}function wl(){return Wi||(Wi=!0,Hi=SyntaxError),Hi}function br(){return Vi||(Vi=!0,zi=TypeError),zi}function Md(){return Gi||(Gi=!0,Ki=URIError),Ki}function Nd(){if(Yi)return Ir;Yi=!0;var o=typeof Symbol<"u"&&Symbol,e=Td();return Ir=function(){return typeof o!="function"||typeof Symbol!="function"||typeof o("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Ir}function Rd(){if(Ji)return Tr;Ji=!0;var o={__proto__:null,foo:{}},e=Object;return Tr=function(){return{__proto__:o}.foo===o.foo&&!(o instanceof e)},Tr}function jd(){if(Qi)return Cr;Qi=!0;var o="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,t=Math.max,r="[object Function]",i=function(a,l){for(var c=[],u=0;u<a.length;u+=1)c[u]=a[u];for(var d=0;d<l.length;d+=1)c[d+a.length]=l[d];return c},n=function(a,l){for(var c=[],u=l,d=0;u<a.length;u+=1,d+=1)c[d]=a[u];return c},s=function(a,l){for(var c="",u=0;u<a.length;u+=1)c+=a[u],u+1<a.length&&(c+=l);return c};return Cr=function(a){var l=this;if(typeof l!="function"||e.apply(l)!==r)throw new TypeError(o+l);for(var c=n(arguments,1),u,d=function(){if(this instanceof u){var y=l.apply(this,i(c,arguments));return Object(y)===y?y:this}return l.apply(a,i(c,arguments))},p=t(0,l.length-c.length),g=[],h=0;h<p;h++)g[h]="$"+h;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},Cr}function Po(){if(Xi)return Pr;Xi=!0;var o=jd();return Pr=Function.prototype.bind||o,Pr}function Dd(){if(Zi)return Or;Zi=!0;var o=Function.prototype.call,e=Object.prototype.hasOwnProperty,t=Po();return Or=t.call(o,e),Or}function er(){if(eo)return Lr;eo=!0;var o,e=Cd(),t=Pd(),r=Od(),i=Ld(),n=wl(),s=br(),a=Md(),l=Function,c=function(z){try{return l('"use strict"; return ('+z+").constructor;")()}catch{}},u=Object.getOwnPropertyDescriptor;if(u)try{u({},"")}catch{u=null}var d=function(){throw new s},p=u?(function(){try{return arguments.callee,d}catch{try{return u(arguments,"callee").get}catch{return d}}})():d,g=Nd()(),h=Rd()(),b=Object.getPrototypeOf||(h?function(z){return z.__proto__}:null),y={},w=typeof Uint8Array>"u"||!b?o:b(Uint8Array),m={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?o:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?o:ArrayBuffer,"%ArrayIteratorPrototype%":g&&b?b([][Symbol.iterator]()):o,"%AsyncFromSyncIteratorPrototype%":o,"%AsyncFunction%":y,"%AsyncGenerator%":y,"%AsyncGeneratorFunction%":y,"%AsyncIteratorPrototype%":y,"%Atomics%":typeof Atomics>"u"?o:Atomics,"%BigInt%":typeof BigInt>"u"?o:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?o:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?o:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?o:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":t,"%Float32Array%":typeof Float32Array>"u"?o:Float32Array,"%Float64Array%":typeof Float64Array>"u"?o:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?o:FinalizationRegistry,"%Function%":l,"%GeneratorFunction%":y,"%Int8Array%":typeof Int8Array>"u"?o:Int8Array,"%Int16Array%":typeof Int16Array>"u"?o:Int16Array,"%Int32Array%":typeof Int32Array>"u"?o:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":g&&b?b(b([][Symbol.iterator]())):o,"%JSON%":typeof JSON=="object"?JSON:o,"%Map%":typeof Map>"u"?o:Map,"%MapIteratorPrototype%":typeof Map>"u"||!g||!b?o:b(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?o:Promise,"%Proxy%":typeof Proxy>"u"?o:Proxy,"%RangeError%":r,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?o:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?o:Set,"%SetIteratorPrototype%":typeof Set>"u"||!g||!b?o:b(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?o:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":g&&b?b(""[Symbol.iterator]()):o,"%Symbol%":g?Symbol:o,"%SyntaxError%":n,"%ThrowTypeError%":p,"%TypedArray%":w,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?o:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?o:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?o:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?o:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?o:WeakMap,"%WeakRef%":typeof WeakRef>"u"?o:WeakRef,"%WeakSet%":typeof WeakSet>"u"?o:WeakSet};if(b)try{null.error}catch(z){var k=b(b(z));m["%Error.prototype%"]=k}var _=function z(W){var ne;if(W==="%AsyncFunction%")ne=c("async function () {}");else if(W==="%GeneratorFunction%")ne=c("function* () {}");else if(W==="%AsyncGeneratorFunction%")ne=c("async function* () {}");else if(W==="%AsyncGenerator%"){var D=z("%AsyncGeneratorFunction%");D&&(ne=D.prototype)}else if(W==="%AsyncIteratorPrototype%"){var G=z("%AsyncGenerator%");G&&b&&(ne=b(G.prototype))}return m[W]=ne,ne},v={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},E=Po(),S=Dd(),I=E.call(Function.call,Array.prototype.concat),P=E.call(Function.apply,Array.prototype.splice),O=E.call(Function.call,String.prototype.replace),j=E.call(Function.call,String.prototype.slice),T=E.call(Function.call,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,$=/\\(\\)?/g,U=function(z){var W=j(z,0,1),ne=j(z,-1);if(W==="%"&&ne!=="%")throw new n("invalid intrinsic syntax, expected closing `%`");if(ne==="%"&&W!=="%")throw new n("invalid intrinsic syntax, expected opening `%`");var D=[];return O(z,F,function(G,L,Y,pe){D[D.length]=Y?O(pe,$,"$1"):L||G}),D},X=function(z,W){var ne=z,D;if(S(v,ne)&&(D=v[ne],ne="%"+D[0]+"%"),S(m,ne)){var G=m[ne];if(G===y&&(G=_(ne)),typeof G>"u"&&!W)throw new s("intrinsic "+z+" exists, but is not available. Please file an issue!");return{alias:D,name:ne,value:G}}throw new n("intrinsic "+z+" does not exist!")};return Lr=function(z,W){if(typeof z!="string"||z.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(/^%?[^%]*%?$/,z)===null)throw new n("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var ne=U(z),D=ne.length>0?ne[0]:"",G=X("%"+D+"%",W),L=G.name,Y=G.value,pe=!1,te=G.alias;te&&(D=te[0],P(ne,I([0,1],te)));for(var ve=1,J=!0;ve<ne.length;ve+=1){var R=ne[ve],ie=j(R,0,1),V=j(R,-1);if((ie==='"'||ie==="'"||ie==="`"||V==='"'||V==="'"||V==="`")&&ie!==V)throw new n("property names with quotes must have matching quotes");if((R==="constructor"||!J)&&(pe=!0),D+="."+R,L="%"+D+"%",S(m,L))Y=m[L];else if(Y!=null){if(!(R in Y)){if(!W)throw new s("base intrinsic for "+z+" exists, but the property is not available.");return}if(u&&ve+1>=ne.length){var Q=u(Y,R);J=!!Q,J&&"get"in Q&&!("originalValue"in Q.get)?Y=Q.get:Y=Y[R]}else J=S(Y,R),Y=Y[R];J&&!pe&&(m[L]=Y)}}return Y},Lr}function Oo(){if(to)return Mr;to=!0;var o=er(),e=o("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Mr=e,Mr}function kl(){if(ro)return Nr;ro=!0;var o=er(),e=o("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Nr=e,Nr}function $d(){if(no)return Rr;no=!0;var o=Oo(),e=wl(),t=br(),r=kl();return Rr=function(i,n,s){if(!i||typeof i!="object"&&typeof i!="function")throw new t("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new t("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new t("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new t("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new t("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new t("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,l=arguments.length>4?arguments[4]:null,c=arguments.length>5?arguments[5]:null,u=arguments.length>6?arguments[6]:!1,d=!!r&&r(i,n);if(o)o(i,n,{configurable:c===null&&d?d.configurable:!c,enumerable:a===null&&d?d.enumerable:!a,value:s,writable:l===null&&d?d.writable:!l});else if(u||!a&&!l&&!c)i[n]=s;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Rr}function Ud(){if(io)return jr;io=!0;var o=Oo(),e=function(){return!!o};return e.hasArrayLengthDefineBug=function(){if(!o)return null;try{return o([],"length",{value:1}).length!==1}catch{return!0}},jr=e,jr}function Bd(){if(oo)return Dr;oo=!0;var o=er(),e=$d(),t=Ud()(),r=kl(),i=br(),n=o("%Math.floor%");return Dr=function(s,a){if(typeof s!="function")throw new i("`fn` is not a function");if(typeof a!="number"||a<0||a>4294967295||n(a)!==a)throw new i("`length` must be a positive 32-bit integer");var l=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in s&&r){var d=r(s,"length");d&&!d.configurable&&(c=!1),d&&!d.writable&&(u=!1)}return(c||u||!l)&&(t?e(s,"length",a,!0,!0):e(s,"length",a)),s},Dr}function Fd(){if(so)return Vt;so=!0;var o=Po(),e=er(),t=Bd(),r=br(),i=e("%Function.prototype.apply%"),n=e("%Function.prototype.call%"),s=e("%Reflect.apply%",!0)||o.call(n,i),a=Oo(),l=e("%Math.max%");Vt=function(u){if(typeof u!="function")throw new r("a function is required");var d=s(o,n,arguments);return t(d,1+l(0,u.length-(arguments.length-1)),!0)};var c=function(){return s(o,i,arguments)};return a?a(Vt,"apply",{value:c}):Vt.apply=c,Vt}function qd(){if(ao)return $r;ao=!0;var o=er(),e=Fd(),t=e(o("String.prototype.indexOf"));return $r=function(r,i){var n=o(r,!!i);return typeof n=="function"&&t(r,".prototype.")>-1?e(n):n},$r}var Mi,Ni,Ri,ji,Di,$i,Ui,Bi,Fi,qi,Hi,Wi,zi,Vi,Ki,Gi,Ir,Yi,Tr,Ji,Cr,Qi,Pr,Xi,Or,Zi,Lr,eo,Mr,to,Nr,ro,Rr,no,jr,io,Dr,oo,Vt,so,$r,ao,Hd=Qe(()=>{le(),ue(),ce(),Mi={},Ni=!1,Ri={},ji=!1,Di={},$i=!1,Ui={},Bi=!1,Fi={},qi=!1,Hi={},Wi=!1,zi={},Vi=!1,Ki={},Gi=!1,Ir={},Yi=!1,Tr={},Ji=!1,Cr={},Qi=!1,Pr={},Xi=!1,Or={},Zi=!1,Lr={},eo=!1,Mr={},to=!1,Nr={},ro=!1,Rr={},no=!1,jr={},io=!1,Dr={},oo=!1,Vt={},so=!1,$r={},ao=!1});function Lo(o){throw new Error("Node.js process "+o+" is not supported by JSPM core outside of Node.js")}function Wd(){!$t||!jt||($t=!1,jt.length?ht=jt.concat(ht):fr=-1,ht.length&&xl())}function xl(){if(!$t){var o=setTimeout(Wd,0);$t=!0;for(var e=ht.length;e;){for(jt=ht,ht=[];++fr<e;)jt&&jt[fr].run();fr=-1,e=ht.length}jt=null,$t=!1,clearTimeout(o)}}function zd(o){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];ht.push(new _l(o,e)),ht.length===1&&!$t&&setTimeout(xl,0)}function _l(o,e){this.fun=o,this.array=e}function ze(){}function Vd(o){Lo("_linkedBinding")}function Kd(o){Lo("dlopen")}function Gd(){return[]}function Yd(){return[]}function Jd(o,e){if(!o)throw new Error(e||"assertion error")}function Qd(){return!1}function Xd(){return bt.now()/1e3}function un(o){var e=Math.floor((Date.now()-bt.now())*.001),t=bt.now()*.001,r=Math.floor(t)+e,i=Math.floor(t%1*1e9);return o&&(r=r-o[0],i=i-o[1],i<0&&(r--,i+=Ur)),[r,i]}function Et(){return Mo}function Zd(o){return[]}var ht,$t,jt,fr,Ko,Go,Yo,Jo,Qo,Xo,Zo,es,ts,rs,ns,is,os,ss,as,ls,cs,us,ds,hs,fs,wr,ps,ms,gs,bs,ys,vs,ws,ks,xs,_s,Ss,Es,As,Is,Ts,Cs,Ps,Os,Ls,Ms,Ns,Rs,js,Ds,$s,bt,dn,Ur,Us,Bs,Fs,qs,Hs,Ws,zs,Vs,Ks,Gs,Ys,Mo,Sl=Qe(()=>{le(),ue(),ce(),ht=[],$t=!1,fr=-1,_l.prototype.run=function(){this.fun.apply(null,this.array)},Ko="browser",Go="x64",Yo="browser",Jo={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},Qo=["/usr/bin/node"],Xo=[],Zo="v16.8.0",es={},ts=function(o,e){console.warn((e?e+": ":"")+o)},rs=function(o){Lo("binding")},ns=function(o){return 0},is=function(){return"/"},os=function(o){},ss={name:"node",sourceUrl:"",headersUrl:"",libUrl:""},as=ze,ls=[],cs={},us=!1,ds={},hs=ze,fs=ze,wr=function(){return{}},ps=wr,ms=wr,gs=ze,bs=ze,ys=ze,vs={},ws={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},ks=ze,xs=ze,_s=ze,Ss=ze,Es=ze,As=ze,Is=ze,Ts=void 0,Cs=void 0,Ps=void 0,Os=ze,Ls=2,Ms=1,Ns="/bin/usr/node",Rs=9229,js="node",Ds=[],$s=ze,bt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0},bt.now===void 0&&(dn=Date.now(),bt.timing&&bt.timing.navigationStart&&(dn=bt.timing.navigationStart),bt.now=()=>Date.now()-dn),Ur=1e9,un.bigint=function(o){var e=un(o);return typeof BigInt>"u"?e[0]*Ur+e[1]:BigInt(e[0]*Ur)+BigInt(e[1])},Us=10,Bs={},Fs=0,qs=Et,Hs=Et,Ws=Et,zs=Et,Vs=Et,Ks=ze,Gs=Et,Ys=Et,Mo={version:Zo,versions:es,arch:Go,platform:Yo,release:ss,_rawDebug:as,moduleLoadList:ls,binding:rs,_linkedBinding:Vd,_events:Bs,_eventsCount:Fs,_maxListeners:Us,on:Et,addListener:qs,once:Hs,off:Ws,removeListener:zs,removeAllListeners:Vs,emit:Ks,prependListener:Gs,prependOnceListener:Ys,listeners:Zd,domain:cs,_exiting:us,config:ds,dlopen:Kd,uptime:Xd,_getActiveRequests:Gd,_getActiveHandles:Yd,reallyExit:hs,_kill:fs,cpuUsage:wr,resourceUsage:ps,memoryUsage:ms,kill:gs,exit:bs,openStdin:ys,allowedNodeEnvironmentFlags:vs,assert:Jd,features:ws,_fatalExceptions:ks,setUncaughtExceptionCaptureCallback:xs,hasUncaughtExceptionCaptureCallback:Qd,emitWarning:ts,nextTick:zd,_tickCallback:_s,_debugProcess:Ss,_debugEnd:Es,_startProfilerIdleNotifier:As,_stopProfilerIdleNotifier:Is,stdout:Ts,stdin:Ps,stderr:Cs,abort:Os,umask:ns,chdir:os,cwd:is,env:Jo,title:Ko,argv:Qo,execArgv:Xo,pid:Ls,ppid:Ms,execPath:Ns,debugPort:Rs,hrtime:un,argv0:js,_preload_modules:Ds,setSourceMapsEnabled:$s}});function eh(){if(lo)return Br;lo=!0;var o=Mo;function e(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}function t(n,s){for(var a="",l=0,c=-1,u=0,d,p=0;p<=n.length;++p){if(p<n.length)d=n.charCodeAt(p);else{if(d===47)break;d=47}if(d===47){if(!(c===p-1||u===1))if(c!==p-1&&u===2){if(a.length<2||l!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var g=a.lastIndexOf("/");if(g!==a.length-1){g===-1?(a="",l=0):(a=a.slice(0,g),l=a.length-1-a.lastIndexOf("/")),c=p,u=0;continue}}else if(a.length===2||a.length===1){a="",l=0,c=p,u=0;continue}}s&&(a.length>0?a+="/..":a="..",l=2)}else a.length>0?a+="/"+n.slice(c+1,p):a=n.slice(c+1,p),l=p-c-1;c=p,u=0}else d===46&&u!==-1?++u:u=-1}return a}function r(n,s){var a=s.dir||s.root,l=s.base||(s.name||"")+(s.ext||"");return a?a===s.root?a+l:a+n+l:l}var i={resolve:function(){for(var n="",s=!1,a,l=arguments.length-1;l>=-1&&!s;l--){var c;l>=0?c=arguments[l]:(a===void 0&&(a=o.cwd()),c=a),e(c),c.length!==0&&(n=c+"/"+n,s=c.charCodeAt(0)===47)}return n=t(n,!s),s?n.length>0?"/"+n:"/":n.length>0?n:"."},normalize:function(n){if(e(n),n.length===0)return".";var s=n.charCodeAt(0)===47,a=n.charCodeAt(n.length-1)===47;return n=t(n,!s),n.length===0&&!s&&(n="."),n.length>0&&a&&(n+="/"),s?"/"+n:n},isAbsolute:function(n){return e(n),n.length>0&&n.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var n,s=0;s<arguments.length;++s){var a=arguments[s];e(a),a.length>0&&(n===void 0?n=a:n+="/"+a)}return n===void 0?".":i.normalize(n)},relative:function(n,s){if(e(n),e(s),n===s||(n=i.resolve(n),s=i.resolve(s),n===s))return"";for(var a=1;a<n.length&&n.charCodeAt(a)===47;++a);for(var l=n.length,c=l-a,u=1;u<s.length&&s.charCodeAt(u)===47;++u);for(var d=s.length,p=d-u,g=c<p?c:p,h=-1,b=0;b<=g;++b){if(b===g){if(p>g){if(s.charCodeAt(u+b)===47)return s.slice(u+b+1);if(b===0)return s.slice(u+b)}else c>g&&(n.charCodeAt(a+b)===47?h=b:b===0&&(h=0));break}var y=n.charCodeAt(a+b),w=s.charCodeAt(u+b);if(y!==w)break;y===47&&(h=b)}var m="";for(b=a+h+1;b<=l;++b)(b===l||n.charCodeAt(b)===47)&&(m.length===0?m+="..":m+="/..");return m.length>0?m+s.slice(u+h):(u+=h,s.charCodeAt(u)===47&&++u,s.slice(u))},_makeLong:function(n){return n},dirname:function(n){if(e(n),n.length===0)return".";for(var s=n.charCodeAt(0),a=s===47,l=-1,c=!0,u=n.length-1;u>=1;--u)if(s=n.charCodeAt(u),s===47){if(!c){l=u;break}}else c=!1;return l===-1?a?"/":".":a&&l===1?"//":n.slice(0,l)},basename:function(n,s){if(s!==void 0&&typeof s!="string")throw new TypeError('"ext" argument must be a string');e(n);var a=0,l=-1,c=!0,u;if(s!==void 0&&s.length>0&&s.length<=n.length){if(s.length===n.length&&s===n)return"";var d=s.length-1,p=-1;for(u=n.length-1;u>=0;--u){var g=n.charCodeAt(u);if(g===47){if(!c){a=u+1;break}}else p===-1&&(c=!1,p=u+1),d>=0&&(g===s.charCodeAt(d)?--d===-1&&(l=u):(d=-1,l=p))}return a===l?l=p:l===-1&&(l=n.length),n.slice(a,l)}else{for(u=n.length-1;u>=0;--u)if(n.charCodeAt(u)===47){if(!c){a=u+1;break}}else l===-1&&(c=!1,l=u+1);return l===-1?"":n.slice(a,l)}},extname:function(n){e(n);for(var s=-1,a=0,l=-1,c=!0,u=0,d=n.length-1;d>=0;--d){var p=n.charCodeAt(d);if(p===47){if(!c){a=d+1;break}continue}l===-1&&(c=!1,l=d+1),p===46?s===-1?s=d:u!==1&&(u=1):s!==-1&&(u=-1)}return s===-1||l===-1||u===0||u===1&&s===l-1&&s===a+1?"":n.slice(s,l)},format:function(n){if(n===null||typeof n!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof n);return r("/",n)},parse:function(n){e(n);var s={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return s;var a=n.charCodeAt(0),l=a===47,c;l?(s.root="/",c=1):c=0;for(var u=-1,d=0,p=-1,g=!0,h=n.length-1,b=0;h>=c;--h){if(a=n.charCodeAt(h),a===47){if(!g){d=h+1;break}continue}p===-1&&(g=!1,p=h+1),a===46?u===-1?u=h:b!==1&&(b=1):u!==-1&&(b=-1)}return u===-1||p===-1||b===0||b===1&&u===p-1&&u===d+1?p!==-1&&(d===0&&l?s.base=s.name=n.slice(1,p):s.base=s.name=n.slice(d,p)):(d===0&&l?(s.name=n.slice(1,u),s.base=n.slice(1,p)):(s.name=n.slice(d,u),s.base=n.slice(d,p)),s.ext=n.slice(u,p)),d>0?s.dir=n.slice(0,d-1):l&&(s.dir="/"),s},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,Br=i,Br}var Br,lo,co,th=Qe(()=>{le(),ue(),ce(),Sl(),Br={},lo=!1,co=eh()}),El={};Qt(El,{URL:()=>Rl,Url:()=>Pl,default:()=>Ke,fileURLToPath:()=>Il,format:()=>Ol,parse:()=>Nl,pathToFileURL:()=>Tl,resolve:()=>Ll,resolveObject:()=>Ml});function rh(){if(uo)return Fr;uo=!0;var o=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&o?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,t=o&&e&&typeof e.get=="function"?e.get:null,r=o&&Map.prototype.forEach,i=typeof Set=="function"&&Set.prototype,n=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,s=i&&n&&typeof n.get=="function"?n.get:null,a=i&&Set.prototype.forEach,l=typeof WeakMap=="function"&&WeakMap.prototype,c=l?WeakMap.prototype.has:null,u=typeof WeakSet=="function"&&WeakSet.prototype,d=u?WeakSet.prototype.has:null,p=typeof WeakRef=="function"&&WeakRef.prototype,g=p?WeakRef.prototype.deref:null,h=Boolean.prototype.valueOf,b=Object.prototype.toString,y=Function.prototype.toString,w=String.prototype.match,m=String.prototype.slice,k=String.prototype.replace,_=String.prototype.toUpperCase,v=String.prototype.toLowerCase,E=RegExp.prototype.test,S=Array.prototype.concat,I=Array.prototype.join,P=Array.prototype.slice,O=Math.floor,j=typeof BigInt=="function"?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,F=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,$=typeof Symbol=="function"&&typeof Symbol.iterator=="object",U=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===$||!0)?Symbol.toStringTag:null,X=Object.prototype.propertyIsEnumerable,z=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(K){return K.__proto__}:null);function W(K,oe){if(K===1/0||K===-1/0||K!==K||K&&K>-1e3&&K<1e3||E.call(/e/,oe))return oe;var Ie=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof K=="number"){var Te=K<0?-O(-K):O(K);if(Te!==K){var Oe=String(Te),Ne=m.call(oe,Oe.length+1);return k.call(Oe,Ie,"$&_")+"."+k.call(k.call(Ne,/([0-9]{3})/g,"$&_"),/_$/,"")}}return k.call(oe,Ie,"$&_")}var ne=Cl,D=ne.custom,G=Q(D)?D:null;Fr=function K(oe,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 it=se(Ne,"customInspect")?Ne.customInspect:!0;if(typeof it!="boolean"&&it!=="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 ot=Ne.numericSeparator;if(typeof oe>"u")return"undefined";if(oe===null)return"null";if(typeof oe=="boolean")return oe?"true":"false";if(typeof oe=="string")return ae(oe,Ne);if(typeof oe=="number"){if(oe===0)return 1/0/oe>0?"0":"-0";var He=String(oe);return ot?W(oe,He):He}if(typeof oe=="bigint"){var st=String(oe)+"n";return ot?W(oe,st):st}var qt=typeof Ne.depth>"u"?5:Ne.depth;if(typeof Te>"u"&&(Te=0),Te>=qt&&qt>0&&typeof oe=="object")return pe(oe)?"[Array]":"[Object]";var at=ee(Ne,Te);if(typeof Oe>"u")Oe=[];else if(re(Oe,oe)>=0)return"[Circular]";function Xe(lt,St,Mt){if(St&&(Oe=P.call(Oe),Oe.push(St)),Mt){var ct={depth:Ne.depth};return se(Ne,"quoteStyle")&&(ct.quoteStyle=Ne.quoteStyle),K(lt,ct,Te+1,Oe)}return K(lt,Ne,Te+1,Oe)}if(typeof oe=="function"&&!ve(oe)){var yr=q(oe),Ht=xe(oe,Xe);return"[Function"+(yr?": "+yr:" (anonymous)")+"]"+(Ht.length>0?" { "+I.call(Ht,", ")+" }":"")}if(Q(oe)){var tr=$?k.call(String(oe),/^(Symbol\(.*\))_[^)]*$/,"$1"):F.call(oe);return typeof oe=="object"&&!$?f(tr):tr}if(we(oe)){for(var C="<"+v.call(String(oe.nodeName)),N=oe.attributes||[],ke=0;ke<N.length;ke++)C+=" "+N[ke].name+"="+L(Y(N[ke].value),"double",Ne);return C+=">",oe.childNodes&&oe.childNodes.length&&(C+="..."),C+="</"+v.call(String(oe.nodeName))+">",C}if(pe(oe)){if(oe.length===0)return"[]";var Se=xe(oe,Xe);return at&&!B(Se)?"["+de(Se,at)+"]":"[ "+I.call(Se,", ")+" ]"}if(J(oe)){var Ae=xe(oe,Xe);return!("cause"in Error.prototype)&&"cause"in oe&&!X.call(oe,"cause")?"{ ["+String(oe)+"] "+I.call(S.call("[cause]: "+Xe(oe.cause),Ae),", ")+" }":Ae.length===0?"["+String(oe)+"]":"{ ["+String(oe)+"] "+I.call(Ae,", ")+" }"}if(typeof oe=="object"&&it){if(G&&typeof oe[G]=="function"&&ne)return ne(oe,{depth:qt-Te});if(it!=="symbol"&&typeof oe.inspect=="function")return oe.inspect()}if(he(oe)){var Be=[];return r&&r.call(oe,function(lt,St){Be.push(Xe(St,oe,!0)+" => "+Xe(lt,oe))}),A("Map",t.call(oe),Be,at)}if(H(oe)){var Ge=[];return a&&a.call(oe,function(lt){Ge.push(Xe(lt,oe))}),A("Set",s.call(oe),Ge,at)}if(fe(oe))return x("WeakMap");if(ge(oe))return x("WeakSet");if(ye(oe))return x("WeakRef");if(ie(oe))return f(Xe(Number(oe)));if(Z(oe))return f(Xe(j.call(oe)));if(V(oe))return f(h.call(oe));if(R(oe))return f(Xe(String(oe)));if(typeof window<"u"&&oe===window)return"{ [object Window] }";if(typeof globalThis<"u"&&oe===globalThis||typeof qr<"u"&&oe===qr)return"{ [object globalThis] }";if(!te(oe)&&!ve(oe)){var et=xe(oe,Xe),rr=z?z(oe)===Object.prototype:oe instanceof Object||oe.constructor===Object,nr=oe instanceof Object?"":"null prototype",ir=!rr&&U&&Object(oe)===oe&&U in oe?m.call(M(oe),8,-1):nr?"Object":"",vr=rr||typeof oe.constructor!="function"?"":oe.constructor.name?oe.constructor.name+" ":"",Lt=vr+(ir||nr?"["+I.call(S.call([],ir||[],nr||[]),": ")+"] ":"");return et.length===0?Lt+"{}":at?Lt+"{"+de(et,at)+"}":Lt+"{ "+I.call(et,", ")+" }"}return String(oe)};function L(K,oe,Ie){var Te=(Ie.quoteStyle||oe)==="double"?'"':"'";return Te+K+Te}function Y(K){return k.call(String(K),/"/g,""")}function pe(K){return M(K)==="[object Array]"&&(!U||!(typeof K=="object"&&U in K))}function te(K){return M(K)==="[object Date]"&&(!U||!(typeof K=="object"&&U in K))}function ve(K){return M(K)==="[object RegExp]"&&(!U||!(typeof K=="object"&&U in K))}function J(K){return M(K)==="[object Error]"&&(!U||!(typeof K=="object"&&U in K))}function R(K){return M(K)==="[object String]"&&(!U||!(typeof K=="object"&&U in K))}function ie(K){return M(K)==="[object Number]"&&(!U||!(typeof K=="object"&&U in K))}function V(K){return M(K)==="[object Boolean]"&&(!U||!(typeof K=="object"&&U in K))}function Q(K){if($)return K&&typeof K=="object"&&K instanceof Symbol;if(typeof K=="symbol")return!0;if(!K||typeof K!="object"||!F)return!1;try{return F.call(K),!0}catch{}return!1}function Z(K){if(!K||typeof K!="object"||!j)return!1;try{return j.call(K),!0}catch{}return!1}var be=Object.prototype.hasOwnProperty||function(K){return K in(this||qr)};function se(K,oe){return be.call(K,oe)}function M(K){return b.call(K)}function q(K){if(K.name)return K.name;var oe=w.call(y.call(K),/^function\s*([\w$]+)/);return oe?oe[1]:null}function re(K,oe){if(K.indexOf)return K.indexOf(oe);for(var Ie=0,Te=K.length;Ie<Te;Ie++)if(K[Ie]===oe)return Ie;return-1}function he(K){if(!t||!K||typeof K!="object")return!1;try{t.call(K);try{s.call(K)}catch{return!0}return K instanceof Map}catch{}return!1}function fe(K){if(!c||!K||typeof K!="object")return!1;try{c.call(K,c);try{d.call(K,d)}catch{return!0}return K instanceof WeakMap}catch{}return!1}function ye(K){if(!g||!K||typeof K!="object")return!1;try{return g.call(K),!0}catch{}return!1}function H(K){if(!s||!K||typeof K!="object")return!1;try{s.call(K);try{t.call(K)}catch{return!0}return K instanceof Set}catch{}return!1}function ge(K){if(!d||!K||typeof K!="object")return!1;try{d.call(K,d);try{c.call(K,c)}catch{return!0}return K instanceof WeakSet}catch{}return!1}function we(K){return!K||typeof K!="object"?!1:typeof HTMLElement<"u"&&K instanceof HTMLElement?!0:typeof K.nodeName=="string"&&typeof K.getAttribute=="function"}function ae(K,oe){if(K.length>oe.maxStringLength){var Ie=K.length-oe.maxStringLength,Te="... "+Ie+" more character"+(Ie>1?"s":"");return ae(m.call(K,0,oe.maxStringLength),oe)+Te}var Oe=k.call(k.call(K,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Le);return L(Oe,"single",oe)}function Le(K){var oe=K.charCodeAt(0),Ie={8:"b",9:"t",10:"n",12:"f",13:"r"}[oe];return Ie?"\\"+Ie:"\\x"+(oe<16?"0":"")+_.call(oe.toString(16))}function f(K){return"Object("+K+")"}function x(K){return K+" { ? }"}function A(K,oe,Ie,Te){var Oe=Te?de(Ie,Te):I.call(Ie,", ");return K+" ("+oe+") {"+Oe+"}"}function B(K){for(var oe=0;oe<K.length;oe++)if(re(K[oe],`
|
|
4
|
-
`)>=0)return!1;return!0}function ee(K,oe){var Ie;if(K.indent===" ")Ie=" ";else if(typeof K.indent=="number"&&K.indent>0)Ie=I.call(Array(K.indent+1)," ");else return null;return{base:Ie,prev:I.call(Array(oe+1),Ie)}}function de(K,oe){if(K.length===0)return"";var Ie=`
|
|
5
|
-
`+oe.prev+oe.base;return Ie+I.call(K,","+Ie)+`
|
|
6
|
-
`+oe.prev}function xe(K,oe){var Ie=pe(K),Te=[];if(Ie){Te.length=K.length;for(var Oe=0;Oe<K.length;Oe++)Te[Oe]=se(K,Oe)?oe(K[Oe],K):""}var Ne=typeof T=="function"?T(K):[],it;if($){it={};for(var ot=0;ot<Ne.length;ot++)it["$"+Ne[ot]]=Ne[ot]}for(var He in K)se(K,He)&&(Ie&&String(Number(He))===He&&He<K.length||$&&it["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Te.push(oe(He,K)+": "+oe(K[He],K)):Te.push(He+": "+oe(K[He],K))));if(typeof T=="function")for(var st=0;st<Ne.length;st++)X.call(K,Ne[st])&&Te.push("["+oe(Ne[st])+"]: "+oe(K[Ne[st]],K));return Te}return Fr}function nh(){if(ho)return Hr;ho=!0;var o=er(),e=qd(),t=rh(),r=br(),i=o("%WeakMap%",!0),n=o("%Map%",!0),s=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),c=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,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=p(y,w);return m&&m.value},h=function(y,w,m){var k=p(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return Hr=function(){var y,w,m,k={assert:function(_){if(!k.has(_))throw new r("Side channel does not contain "+t(_))},get:function(_){if(i&&_&&(typeof _=="object"||typeof _=="function")){if(y)return s(y,_)}else if(n){if(w)return c(w,_)}else if(m)return g(m,_)},has:function(_){if(i&&_&&(typeof _=="object"||typeof _=="function")){if(y)return l(y,_)}else if(n){if(w)return d(w,_)}else if(m)return b(m,_);return!1},set:function(_,v){i&&_&&(typeof _=="object"||typeof _=="function")?(y||(y=new i),a(y,_,v)):n?(w||(w=new n),u(w,_,v)):(m||(m={key:{},next:null}),h(m,_,v))}};return k},Hr}function No(){if(fo)return Wr;fo=!0;var o=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Wr={default:t.RFC3986,formatters:{RFC1738:function(r){return o.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Wr}function Al(){if(po)return zr;po=!0;var o=No(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),i=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],_=0;_<m.length;++_)typeof m[_]<"u"&&k.push(m[_]);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 _=w;return t(w)&&!t(m)&&(_=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,k):w.push(v)}else w[E]=v}),w):Object.keys(m).reduce(function(v,E){var S=m[E];return e.call(v,E)?v[E]=y(v[E],S,k):v[E]=S,v},_)},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,_){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,P=[],O=0;O<I.length;++O){var j=I.charCodeAt(O);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||_===o.RFC1738&&(j===40||j===41)){P[P.length]=I.charAt(O);continue}if(j<128){P[P.length]=r[j];continue}if(j<2048){P[P.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){P[P.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}O+=1,j=65536+((j&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=P.join("")}return E},d=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],k=0;k<w.length;++k)for(var _=w[k],v=_.obj[_.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return i(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},h=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 zr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:s},zr}function ih(){if(mo)return Vr;mo=!0;var o=nh(),e=Al(),t=No(),r=Object.prototype.hasOwnProperty,i={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,s=Array.prototype.push,a=function(b,y){s.apply(b,n(y)?y:[y])},l=Date.prototype.toISOString,c=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:c,formatter:t.formatters[c],indices:!1,serializeDate:function(b){return l.call(b)},skipNulls:!1,strictNullHandling:!1},d=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,k,_,v,E,S,I,P,O,j,T,F,$,U,X,z){for(var W=y,ne=z,D=0,G=!1;(ne=ne.get(p))!==void 0&&!G;){var L=ne.get(y);if(D+=1,typeof L<"u"){if(L===D)throw new RangeError("Cyclic object value");G=!0}typeof ne.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(M){return M instanceof Date?T(M):M})),W===null){if(v)return I&&!U?I(w,u.encoder,X,"key",F):w;W=""}if(d(W)||e.isBuffer(W)){if(I){var Y=U?w:I(w,u.encoder,X,"key",F);return[$(Y)+"="+$(I(W,u.encoder,X,"value",F))]}return[$(w)+"="+$(String(W))]}var pe=[];if(typeof W>"u")return pe;var te;if(m==="comma"&&n(W))U&&I&&(W=e.maybeMap(W,I)),te=[{value:W.length>0?W.join(",")||null:void 0}];else if(n(P))te=P;else{var ve=Object.keys(W);te=O?ve.sort(O):ve}var J=S?w.replace(/\./g,"%2E"):w,R=k&&n(W)&&W.length===1?J+"[]":J;if(_&&n(W)&&W.length===0)return R+"[]";for(var ie=0;ie<te.length;++ie){var V=te[ie],Q=typeof V=="object"&&typeof V.value<"u"?V.value:W[V];if(!(E&&Q===null)){var Z=j&&S?V.replace(/\./g,"%2E"):V,be=n(W)?typeof m=="function"?m(R,Z):R:R+(j?"."+Z:"["+Z+"]");z.set(y,D);var se=o();se.set(p,z),a(pe,b(Q,be,m,k,_,v,E,S,m==="comma"&&U&&n(W)?null:I,P,O,j,T,F,$,U,X,se))}}return pe},h=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 _;if(b.arrayFormat in i?_=b.arrayFormat:"indices"in b?_=b.indices?"indices":"repeat":_=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:_,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 Vr=function(b,y){var w=b,m=h(y),k,_;typeof m.filter=="function"?(_=m.filter,w=_("",w)):n(m.filter)&&(_=m.filter,k=_);var v=[];if(typeof w!="object"||w===null)return"";var E=i[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=o(),P=0;P<k.length;++P){var O=k[P];m.skipNulls&&w[O]===null||a(v,g(w[O],O,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var j=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),j.length>0?T+j:""},Vr}function oh(){if(go)return Kr;go=!0;var o=Al(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:o.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},i=function(p){return p.replace(/&#(\d+);/g,function(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},s="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,g){var h={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,_=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?_="utf-8":w[k]===s&&(_="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,P;S===-1?(I=g.decoder(v,r.decoder,_,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,_,"key"),P=o.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,_,"value")})),P&&g.interpretNumericEntities&&_==="iso-8859-1"&&(P=i(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(h,I);O&&g.duplicates==="combine"?h[I]=o.combine(h[I],P):(!O||g.duplicates==="last")&&(h[I]=P)}return h},c=function(p,g,h,b){for(var y=b?g:n(g,h),w=p.length-1;w>=0;--w){var m,k=p[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var _=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?_.replace(/%2E/g,"."):_,E=parseInt(v,10);!h.parseArrays&&v===""?m={0:y}:!isNaN(E)&&k!==v&&String(E)===v&&E>=0&&h.parseArrays&&E<=h.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,h,b){if(p){var y=h.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),_=k?y.slice(0,k.index):y,v=[];if(_){if(!h.plainObjects&&e.call(Object.prototype,_)&&!h.allowPrototypes)return;v.push(_)}for(var E=0;h.depth>0&&(k=m.exec(y))!==null&&E<h.depth;){if(E+=1,!h.plainObjects&&e.call(Object.prototype,k[1].slice(1,-1))&&!h.allowPrototypes)return;v.push(k[1])}if(k){if(h.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+h.depth+" and strictDepth is true");v.push("["+y.slice(k.index)+"]")}return c(v,g,h,b)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof p.charset>"u"?r.charset:p.charset,h=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||o.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:h,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 Kr=function(p,g){var h=d(g);if(p===""||p===null||typeof p>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,h):p,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],_=u(k,b[k],h,typeof p=="string");y=o.merge(y,_,h)}return h.allowSparse===!0?y:o.compact(y)},Kr}function sh(){if(bo)return Gr;bo=!0;var o=ih(),e=oh(),t=No();return Gr={formats:t,parse:e,stringify:o},Gr}function ah(){if(yo)return Ct;yo=!0;var o=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]*$/,i=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
|
-
`," "],s=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(s),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},h={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=sh();function w(v,E,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,E,S),I}e.prototype.parse=function(v,E,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),P=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(P),j=/\\/g;O[0]=O[0].replace(j,"/"),v=O.join(P);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var F=i.exec(T);if(F)return this.path=T,this.href=T,this.pathname=F[1],F[2]?(this.search=F[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var $=t.exec(T);if($){$=$[0];var U=$.toLowerCase();this.protocol=U,T=T.substr($.length)}if(S||$||T.match(/^\/\/[^@/]+@[^@/]+/)){var X=T.substr(0,2)==="//";X&&!($&&h[$])&&(T=T.substr(2),this.slashes=!0)}if(!h[$]&&(X||$&&!b[$])){for(var z=-1,W=0;W<c.length;W++){var ne=T.indexOf(c[W]);ne!==-1&&(z===-1||ne<z)&&(z=ne)}var D,G;z===-1?G=T.lastIndexOf("@"):G=T.lastIndexOf("@",z),G!==-1&&(D=T.slice(0,G),T=T.slice(G+1),this.auth=decodeURIComponent(D)),z=-1;for(var W=0;W<l.length;W++){var ne=T.indexOf(l[W]);ne!==-1&&(z===-1||ne<z)&&(z=ne)}z===-1&&(z=T.length),this.host=T.slice(0,z),T=T.slice(z),this.parseHost(),this.hostname=this.hostname||"";var L=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!L)for(var Y=this.hostname.split(/\./),W=0,pe=Y.length;W<pe;W++){var te=Y[W];if(te&&!te.match(d)){for(var ve="",J=0,R=te.length;J<R;J++)te.charCodeAt(J)>127?ve+="x":ve+=te[J];if(!ve.match(d)){var ie=Y.slice(0,W),V=Y.slice(W+1),Q=te.match(p);Q&&(ie.push(Q[1]),V.unshift(Q[2])),V.length&&(T="/"+V.join(".")+T),this.hostname=ie.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),L||(this.hostname=o.toASCII(this.hostname));var Z=this.port?":"+this.port:"",be=this.hostname||"";this.host=be+Z,this.href+=this.host,L&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var W=0,pe=a.length;W<pe;W++){var se=a[W];if(T.indexOf(se)!==-1){var M=encodeURIComponent(se);M===se&&(M=escape(se)),T=T.split(se).join(M)}}var q=T.indexOf("#");q!==-1&&(this.hash=T.substr(q),T=T.slice(0,q));var re=T.indexOf("?");if(re!==-1?(this.search=T.substr(re),this.query=T.substr(re+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,re)):E&&(this.search="",this.query={}),T&&(this.pathname=T),b[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Z=this.pathname||"",he=this.search||"";this.path=Z+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",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 j=this.search||O&&"?"+O||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||b[E])&&P!==!1?(P="//"+(P||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):P||(P=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+P+S+j+I};function k(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function _(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),P=0;P<I.length;P++){var O=I[P];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var F=j[T];F!=="protocol"&&(S[F]=v[F])}return b[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!b[v.protocol]){for(var $=Object.keys(v),U=0;U<$.length;U++){var X=$[U];S[X]=v[X]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!h[v.protocol]){for(var pe=(v.pathname||"").split("/");pe.length&&!(v.host=pe.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),pe[0]!==""&&pe.unshift(""),pe.length<2&&pe.unshift(""),S.pathname=pe.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var z=S.pathname||"",W=S.search||"";S.path=z+W}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var ne=S.pathname&&S.pathname.charAt(0)==="/",D=v.host||v.pathname&&v.pathname.charAt(0)==="/",G=D||ne||S.host&&v.pathname,L=G,Y=S.pathname&&S.pathname.split("/")||[],pe=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!b[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Y[0]===""?Y[0]=S.host:Y.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(pe[0]===""?pe[0]=v.host:pe.unshift(v.host)),v.host=null),G=G&&(pe[0]===""||Y[0]==="")),D)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Y=pe;else if(pe.length)Y||(Y=[]),Y.pop(),Y=Y.concat(pe),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Y.shift(),S.hostname=S.host;var ve=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;ve&&(S.auth=ve.shift(),S.hostname=ve.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Y.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var J=Y.slice(-1)[0],R=(S.host||v.host||Y.length>1)&&(J==="."||J==="..")||J==="",ie=0,V=Y.length;V>=0;V--)J=Y[V],J==="."?Y.splice(V,1):J===".."?(Y.splice(V,1),ie++):ie&&(Y.splice(V,1),ie--);if(!G&&!L)for(;ie--;ie)Y.unshift("..");G&&Y[0]!==""&&(!Y[0]||Y[0].charAt(0)!=="/")&&Y.unshift(""),R&&Y.join("/").substr(-1)!=="/"&&Y.push("");var Q=Y[0]===""||Y[0]&&Y[0].charAt(0)==="/";if(te){S.hostname=Q?"":Y.length?Y.shift():"",S.host=S.hostname;var ve=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;ve&&(S.auth=ve.shift(),S.hostname=ve.shift(),S.host=S.hostname)}return G=G||S.host&&Y.length,G&&!Q&&Y.unshift(""),Y.length>0?S.pathname=Y.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},Ct.parse=w,Ct.resolve=k,Ct.resolveObject=_,Ct.format=m,Ct.Url=e,Ct}function Il(o){if(typeof o=="string")o=new URL(o);else if(!(o instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(o.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Qr?lh(o):ch(o)}function lh(o){let e=o.hostname,t=o.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let i=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&i===102||t[r+1]==="5"&&i===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,i=t[2];if(r<$l||r>Ul||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function ch(o){if(o.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=o.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 Tl(o){let e=co.resolve(o),t=o.charCodeAt(o.length-1);(t===Dl||Qr&&t===jl)&&e[e.length-1]!==co.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Fl,"%25")),!Qr&&e.includes("\\")&&(e=e.replace(ql,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(Hl,"%0A")),e.includes("\r")&&(e=e.replace(Wl,"%0D")),e.includes(" ")&&(e=e.replace(zl,"%09")),r.pathname=e,r}var Cl,Fr,uo,qr,Hr,ho,Wr,fo,zr,po,Vr,mo,Kr,go,Gr,bo,Ct,yo,Ke,Js,Pl,Ol,Ll,Ml,Nl,Rl,jl,Dl,$l,Ul,Qr,Bl,Fl,ql,Hl,Wl,zl,uh=Qe(()=>{le(),ue(),ce(),Id(),Hd(),th(),Sl(),Cl=Object.freeze(Object.create(null)),Fr={},uo=!1,qr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Hr={},ho=!1,Wr={},fo=!1,zr={},po=!1,Vr={},mo=!1,Kr={},go=!1,Gr={},bo=!1,Ct={},yo=!1,Ke=ah(),Ke.parse,Ke.resolve,Ke.resolveObject,Ke.format,Ke.Url,Js=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Ke.URL=typeof URL<"u"?URL:null,Ke.pathToFileURL=Tl,Ke.fileURLToPath=Il,Pl=Ke.Url,Ol=Ke.format,Ll=Ke.resolve,Ml=Ke.resolveObject,Nl=Ke.parse,Rl=Ke.URL,jl=92,Dl=47,$l=97,Ul=122,Qr=Js==="win32",Bl=/\//g,Fl=/%/g,ql=/\\/g,Hl=/\n/g,Wl=/\r/g,zl=/\t/g}),dh=me((o,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Ro=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0}),o.BufferedDuplex=void 0,o.writev=r;var e=Ft(),t=(qe(),Re(Fe));function r(n,s){let a=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?a[l]=t.Buffer.from(n[l].chunk,"utf8"):a[l]=n[l].chunk;this._write(t.Buffer.concat(a),"binary",s)}var i=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,s,a){super({objectMode:!0}),this.proxy=s,this.socket=a,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",l=>{!this.destroyed&&this.readable&&this.push(l)})}_read(n){this.proxy.read(n)}_write(n,s,a){this.isSocketOpen?this.writeToProxy(n,s,a):this.writeQueue.push({chunk:n,encoding:s,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,s){this.writeQueue=[],this.proxy.destroy(),s(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,s,a){this.proxy.write(n,s)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:s,cb:a}=this.writeQueue.shift();this.writeToProxy(n,s,a)}}};o.BufferedDuplex=i}),kr=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(o,"__esModule",{value:!0}),o.streamBuilder=o.browserStreamBuilder=void 0;var t=(qe(),Re(Fe)),r=e(dh()),i=e(vt()),n=Ft(),s=e(sn()),a=Ro(),l=(0,i.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 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 _=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${_}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[_],k):v=new r.default(m,[_],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",_=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(_,[k],m):v=new WebSocket(_,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let _=u(k,w),v=g(w,_,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=_,v.on("close",()=>{E.destroy()}),E};o.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,_=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,X);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(k=I,k.socket=S):(k=new a.BufferedDuplex(m,I,S),P?S.addEventListener("open",j):S.onopen=j),P?(S.addEventListener("close",T),S.addEventListener("error",F),S.addEventListener("message",$)):(S.onclose=T,S.onerror=F,S.onmessage=$);function O(z,W,ne){let D=new n.Transform({objectMode:z.objectMode});return D._write=W,D._flush=ne,D}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(z){l("WebSocket onClose",z),k.end(),k.destroy()}function F(z){l("WebSocket onError",z);let W=new Error("WebSocket error");W.event=z,k.destroy(W)}async function $(z){if(!I||!I.readable||!I.writable)return;let{data:W}=z;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(z,W,ne){if(S.bufferedAmount>_){setTimeout(U,v,z,W,ne);return}E&&typeof z=="string"&&(z=t.Buffer.from(z,"utf8"));try{S.send(z)}catch(D){return ne(D)}ne()}function X(z){S.close(),z()}return k};o.browserStreamBuilder=y}),jo={};Qt(jo,{Server:()=>$e,Socket:()=>$e,Stream:()=>$e,_createServerHandle:()=>$e,_normalizeArgs:()=>$e,_setSimultaneousAccepts:()=>$e,connect:()=>$e,createConnection:()=>$e,createServer:()=>$e,default:()=>Vl,isIP:()=>$e,isIPv4:()=>$e,isIPv6:()=>$e});function $e(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Vl,Kl=Qe(()=>{le(),ue(),ce(),Vl={_createServerHandle:$e,_normalizeArgs:$e,_setSimultaneousAccepts:$e,connect:$e,createConnection:$e,createServer:$e,isIP:$e,isIPv4:$e,isIPv6:$e,Server:$e,Socket:$e,Stream:$e}}),Gl=me((o,e)=>{le(),ue(),ce(),e.exports={}}),Qs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0});var t=e((Kl(),Re(jo))),r=e(vt()),i=e(Gl()),n=(0,r.default)("mqttjs:tcp"),s=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,i.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};o.default=s}),Yl={};Qt(Yl,{default:()=>Jl});var Jl,hh=Qe(()=>{le(),ue(),ce(),Jl={}}),Xs=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(o,"__esModule",{value:!0});var t=(hh(),Re(Yl)),r=e((Kl(),Re(jo))),i=e(vt()),n=e(Gl()),s=(0,i.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:p,...g}=c;if(p!==void 0){let h=(0,n.default)(u,d,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:h})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,s("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=a(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",p),d};o.default=l}),Zs=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s;function a(){let p=new t.Transform;return p._write=(g,h,b)=>{i.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{i.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let h=p.protocol==="wxs"?"wss":"ws",b=`${h}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${h}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){i.onOpen(()=>{s.socketReady()}),i.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),i.onClose(()=>{s.emit("close"),s.end(),s.destroy()}),i.onError(p=>{let g=new Error(p.errMsg);s.destroy(g)})}var d=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let h=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);i=wx.connectSocket({url:b,protocols:[h]}),n=a(),s=new r.BufferedDuplex(g,n,i),s._destroy=(w,m)=>{i.close({success(){m&&m(w)}})};let y=s.destroy;return s.destroy=(w,m)=>(s.destroy=y,setTimeout(()=>{i.close({fail(){s._destroy(w,m)}})},0),s),u(),s};o.default=d}),ea=me(o=>{le(),ue(),ce(),Object.defineProperty(o,"__esModule",{value:!0});var e=(qe(),Re(Fe)),t=Ft(),r=Ro(),i,n,s,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{i.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{i.closeSocket({success(){h()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,h){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,h)),y}function d(){a||(a=!0,i.onSocketOpen(()=>{s.socketReady()}),i.onSocketMessage(g=>{if(typeof g.data=="string"){let h=e.Buffer.from(g.data,"base64");n.push(h)}else{let h=new FileReader;h.addEventListener("load",()=>{if(h.result instanceof ArrayBuffer){n.push(e.Buffer.from(h.result));return}n.push(e.Buffer.from(h.result,"utf-8"))}),h.readAsArrayBuffer(g.data)}}),i.onSocketClose(()=>{s.end(),s.destroy()}),i.onSocketError(g=>{s.destroy(g)}))}var p=(g,h)=>{if(h.hostname=h.hostname||h.host,!h.hostname)throw new Error("Could not determine host. Specify host manually.");let b=h.protocolId==="MQIsdp"&&h.protocolVersion===3?"mqttv3.1":"mqtt";c(h);let y=u(h,g);return i=h.my,i.connectSocket({url:y,protocols:b}),n=l(),s=new r.BufferedDuplex(h,n,i),d(),s};o.default=p}),fh=me(o=>{le(),ue(),ce();var e=o&&o.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(o,"__esModule",{value:!0}),o.connectAsync=u;var t=e(vt()),r=e((uh(),Re(El))),i=e(Pi()),n=e(sn());typeof je?.nextTick!="function"&&(je.nextTick=setImmediate);var s=(0,t.default)("mqttjs"),a=null;function l(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,g,h]=p;d.username=g,d.password=h}else d.username=d.auth}function c(d,p){if(s("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let b=r.default.parse(d,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof 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=kr().streamBuilder,a.wss=kr().streamBuilder,a.mqtt=Qs().default,a.tcp=Qs().default,a.ssl=Xs().default,a.tls=a.ssl,a.mqtts=Xs().default):(a.ws=kr().browserStreamBuilder,a.wss=kr().browserStreamBuilder,a.wx=Zs().default,a.wxs=Zs().default,a.ali=ea().default,a.alis=ea().default)),!a[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),s("calling streambuilder for",p.protocol),a[p.protocol](b,p)}let h=new i.default(g,p);return h.on("error",()=>{}),h}function u(d,p,g=!0){return new Promise((h,b)=>{let y=c(d,p),w={connect:k=>{m(),h(y)},end:()=>{m(),h(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])})})}o.default=c}),ta=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(g,h,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(h,b);(!w||("get"in w?!h.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return h[b]}}),Object.defineProperty(g,y,w)}:function(g,h,b,y){y===void 0&&(y=b),g[y]=h[b]}),t=o&&o.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=o&&o.__importStar||(function(){var g=function(h){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(h)};return function(h){if(h&&h.__esModule)return h;var b={};if(h!=null)for(var y=g(h),w=0;w<y.length;w++)y[w]!=="default"&&e(b,h,y[w]);return t(b,h),b}})(),i=o&&o.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=o&&o.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(o,"__esModule",{value:!0}),o.ReasonCodes=o.KeepaliveManager=o.UniqueMessageIdProvider=o.DefaultMessageIdProvider=o.Store=o.MqttClient=o.connectAsync=o.connect=o.Client=void 0;var s=n(Pi());o.MqttClient=s.default;var a=n(hl());o.DefaultMessageIdProvider=a.default;var l=n(Ed());o.UniqueMessageIdProvider=l.default;var c=n(Ya());o.Store=c.default;var u=r(fh());o.connect=u.default,Object.defineProperty(o,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(vl());o.KeepaliveManager=d.default,o.Client=s.default,i(Pi(),o),i(Zt(),o),i(Ga(),o);var p=nn();Object.defineProperty(o,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ph=me(o=>{le(),ue(),ce();var e=o&&o.__createBinding||(Object.create?function(s,a,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(a,l);(!u||("get"in u?!a.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(s,c,u)}:function(s,a,l,c){c===void 0&&(c=l),s[c]=a[l]}),t=o&&o.__setModuleDefault||(Object.create?function(s,a){Object.defineProperty(s,"default",{enumerable:!0,value:a})}:function(s,a){s.default=a}),r=o&&o.__importStar||(function(){var s=function(a){return s=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},s(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=s(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),i=o&&o.__exportStar||function(s,a){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,s,l)};Object.defineProperty(o,"__esModule",{value:!0});var n=r(ta());o.default=n,i(ta(),o)});const mh=ph();const gh={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}/#"},bh=300,yh={templateId:"7",type:"link",isDeepLink:!0},vh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ql{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={...gh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,i={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(i.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,s)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:p?.message}),l(()=>s(p??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=mh.connect(this.config.mqttEndpoint,i),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,p)=>{this.dispatchInbound(d,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[i,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[i]=`${n.slice(0,200)}…(${n.length})`:r[i]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const i=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,i)}publishFileMessage(e,t){if(!this.client)return;const r={...yh,...this.config.fileTemplate??{},...wh(t)},i={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},s=this.buildOutgoingEnvelope(e,{text:JSON.stringify(i),type:"html",attributes:n,metadata:i.metadata});this.publishEnvelope(e,s)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=bh){if(!this.client)return;const i=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(i,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const i=[...this.subscribedTopics];this.subscribedTopics.clear(),i.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let i=null;try{i=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!i)return;this.debugLog("RECV",{topic:e,sender:i.sender,type:i.type,contentType:i.metadata?.contentType,templateId:i.metadata?.templateId,messageId:i.message_id,text:typeof i.text=="string"?i.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof i.status=="number"?i.status:Number(i.status??0),p={conversationId:c,messageId:u,status:d,raw:i};this.statusUpdateHandlers.forEach(g=>g(p)),this.messageHandlers.forEach(g=>g(i,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const s=e.match(this.inboundRegex),a=s?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof i.message_id=="string"?i.message_id:void 0,kind:s?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(i,l))}buildOutgoingEnvelope(e,t){const r={...vh,...this.config.messageDefaults??{}},i=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),s={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:i,senderFullname:i,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:s}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(i,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(i,n)=>{const s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=s[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function wh(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(e[t]=r);return e}function Xl(o,e){return(o.sender??"").toString()===e}function Zl(o,e){const t=(o.sender??"").toString(),r=e.systemSenders??["metadata","system"],i=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(i)?"assistant":r.includes(t)?"system":"agent":"system"}function Do(o){const e={raw:o},t=o.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof o.text=="string"&&o.text.trim().startsWith("{"))try{const i=o.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(i);typeof n.message=="string"&&(e.innerMessage=n.message);const s=n.metadata;s&&typeof s=="object"&&(typeof s.contentType=="string"&&(e.contentType=s.contentType),typeof s.templateId=="string"&&(e.templateId=s.templateId),s.payload!==void 0&&(e.payload=s.payload))}catch{}const r=o.attributes;if(r&&typeof r=="object"){const i=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&i&&typeof i.contentType=="string"&&(e.contentType=i.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&i&&typeof i.templateId=="string"&&(e.templateId=i.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&i&&i.payload!==void 0&&(e.payload=i.payload),e.payload===void 0&&i&&i.template!==void 0&&(e.payload=i.template)}return e}function ec(o){const e=Do(o);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const i=r[0],n=i.action,s=n&&typeof n.url=="string"?n.url:void 0,a=typeof i.description=="string"?i.description:void 0,l=o.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!s&&!a?null:{fileName:a,fileUrl:s,cloudFileId:c,templateId:e.templateId}}function ra(o,e,t){const r=Zl(o,t),i=Do(o),n=ec(o);let s="";i.innerMessage?s=i.innerMessage:typeof o.text=="string"&&(o.text.trim().startsWith("{")?i.contentType!=="300"&&(s=o.text):s=o.text);const a=typeof o.message_id=="string"?o.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof o.timestamp=="number"?new Date(o.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof o.status=="number"?kh(o.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:s,createdAt:l,status:u,metadata:{sender:o.sender,sender_fullname:o.sender_fullname??o.senderFullname,app_id:o.app_id,attributes:o.attributes}};return i.contentType&&(d.template={contentType:i.contentType,templateId:i.templateId,payload:i.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:i}}function kh(o){return o<0?"error":o>=250?"read":o>=150?"delivered":"sent"}class tc extends xo{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 ga(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new ba,this.conversationManager=new va(e.conversationId),this.usesAikaara()&&(this.connection=new ma(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 Ql({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const i=r?"connected":"disconnected";this.emit("connection:state",i),this.config.onConnectionStateChange?.(i)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,i)=>this.handleTiledeskMessage(r,i))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),i=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;i&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const i=r.map(l=>ra(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=i.map(l=>l.message),s=this.messageStore.messages,a=[...n,...s.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of i){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",i),this.config.onMessage?.(i);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const i=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:i.fileName,fileUrl:i.url,cloudFileId:i.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(i,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const i=t.conversationId??r;if(!i)return;const n=this.config.tiledeskIdentity?.userId??"",{message:s,template:a}=ra(e,i,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&s.role==="assistant")return;if(Xl(e,n)){const u=this.messageStore.reconcileOptimistic(s);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(s);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:i,role:s.role==="tool"?"system":s.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",i=e.content||"";i?this.messageStore.updateStreaming(i):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,i=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),i&&(this.emit("stream:end",{messageId:i.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",i),this.config.onMessage?.(i));break}case"message_queued":{const r=this.messageStore.messages.findLast(i=>i.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const na={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 xh(o){const e=o.lastIndexOf(".");return e<0||e===o.length-1?"":o.slice(e+1).toLowerCase()}function _h(o,e,t){const r=xh(o.name||"");if(r&&e&&e[r])return e[r];const i=o.type;return i&&i.trim().length>0?i:r&&na[r]?na[r]:t}function or(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Sh(o,e){const t=e.split(".");let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return"";return typeof r=="string"?r:""}function rc(o){const e=o.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const i=t.name||`upload-${Date.now()}`,n=_h(t,o.contentTypeMap,o.contentTypeFallback??"application/octet-stream"),s={fileName:i,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=o.authHeader?await o.authHeader():void 0,l={accept:"application/json",...o.extraHeaders??{},...a?{authorization:a}:{}};let c,u;if(o.signBody){c=or(o.signEndpoint,s);const w=or(JSON.stringify(o.signBody),s);u={method:o.signMethod??"POST",headers:{...l,"content-type":"application/json"},body:w}}else{let w=o.signEndpoint.includes("{")?o.signEndpoint:`${o.signEndpoint}?fileName={fileName}`;if(!w.includes("{contentType}")){const m=w.includes("?")?"&":"?";w=`${w}${m}contentType={contentType}`}c=or(w,s),u={method:o.signMethod??"GET",headers:l}}const d=await fetch(c,u);if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const p=await d.json().catch(()=>({})),g=Sh(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=o.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,o.s3HostRewrite):g,b=await fetch(h,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(o.registerEndpoint){const w=JSON.parse(or(JSON.stringify(o.registerBody??{}),s)),m=await fetch(o.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const k=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${k.slice(0,200)}`)}}return{url:o.viewerTemplate?or(o.viewerTemplate,s):g.split("?")[0],fileName:i,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function $o(o){return{async upload(e,t){const r=new FormData,i=o.fieldName??"file";r.append(i,e,e.name);const n=typeof o.extraFields=="function"?o.extraFields(t):o.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const s=typeof o.headers=="function"?await o.headers():o.headers??{},a=await fetch(o.endpoint,{method:o.method??"POST",body:r,headers:s,credentials:o.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(o.parseResponse)return o.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,d=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const Eh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function nc(o){const e=o.apiBase.replace(/\/$/,""),t=o.pageSize??200,r=o.pathTemplate??Eh;return{async fetchMessages(i,n){const s=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(i)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=s.startsWith("http")?s:`${e}${s.startsWith("/")?s:`/${s}`}`,l={accept:"application/json","content-type":"application/json",...o.extraHeaders??{}};if(o.getToken){const p=await o.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(o.parseResponse&&u)return o.parseResponse(u);if(Array.isArray(u))return u;const d=u;if(d&&Array.isArray(d.result))return d.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const Ah="^[A-Z]{4}[0-9]{5}[A-Z]$",Ih="^\\S{12}$",ic="^[A-Z]{4}0[A-Z0-9]{6}$",oc="^[0-9]{6}$",Th={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"},Ch={id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:Ah,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"},Ph={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:Ih,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,uppercase:!0,pattern:ic,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:oc}]},{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:"select",label:"Loan Taken From",options:[{value:"B",label:"Bank"},{value:"O",label:"Other"}]},{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"},Oh={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"},Lh={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"},Mh={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income",collapsible:!0,defaultCollapsed:!0,fields:[{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",collapsible:!0,defaultCollapsed:!0,fields:[{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"},Nh={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:oc},{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"},Rh={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:ic,maxLength:11}]}],submitLabel:"Save"},jh=[Ch,Mh,Oh,Lh,Th,Ph,Nh,Rh];function Dh(o,e){const t=o||{},r={userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:Ee(t.aadhaarNumber),isRevised:e.isRevised||"N",timestamp:Qh()};r.us80cAmount=_e(t.us80cAmount),r.us80dForSelfAndFamilyAmount=_e(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=_e(t.us80dForParentsAmount),r.hasParentOverSixty=mr(t.hasParentOverSixty),r.preventiveHealthCheckUp=_e(t.preventiveHealthCheckUp),r.medicalExpenditure=_e(t.medicalExpenditure),r.savingBankInterest=_e(t.savingBankInterest),r.fdInterest=_e(t.fdInterest),r.dividend=_e(t.dividend),r.anyOtherIncome=_e(t.anyOtherIncome),r.familyPension=_e(t.familyPension),r.cryptoSellValue=_e(t.cryptoSellPrice),r.cryptoPurchaseAmount=_e(t.cryptoPurchasePrice),r.vdaPurchaseCost=_e(t.cryptoPurchasePrice);const i=(_e(t.bizReceiptsBank)??0)+(_e(t.bizReceiptsCash)??0),n=(_e(t.profReceiptsBank)??0)+(_e(t.profReceiptsCash)??0),s=Ee(t.bizName)!==void 0||i>0;r.businessName=Ee(s?t.bizName:t.profName),r.businessAnnualTurnOver=s?i||void 0:n||void 0,r.agricultureDetails=ac(t),r.exemptIncomeAmount=_e(t.exemptIncome),r.exemptIncomeNature=Ee(t.exemptIncomeNature),_e(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Ee(t.exemptIncomeNature)??"Exempt income",value:String(_e(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:_e(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=hn(t.hpDetails,$h);l.length&&(r.hpDetails=l);const c=hn(t.salaryDetails,Uh);if(c.length){r.salaryIncome=c;const u=hn(t.salaryDetails,p=>({grossSalary:_e(p.grossSalary),employerName:Ee(p.employerName)}));u.length&&(r.salary=u);const d=an(t.salaryDetails)[0]??{};r.hraAmount=_e(d.hraReceived),r.leaveTravelAllowanceAmount=_e(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=_e(d.leaveEncashment),r.anyOtherAllowanceAmount=_e(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return rt(r)}function $h(o){const e={loanType:"HOME_LOAN",loanTakenFrom:Ee(o.loanTakenFrom),bankOrInstituteName:Ee(o.lenderName),loanAccountNo:Ee(o.loanAccountNumber),loanSanctionDate:Xr(o.sanctionDate),totalLoanAmount:_e(o.totalLoanAmount),loanOutstandingAmount:_e(o.outstandingAmount),interest:_e(o.homeLoanInterest)},t=Object.entries(e).some(([r,i])=>r!=="loanType"&&i!==void 0);return{typeOfHouseProperty:Ee(o.typeOfHouseProperty),hasRentalIncome:o.typeOfHouseProperty==="LOP"?!0:mr(o.hasRentalIncome),homeLoanInterest:_e(o.homeLoanInterest),homeLoanPrinciple:_e(o.homeLoanPrinciple),housePropertyAddress:Ee(o.housePropertyAddress),housePropertyPincode:Ee(o.housePropertyPincode),rentalIncome:_e(o.rentalIncome),nameOfTenant:Ee(o.nameOfTenant),propertyTax:_e(o.propertyTax),hasCoOwnedProperty:mr(o.hasCoOwnedProperty),coOwnerName:Ee(o.coOwnerName),coOwnerPan:Ee(o.coOwnerPan),coOwnerShare:Ee(o.coOwnerShare),loanDetails:t?[e]:void 0}}function Uh(o){return{grossSalaryIncome:_e(o.grossSalary),salary:_e(o.basicSalary),totalTdsDeposited:_e(o.totalTdsDeposited),employer:{employerName:Ee(o.employerName),employerTan:Ee(o.employerTan)},allowance:{hraAmount:_e(o.hraReceived),leaveTravelAllowanceAmount:_e(o.leaveTravelAllowance),leaveEncashmentAllowanceAmount:_e(o.leaveEncashment),anyOtherAllowanceAmount:_e(o.anyOtherAllowance)}}}function Bh(o,e){const t=[];for(const r of o){const i=Ee(r.employerName),n=Ee(r.employerTan),s=_e(r.grossSalary),a=_e(r.basicSalary),l=_e(r.totalTdsDeposited);i===void 0&&n===void 0&&s===void 0&&a===void 0&&l===void 0||t.push({grossSalary:s??0,basicSalary:a??0,employerName:i??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function Fh(o,e){const t=Ee(o.aadhaarNumber),r=Ee(o.bankAccountNumber),i=Ee(o.bankIfscCode);return t===void 0&&r===void 0&&i===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:i}]}}function qh(o,e){return{userId:nt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:_e(o.savingBankInterest)??0,fdInterest:_e(o.fdInterest)??0,dividend:_e(o.dividend)??0,anyOtherIncome:_e(o.anyOtherIncome)??0,familyPension:_e(o.familyPension)??0}}function Hh(o,e){const t=_e(o.cryptoSellPrice),r=_e(o.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:nt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function Wh(o,e){const t=(i,n,s,a)=>{const l=Ee(o[n]),c=_e(o[s]),u=_e(o[a]);return l===void 0&&c===void 0&&u===void 0?null:{businessType:i,businessCode:l??"",cashAmount:u??0,bankAmount:c??0}},r=[t("BUSINESS","bizNature","bizReceiptsBank","bizReceiptsCash"),t("PROFESSIONAL","profNature","profReceiptsBank","profReceiptsCash")].filter(i=>i!==null);return r.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function zh(o){return Ee(o.lenderName)!==void 0||Ee(o.loanAccountNumber)!==void 0||_e(o.totalLoanAmount)!==void 0||_e(o.outstandingAmount)!==void 0||_e(o.homeLoanInterest)!==void 0}function sc(o){const e=Ee(o.typeOfHouseProperty)?.toUpperCase();return _e(o.rentalIncome)!==void 0||Ee(o.nameOfTenant)!==void 0||e==="LOP"||e==="DLOP"}function Vh(o,e){const t=an(o.hpDetails).filter(zh).map(r=>{const i=rt({loanType:"HOMELOAN",bankOrInstituteName:Ee(r.lenderName),loanAccountNo:Ee(r.loanAccountNumber),loanSanctionDate:Xr(r.sanctionDate),totalLoanAmount:_e(r.totalLoanAmount),loanOutstandingAmount:_e(r.outstandingAmount),interest:_e(r.homeLoanInterest)});return rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),homeLoanInterest:_e(r.homeLoanInterest),homeLoanPrinciple:_e(r.homeLoanPrinciple),propertyTax:_e(r.propertyTax),eligible80EEAAmount:_e(r.eligible80EEAAmount),eligible80EEAmount:_e(r.eligible80EEAmount),hasCoOwnedProperty:mr(r.hasCoOwnedProperty)??!1,hasRentalIncome:sc(r),loanDetails:[i]})});return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Kh(o,e){const t=an(o.hpDetails).filter(sc).map(r=>rt({typeOfHouseProperty:Ee(r.typeOfHouseProperty),housePropertyAddress:Ee(r.housePropertyAddress),housePropertyPincode:Ee(r.housePropertyPincode),rentalIncome:_e(r.rentalIncome),propertyTax:_e(r.propertyTax),hasRentalIncome:!0,nameOfTenant:Ee(r.nameOfTenant),tenantPanNumber:Ee(r.tenantPanNumber),homeLoanInterest:_e(r.homeLoanInterest)}));return t.length?{userId:nt(e.userId),assessmentYear:e.assessmentYear,hpDetails:t}:null}function Gh(o,e){const t=o||{},r=g=>({userId:nt(e.userId),assessmentYear:e.assessmentYear,deductions:rt(g)}),i=[],n=_e(t.us80cAmount);if(n!==void 0){const g=Ee(t.us80cSubType);g?i.push(r({deductionSection:"80C",subType:g,amount:n,accountNo:Ee(t.us80cPolicyNumber)})):console.warn("[smart-edit] 80C skipped — Investment Type is required by the API")}const s=Ee(t.us80ccd1bPanNo),a=_e(t.us80ccd1bAmount);a!==void 0&&i.push(r({deductionSection:"80CCD(1B)",subType:"NPS",amount:a,accountNo:s}));const l=_e(t.us80ccd2Amount);l!==void 0&&i.push(r({deductionSection:"80CCD(2)",subType:"EMPLOYER_NPS",amount:l,accountNo:s}));const c=_e(t.us80eInterest);c!==void 0&&i.push(r({deductionSection:"80E",subType:"EDUCATION_LOAN",interest:c,loanTakenFrom:Ee(t.us80eLoanTakenFrom),bankOrInstituteName:Ee(t.us80eBankName),loanAccountNo:Ee(t.us80eLoanAccountNumber),loanSanctionDate:Xr(t.us80eLoanSanctionDate),totalLoanAmount:_e(t.us80eLoanAmount),loanOutstandingAmount:_e(t.us80eOutstandingLoan)}));const u=_e(t.us80eeInterest);u!==void 0&&i.push(r({deductionSection:"80EEB",interest:u,loanTakenFrom:Ee(t.us80eeLoanTakenFrom),bankOrInstituteName:Ee(t.us80eeBankName),loanAccountNo:Ee(t.us80eeLoanAccountNumber),loanSanctionDate:Xr(t.us80eeLoanSanctionDate),totalLoanAmount:_e(t.us80eeLoanAmount),loanOutstandingAmount:_e(t.us80eeOutstandingLoan),vehicleRegistrationNo:Ee(t.us80eeVehicleRegistrationNumber)}));const d=_e(t.us80dForSelfAndFamilyAmount);d!==void 0&&i.push(r({deductionSection:"80D",subType:"selfFamilyPremium80D",amount:d,insurerName:Ee(t.us80dForSelfAndFamilyPolicyCompany),accountNo:Ee(t.us80dForSelfAndFamilyPolicyNumber)}));const p=_e(t.us80dForParentsAmount);return p!==void 0&&i.push(r({deductionSection:"80D",subType:"parentsPremium80D",amount:p,insurerName:Ee(t.us80dForParentsPolicyCompany),accountNo:Ee(t.us80dForParentsPolicyNumber),parentSeniorCitizen:mr(t.hasParentOverSixty)??!1})),i}function Yh(o,e){const t=o||{},r=_e(t.us80gDonationInCash),i=_e(t.us80gDonationOnline),n=Ee(t.us80gNameOfCharity);if(r===void 0&&i===void 0&&n===void 0)return null;const s=(i??0)>0;return{userId:nt(e.userId),assessmentYear:e.assessmentYear,donations80g:[rt({name:n,panNumber:Ee(t.us80gCharityPan),amountInCash:r,amountOtherThanCash:i,address:Ee(t.us80gTrustAddress),pinCode:Ee(t.us80gPincode),transactionRefNum:s?Ee(t.us80gTransactionRefNo):void 0,ifscCode:s?Ee(t.us80gIfscCode):void 0})]}}function ac(o){const e=o||{},t=_e(e.agricultureIncome),r=_e(e.agricultureExpenditure),i=rt({landInAcre:_e(e.agricultureLandInAcre),nameOfDistrict:Ee(e.agricultureLandDistrict),pinCode:Ee(e.agricultureLandPincode),owner:Ee(e.agricultureLandOwner),typeOfLand:Ee(e.agricultureLandType)})??{},n=Object.keys(i).length>0;if(!(t===void 0&&r===void 0&&!n))return rt({income:t,expenditure:r??0,agricultureLandDetails:n?[i]:void 0})}function Jh(o,e){const t=ac(o);return t?{userId:nt(e.userId),assessmentYear:e.assessmentYear,agricultureDetails:t}:null}function nt(o){if(o===void 0||o==="")return;const e=Number(o);return Number.isFinite(e)&&String(e)===String(o)?e:o}function _e(o){if(o==null||o==="")return;const e=typeof o=="number"?o:Number(o);return Number.isFinite(e)?e:void 0}function Ee(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function mr(o){return o===!0||o===!1?o:void 0}function Qh(){const o=new Date,e=(t,r=2)=>String(t).padStart(r,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())}T${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}.${e(o.getMilliseconds(),3)}`}function Xr(o){const e=Ee(o);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function an(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function hn(o,e){return an(o).map(t=>rt(e(t))).filter(t=>t!==void 0)}function rt(o){if(Array.isArray(o)){const e=o.map(rt).filter(t=>t!==void 0);return e.length?e:void 0}if(o&&typeof o=="object"){const e={};for(const[t,r]of Object.entries(o)){const i=rt(r);i!==void 0&&(e[t]=i)}return Object.keys(e).length?e:void 0}return o}function Xh(o){const e=o&&typeof o=="object"?o:{},t={},r=De(e.employers),i=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(X=>{const z=pn(X.salary),W=pn(X.perquisites),ne=pn(X.profitsInLieuOfSalaryType),D=z+W+ne,G=rf(X.allowance);return{employerName:Ce(X.employerName),employerTan:Ce(X.employerTAN),basicSalary:z||void 0,grossSalary:D||void 0,hraReceived:G.hra,leaveTravelAllowance:G.lta,leaveEncashment:G.leaveEncashment,anyOtherAllowance:G.other,totalTdsDeposited:tf(X,i,r)??Me(X.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(X=>{const z=De(X.loanDetails),W=z.length?z[0]:void 0,ne=Me(X.grossAnnualRentReceived),D=z.length?z.reduce((te,ve)=>te+(Me(ve.interest)??0),0):void 0,G=De(X.tenant),L=De(X.coOwners),Y=G[0],pe=L[0];return{typeOfHouseProperty:Ce(X.propertyType),loanTakenFrom:Ce(W?.loanTakenFrom),lenderName:Ce(W?.bankOrInstituteName),loanAccountNumber:Ce(W?.loanAccountNo),sanctionDate:fn(W?.loanSanctionDate),totalLoanAmount:Me(W?.totalLoanAmount),outstandingAmount:Me(W?.loanOutstandingAmount),homeLoanInterest:D,homeLoanPrinciple:void 0,housePropertyAddress:Ce(X.address),housePropertyPincode:Ce(X.pinCode),rentalIncome:ne,nameOfTenant:Ce(Y?.name),tenantPanNumber:Ce(Y?.panNumber),eligible80EEAmount:Me(X.eligible80EEAmount),eligible80EEAAmount:Me(X.eligible80EEAAmount),propertyTax:Me(X.propertyTax),hasCoOwnedProperty:L.length>0,coOwnerName:Ce(pe?.name),coOwnerPan:Ce(pe?.panNumber),coOwnerShare:Me(pe?.share)?.toString()}}));const s=De(e.deductionUS80CDetails),a=At(s.map(X=>Me(X.amount))),l=s.find(X=>Ce(X.identificationNo));t.us80cAmount=a,t.us80cPolicyNumber=Ce(l?.identificationNo);const c=De(e.investments)[0],u=Array.isArray(c?.bifurcation)?c.bifurcation[0]:void 0;t.us80cSubType=Ce(u?.subType??c?.investmentType);const d=De(e.deductionUS80DDetails),p=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="DEPENDANT"),g=d.find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS")??De(e.insurances).find(X=>Ce(X.policyFor)?.toUpperCase()==="PARENTS"),h=Array.isArray(p?.bifurcation)?p.bifurcation[0]:void 0,b=Array.isArray(g?.bifurcation)?g.bifurcation[0]:void 0;t.us80dForSelfAndFamilyAmount=Me(p?.healthInsuranceAmount??p?.premium),t.us80dForSelfAndFamilyPolicyCompany=Ce(p?.insurerName??h?.insurerName),t.us80dForSelfAndFamilyPolicyNumber=Ce(p?.policyNo??h?.accountNo),t.us80dForParentsAmount=Me(g?.healthInsuranceAmount??g?.premium),t.us80dForParentsPolicyCompany=Ce(g?.insurerName??b?.insurerName),t.us80dForParentsPolicyNumber=Ce(g?.policyNo??b?.accountNo),t.hasParentOverSixty=nf(e.systemFlags?.hasParentOverSixty),t.us80ccd1bAmount=void 0,t.us80ccd1bPanNo=Ce(e.pranNumber),t.us80ccd2Amount=void 0;const w=De(e.donations)[0];t.us80gDonationInCash=Me(w?.amountInCash??w?.donationInCash),t.us80gDonationOnline=Me(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?.transactionRefNum??w?.transactionReferenceNo??w?.transactionRefNo),t.us80gIfscCode=Ce(w?.ifscCode??w?.ifsCode);const m=De(e.loanDetails),k=X=>m.find(z=>Ce(z.loanType)?.toUpperCase()===X),_=k("EDUCATION"),v=k("ELECTRIC_VEHICLE");t.us80eLoanTakenFrom=Ce(_?.loanTakenFrom),t.us80eBankName=Ce(_?.bankOrInstituteName),t.us80eLoanAccountNumber=Ce(_?.loanAccountNo),t.us80eLoanSanctionDate=fn(_?.loanSanctionDate),t.us80eLoanAmount=Me(_?.totalLoanAmount),t.us80eOutstandingLoan=Me(_?.loanOutstandingAmount),t.us80eInterest=Me(_?.interest),t.us80eeLoanTakenFrom=Ce(v?.loanTakenFrom),t.us80eeBankName=Ce(v?.bankOrInstituteName),t.us80eeLoanAccountNumber=Ce(v?.loanAccountNo),t.us80eeLoanSanctionDate=fn(v?.loanSanctionDate),t.us80eeLoanAmount=Me(v?.totalLoanAmount),t.us80eeOutstandingLoan=Me(v?.loanOutstandingAmount),t.us80eeVehicleRegistrationNumber=Ce(v?.vehicleRegistrationNo),t.us80eeInterest=Me(v?.interest);const E=De(e.insurances);t.preventiveHealthCheckUp=At(E.map(X=>Me(X.preventiveCheckUp))),t.medicalExpenditure=At(E.map(X=>Me(X.medicalExpenditure)));const S=De(e.incomes),I=X=>At(S.filter(z=>Ce(z.incomeType)===X).map(z=>Me(z.amount)));t.savingBankInterest=I("SAVING_INTEREST"),t.fdInterest=I("FD_RD_INTEREST"),t.anyOtherIncome=I("ANY_OTHER"),t.familyPension=I("FAMILY_PENSION"),t.dividend=At(De(e.dividendIncomes).map(X=>Me(X.income)));const P=e.business;if(P){const X=De(P.presumptiveIncomes),z=D=>{const G=Ce(D.businessType)?.trim().toUpperCase()??"";if(G.includes("PROFESSION")||G==="44ADA")return!0;if(G.includes("BUSINESS")||G==="44AD"||G==="PRESUMPTIVE")return!1;const L=De(D.incomes),Y=pe=>Me(L.find(te=>Ce(te.incomeType)===pe)?.receipts)??0;return Y("ANY_OTHER")>0?!0:(Y("BANK")>0||Y("CASH")>0,!1)},W=D=>X.find(G=>z(G)===D),ne=(D,G)=>{if(!D)return;const L=De(D.incomes),Y=te=>Me(L.find(ve=>Ce(ve.incomeType)===te)?.receipts),pe=Y("BANK")||Y("ANY_OTHER");t[G.nature]=Ce(D.natureOfBusiness),t[G.bank]=pe||void 0,t[G.cash]=Y("CASH")||void 0,t[G.net]=At(L.map(te=>Me(te.presumptiveIncome)))||void 0};ne(W(!1),{nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),ne(W(!0),{nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const O=De(e.capitalGain).filter(X=>Ce(X.assetType)?.toUpperCase()==="VDA").flatMap(X=>De(X.assetDetails));O.length&&(t.cryptoSellPrice=At(O.map(X=>Me(X.sellValue))),t.cryptoPurchasePrice=At(O.map(X=>Me(X.purchaseCost))));const j=e.agriculturalDetails,T=e.agriculturalIncome;t.agricultureIncome=Me(T?.netAgriculturalIncome)??Me(T?.grossAgriculturalReceipts)??Me(j?.income),t.agricultureExpenditure=Me(T?.expenditureIncurredOnAgriculture)??Me(j?.expenditure);const $=De(j?.agricultureLandDetails??j?.agriculturalLandDetails??e.agriculturalLandDetails)[0];$&&(t.agricultureLandInAcre=Me($.landInAcre),t.agricultureLandDistrict=Ce($.nameOfDistrict),t.agricultureLandPincode=Ce($.pinCode),t.agricultureLandOwner=Zh($.owner),t.agricultureLandType=ef($.typeOfLand)),t.aadhaarNumber=Ce(e.aadharNumber);const U=De(e.bankDetails)[0];return U&&(t.bankAccountNumber=Ce(U.accountNumber),t.bankIfscCode=Ce(U.ifsCode)),lc(t)}function Zh(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="O"||t==="OWNED"?"Owned":t==="H"||t.startsWith("HELD")?"Held on lease":e}function ef(o){const e=Ce(o)?.trim();if(!e)return;const t=e.toUpperCase();return t==="IRG"||t==="IRRIGATED"?"Irrigated":t==="RF"||t.startsWith("RAIN")?"Rain-fed":e}function fn(o){const e=Ce(o);if(!e)return;const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function pn(o){return De(o).reduce((e,t)=>e+(Me(t.taxableAmount)??0),0)}function tf(o,e,t){if(!e.length)return;const r=Ce(o.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Ce(n.deductorTAN)?.trim().toUpperCase()===r)return Me(n.totalTdsDeposited)}const i=Ce(o.employerName)?.trim().toLowerCase();if(i){for(const n of e)if(Ce(n.deductorName)?.trim().toLowerCase()===i)return Me(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Me(e[0].totalTdsDeposited)}function rf(o){const e=De(o);if(!e.length)return{};let t,r,i,n;for(const s of e){const a=Me(s.exemptAmount)??Me(s.allowanceAmount);switch(Ce(s.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":i=a;break;default:n=(n??0)+(Me(s.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:i,other:n}}function At(o){let e=0,t=!1;for(const r of o)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(o){return Array.isArray(o)?o.filter(e=>e&&typeof e=="object"):[]}function Me(o){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"&&o.trim()!==""&&Number.isFinite(Number(o)))return Number(o)}function Ce(o){if(o==null)return;const e=String(o).trim();return e===""?void 0:e}function nf(o){if(typeof o=="boolean")return o;if(typeof o=="string"){const e=o.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="y")return!0;if(e==="false"||e==="0"||e==="no"||e==="n")return!1}if(typeof o=="number")return o===1?!0:o===0?!1:void 0}function lc(o){const e={};for(const[t,r]of Object.entries(o))r!==void 0&&(Array.isArray(r)?e[t]=r.map(i=>i&&typeof i=="object"?lc(i):i):e[t]=r);return e}function mn(){if(typeof window>"u")return null;const o=window,e=o.__aikaara_runtime__;if(!e||typeof e.getChatJwt!="function")return console.warn("[smart-edit] API disabled: window.__aikaara_runtime__.getChatJwt is missing — the chat was not mounted via the SDK mountFromSlug path."),null;const t=o.__aikaara_descriptor__??{},r=mf(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const i=gf(e.slug),n=typeof i?.tenantJwt=="string"?i.tenantJwt:"",s=e.getChatJwt,a=async()=>n||await s(),l=(i&&i.userId!=null&&i.userId!==""?String(i.userId):yf(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:bf(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||vf(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function of(o){const e=await o.getToken(),t=o.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${o.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...o.headers}});if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${i.slice(0,200)}`)}return Xh(Uo(await r.json().catch(()=>({}))))}async function sf(o,e){const t=await o.getToken(),r=o.userId,i={...Dh(e,{userId:r,assessmentYear:o.assessmentYear,isRevised:o.isRevised}),sendSummary:!0},n=o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,s={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...o.headers};o.txbdyApiKey&&(s["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(i).join(", "));const a=await fetch(n,{method:"PUT",headers:s,body:JSON.stringify(i)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Uo(await a.json().catch(()=>({})))}async function af(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/salary`,e)}async function lf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function ia(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function cf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function uf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function df(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/deductions`,e)}async function hf(o,e){return _t(o,o.submitUrl||`${o.baseUrl}/itr/v1/automation/data`,e)}async function ff(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/hp-income`,e)}async function pf(o,e){return _t(o,`${o.baseUrl}/itr/v1/automation/vda`,e)}async function _t(o,e,t){const i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await o.getToken()}`,...o.headers};o.txbdyApiKey&&(i["txbdy-api-key"]=o.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:i,body:JSON.stringify(t)});if(!n.ok){const s=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${s.slice(0,200)}`)}return Uo(await n.json().catch(()=>({})))}function mf(o){const e=[o.cloud?.listEndpoint,o.cloud?.downloadEndpoint,o.upload?.signEndpoint,o.login?.pan?.basicPanEndpoint,o.login?.pan?.panDetailEndpoint,o.methodPicker?.leaderAssignmentEndpoint];for(const t of e)if(!(typeof t!="string"||!t))try{const r=new URL(t);if(/(^|\.)taxbuddy\.com$/i.test(r.hostname))return r.origin}catch{}return null}function gf(o){if(!o||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${o}`);if(!e)return null;const t=JSON.parse(e);return t&&typeof t.identity=="object"&&t.identity!==null?t.identity:null}catch{return null}}function bf(o){const e={};if(!o)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,i]of Object.entries(o))!t.test(r)&&typeof i=="string"&&(e[r]=i);return e}function yf(o){if(!o)return;const e=o.userId??o.id??o.ext_uid??o.extUid;return e==null||e===""?void 0:String(e)}function Uo(o){if(o&&typeof o=="object"){const e=o;return e.data&&typeof e.data=="object"?e.data:e}return{}}function vf(){const o=new Date,e=o.getMonth()>=3?o.getFullYear():o.getFullYear()-1;return`${e}-${e+1}`}const wf=["No, I have concerns","No, I have a concerns"];function cc(o){const e=window.__aikaara_descriptor__?.smartEdit?.openOnMessages,t=Array.isArray(e)?e:wf;if(t.length===0)return!1;const r=n=>n.trim().toLowerCase(),i=r(o);return t.some(n=>typeof n=="string"&&r(n)===i)}class kf{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new tc(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(cc(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},i=t.attributes?.action??{},n={...t.attributes,action:{...r,...i}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:jh,data:{}});const t=mn();if(!(!t||!t.baseUrl))try{const r=await of(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=mn();if(!r)return;const i={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],s=Bh(n,i);s&&await af(r,s)}else if(e==="bank-details"){const n=Fh(t,i);n&&await lf(r,n)}else if(e==="other-sources")await ia(r,qh(t,i));else if(e==="business-profession"){const n=Wh(t,i);n&&await cf(r,n)}else if(e==="crypto-income"){const n=Hh(t,i);n&&await pf(r,n)}else if(e==="agricultural-income"){const n=Jh(t,i);n&&await uf(r,n)}else if(e==="deductions"){for(const s of Gh(t,i))await df(r,s);const n=Yh(t,i);n&&await ia(r,n)}else if(e==="house-property"){const n=Vh(t,i);n&&await hf(r,n);const s=Kh(t,i);s&&await ff(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=mn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await sf(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 uc 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||su,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||qo,position:this.getAttribute("position")||this._config.position||ou,width:Number(this.getAttribute("width"))||this._config.width||tu,height:Number(this.getAttribute("height"))||this._config.height||ru,fontFamily:this._config.fontFamily||iu,borderRadius:this._config.borderRadius??nu,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ho,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||au,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,i){if(typeof document>"u")return;const n=document.documentElement,s=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};s("primary",e?.primary??t),s("primary-hover",e?.primaryHover),s("primary-contrast",e?.primaryContrast),s("surface",e?.surface),s("surface-muted",e?.surfaceMuted),s("border",e?.border),s("text",e?.text),s("text-muted",e?.textMuted),s("font",e?.font??i),s("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),s("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),s("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),s("user-bubble-bg",e?.userBubbleBg),s("user-bubble-text",e?.userBubbleText),s("bot-bubble-bg",e?.botBubbleBg),s("bot-bubble-text",e?.botBubbleText),s("modal-width",e?.modalWidth),s("modal-height",e?.modalHeight),s("modal-max-width",e?.modalMaxWidth),s("modal-max-height",e?.modalMaxHeight),s("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=i=>typeof i=="number"?`${i}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,i])=>i!==void 0&&i!=="").map(([i,n])=>`--aikaara-${i}: ${n};`).join(`
|
|
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
|
-
font-family: var(--aikaara-font);
|
|
11
|
-
position: fixed;
|
|
12
|
-
z-index: 9999;
|
|
13
|
-
bottom: var(--aikaara-offset-y);
|
|
14
|
-
${e.position==="bottom-left"?"left":"right"}: var(--aikaara-offset-x);
|
|
15
|
-
`,i=`
|
|
16
|
-
font-family: var(--aikaara-font);
|
|
17
|
-
display: flex;
|
|
18
|
-
flex-direction: column;
|
|
19
|
-
width: 100%;
|
|
20
|
-
height: 100%;
|
|
21
|
-
min-height: var(--aikaara-embed-min-height, 560px);
|
|
22
|
-
`,n=`
|
|
23
|
-
width: var(--aikaara-panel-width);
|
|
24
|
-
height: var(--aikaara-panel-height);
|
|
25
|
-
max-height: calc(100vh - 100px);
|
|
26
|
-
border-radius: var(--aikaara-radius);
|
|
27
|
-
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
|
|
28
|
-
border: 1px solid var(--aikaara-border);
|
|
29
|
-
position: absolute;
|
|
30
|
-
bottom: calc(var(--aikaara-bubble-size) + 16px);
|
|
31
|
-
${e.position==="bottom-left"?"left":"right"}: 0;
|
|
32
|
-
transition: opacity 200ms ease, transform 200ms ease;
|
|
33
|
-
`,s=`
|
|
34
|
-
width: 100%;
|
|
35
|
-
flex: 1 1 auto;
|
|
36
|
-
min-height: 0;
|
|
37
|
-
border-radius: var(--aikaara-radius);
|
|
38
|
-
border: 1px solid var(--aikaara-border);
|
|
39
|
-
position: relative;
|
|
40
|
-
`;this.shadow.innerHTML=`
|
|
41
|
-
<style>
|
|
42
|
-
:host {
|
|
43
|
-
--aikaara-primary: ${e.primaryColor};
|
|
44
|
-
--aikaara-primary-hover: ${this.darkenColor(e.primaryColor||qo)};
|
|
45
|
-
/* Cascade through descriptor.theme.surface / surfaceMuted /
|
|
46
|
-
* text / textMuted / border when those are present (themeVars
|
|
47
|
-
* sets the canonical token below). When the descriptor doesn't
|
|
48
|
-
* theme the chat, the legacy literal defaults still apply, so
|
|
49
|
-
* an un-themed widget renders exactly as it did before 0.8.5. */
|
|
50
|
-
--aikaara-bg: var(--aikaara-surface, #ffffff);
|
|
51
|
-
--aikaara-bg-secondary: var(--aikaara-surface-muted, #f9fafb);
|
|
52
|
-
--aikaara-text: var(--aikaara-text, #1f2937);
|
|
53
|
-
--aikaara-text-secondary: var(--aikaara-text-muted, #6b7280);
|
|
54
|
-
--aikaara-border: var(--aikaara-border, #e5e7eb);
|
|
55
|
-
--aikaara-radius: ${e.borderRadius}px;
|
|
56
|
-
--aikaara-font: ${e.fontFamily};
|
|
57
|
-
--aikaara-panel-width: ${e.width}px;
|
|
58
|
-
--aikaara-panel-height: ${e.height}px;
|
|
59
|
-
--aikaara-bubble-size: 60px;
|
|
60
|
-
--aikaara-offset-x: ${e.offset?.x??20}px;
|
|
61
|
-
--aikaara-offset-y: ${e.offset?.y??20}px;
|
|
62
|
-
${this.themeVars(e.themeTokens)}
|
|
63
|
-
${t?i:r}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
.aikaara-panel {
|
|
67
|
-
background: var(--aikaara-bg);
|
|
68
|
-
display: flex;
|
|
69
|
-
flex-direction: column;
|
|
70
|
-
overflow: hidden;
|
|
71
|
-
${t?s:n}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
.aikaara-panel[hidden] {
|
|
75
|
-
display: none;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
.aikaara-panel.entering {
|
|
79
|
-
opacity: 0;
|
|
80
|
-
transform: translateY(8px) scale(0.98);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
.aikaara-panel.visible {
|
|
84
|
-
opacity: 1;
|
|
85
|
-
transform: translateY(0) scale(1);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
aikaara-chat-header,
|
|
89
|
-
aikaara-message-list,
|
|
90
|
-
aikaara-chat-input,
|
|
91
|
-
aikaara-error-banner {
|
|
92
|
-
display: block;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
aikaara-message-list {
|
|
96
|
-
flex: 1;
|
|
97
|
-
overflow: scroll;
|
|
98
|
-
min-height: 0;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
aikaara-chat-input { flex-shrink: 0; }
|
|
102
|
-
aikaara-chat-header { flex-shrink: 0; }
|
|
103
|
-
</style>
|
|
104
|
-
|
|
105
|
-
${t?"":"<aikaara-chat-bubble></aikaara-chat-bubble>"}
|
|
106
|
-
|
|
107
|
-
<div class="aikaara-panel ${t?"visible":"entering"}" ${t?"":"hidden"} role="${t?"region":"dialog"}" aria-label="Chat">
|
|
108
|
-
${e.showHeader===!1?"":`<aikaara-chat-header
|
|
109
|
-
title="${e.title||"Chat"}"
|
|
110
|
-
${e.subtitle?`subtitle="${e.subtitle}"`:""}
|
|
111
|
-
${e.avatarUrl?`avatar-url="${e.avatarUrl}"`:""}
|
|
112
|
-
></aikaara-chat-header>`}
|
|
113
|
-
<aikaara-message-list></aikaara-message-list>
|
|
114
|
-
<aikaara-chat-input
|
|
115
|
-
placeholder="${e.placeholder||Ho}"
|
|
116
|
-
${this._config.uploadAdapter?"":"disable-attach"}
|
|
117
|
-
${e.input?.attachPosition==="right"?'attach-position="right"':""}
|
|
118
|
-
${e.input?.sendButtonShape==="square"?'send-shape="square"':""}
|
|
119
|
-
></aikaara-chat-input>
|
|
120
|
-
<aikaara-error-banner></aikaara-error-banner>
|
|
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 kf(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),i=Math.max(0,(t>>8&255)-20),n=Math.max(0,(t&255)-20);return`#${(r<<16|i<<8|n).toString(16).padStart(6,"0")}`}catch{return e}}}class dc 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
|
-
<style>
|
|
124
|
-
.bubble {
|
|
125
|
-
width: var(--aikaara-bubble-size, 60px);
|
|
126
|
-
height: var(--aikaara-bubble-size, 60px);
|
|
127
|
-
border-radius: 50%;
|
|
128
|
-
background: var(--aikaara-primary, #6366f1);
|
|
129
|
-
color: #ffffff;
|
|
130
|
-
border: none;
|
|
131
|
-
cursor: pointer;
|
|
132
|
-
display: flex;
|
|
133
|
-
align-items: center;
|
|
134
|
-
justify-content: center;
|
|
135
|
-
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
|
136
|
-
transition: transform 200ms ease, box-shadow 200ms ease;
|
|
137
|
-
}
|
|
138
|
-
.bubble:hover {
|
|
139
|
-
transform: scale(1.05);
|
|
140
|
-
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
|
|
141
|
-
}
|
|
142
|
-
.bubble svg {
|
|
143
|
-
width: 28px;
|
|
144
|
-
height: 28px;
|
|
145
|
-
}
|
|
146
|
-
.bubble-text {
|
|
147
|
-
font-family: var(--aikaara-font, system-ui, sans-serif);
|
|
148
|
-
font-size: 12px;
|
|
149
|
-
font-weight: 500;
|
|
150
|
-
}
|
|
151
|
-
</style>
|
|
152
|
-
<button class="bubble" aria-label="Open chat">
|
|
153
|
-
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
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
|
-
</svg>
|
|
156
|
-
</button>
|
|
157
|
-
`}setIcon(e){const t=this.shadow.querySelector(".bubble");t&&(t.innerHTML=e)}}const xf=[{id:"edit-itr",label:"Edit ITR Details",icon:"edit"}];class hc extends HTMLElement{shadow;actions=xf;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 i=t.dataset.actionId||"",n=t.dataset.actionLabel||"";this.closeMenu(),this.dispatchEvent(new CustomEvent("aikaara-chat-action",{detail:{id:i,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"),i=this.getAttribute("status")||"connected",n=i==="connected"?"#10b981":i==="connecting"||i==="reconnecting"?"#f59e0b":"#ef4444",s=this.actions.map(a=>`
|
|
158
|
-
<button class="menu-item" type="button" data-action-id="${a.id}" data-action-label="${a.label}">
|
|
159
|
-
<span class="menu-item-icon">${this.iconSvg(a.icon)}</span>
|
|
160
|
-
<span class="menu-item-label">${a.label}</span>
|
|
161
|
-
</button>`).join("");this.shadow.innerHTML=`
|
|
162
|
-
<style>
|
|
163
|
-
:host { position: relative; display: block; }
|
|
164
|
-
.header {
|
|
165
|
-
display: flex;
|
|
166
|
-
align-items: center;
|
|
167
|
-
gap: 12px;
|
|
168
|
-
padding: 14px 16px;
|
|
169
|
-
background: var(--aikaara-primary, #6366f1);
|
|
170
|
-
color: #ffffff;
|
|
171
|
-
flex-shrink: 0;
|
|
172
|
-
}
|
|
173
|
-
.avatar {
|
|
174
|
-
width: 36px;
|
|
175
|
-
height: 36px;
|
|
176
|
-
border-radius: 50%;
|
|
177
|
-
background: rgba(255,255,255,0.2);
|
|
178
|
-
display: flex;
|
|
179
|
-
align-items: center;
|
|
180
|
-
justify-content: center;
|
|
181
|
-
flex-shrink: 0;
|
|
182
|
-
overflow: hidden;
|
|
183
|
-
}
|
|
184
|
-
.avatar img {
|
|
185
|
-
width: 100%;
|
|
186
|
-
height: 100%;
|
|
187
|
-
object-fit: cover;
|
|
188
|
-
}
|
|
189
|
-
.avatar svg {
|
|
190
|
-
width: 20px;
|
|
191
|
-
height: 20px;
|
|
192
|
-
}
|
|
193
|
-
.info {
|
|
194
|
-
flex: 1;
|
|
195
|
-
min-width: 0;
|
|
196
|
-
}
|
|
197
|
-
.title {
|
|
198
|
-
font-size: 15px;
|
|
199
|
-
font-weight: 600;
|
|
200
|
-
line-height: 1.2;
|
|
201
|
-
display: flex;
|
|
202
|
-
align-items: center;
|
|
203
|
-
gap: 6px;
|
|
204
|
-
}
|
|
205
|
-
.status-dot {
|
|
206
|
-
width: 8px;
|
|
207
|
-
height: 8px;
|
|
208
|
-
border-radius: 50%;
|
|
209
|
-
flex-shrink: 0;
|
|
210
|
-
}
|
|
211
|
-
.subtitle {
|
|
212
|
-
font-size: 12px;
|
|
213
|
-
opacity: 0.85;
|
|
214
|
-
white-space: nowrap;
|
|
215
|
-
overflow: hidden;
|
|
216
|
-
text-overflow: ellipsis;
|
|
217
|
-
}
|
|
218
|
-
.actions { display: flex; align-items: center; gap: 4px; }
|
|
219
|
-
.icon-btn {
|
|
220
|
-
background: none;
|
|
221
|
-
border: none;
|
|
222
|
-
color: #ffffff;
|
|
223
|
-
cursor: pointer;
|
|
224
|
-
padding: 4px;
|
|
225
|
-
border-radius: 4px;
|
|
226
|
-
display: flex;
|
|
227
|
-
align-items: center;
|
|
228
|
-
justify-content: center;
|
|
229
|
-
opacity: 0.8;
|
|
230
|
-
transition: opacity 200ms, background 200ms;
|
|
231
|
-
}
|
|
232
|
-
.close-btn {
|
|
233
|
-
display: var(--aikaara-close-btn-display, flex);
|
|
234
|
-
}
|
|
235
|
-
.icon-btn:hover {
|
|
236
|
-
opacity: 1;
|
|
237
|
-
background: rgba(255,255,255,0.12);
|
|
238
|
-
}
|
|
239
|
-
.icon-btn svg {
|
|
240
|
-
width: 20px;
|
|
241
|
-
height: 20px;
|
|
242
|
-
}
|
|
243
|
-
.menu-wrap { position: relative; }
|
|
244
|
-
.menu {
|
|
245
|
-
position: absolute;
|
|
246
|
-
top: 100%;
|
|
247
|
-
right: 0;
|
|
248
|
-
margin-top: 6px;
|
|
249
|
-
min-width: 220px;
|
|
250
|
-
background: var(--aikaara-surface, #ffffff);
|
|
251
|
-
color: var(--aikaara-text, #1f2937);
|
|
252
|
-
border-radius: 8px;
|
|
253
|
-
box-shadow: 0 8px 24px rgba(0,0,0,0.18);
|
|
254
|
-
padding: 6px;
|
|
255
|
-
z-index: 1000;
|
|
256
|
-
display: none;
|
|
257
|
-
flex-direction: column;
|
|
258
|
-
gap: 2px;
|
|
259
|
-
}
|
|
260
|
-
.menu.open { display: flex; }
|
|
261
|
-
.menu-item {
|
|
262
|
-
display: flex;
|
|
263
|
-
align-items: center;
|
|
264
|
-
gap: 10px;
|
|
265
|
-
width: 100%;
|
|
266
|
-
padding: 9px 10px;
|
|
267
|
-
background: none;
|
|
268
|
-
border: none;
|
|
269
|
-
color: inherit;
|
|
270
|
-
font: inherit;
|
|
271
|
-
font-size: 13.5px;
|
|
272
|
-
text-align: left;
|
|
273
|
-
border-radius: 6px;
|
|
274
|
-
cursor: pointer;
|
|
275
|
-
}
|
|
276
|
-
.menu-item:hover {
|
|
277
|
-
background: var(--aikaara-menu-hover, rgba(99,102,241,0.10));
|
|
278
|
-
}
|
|
279
|
-
.menu-item-icon {
|
|
280
|
-
display: flex;
|
|
281
|
-
align-items: center;
|
|
282
|
-
justify-content: center;
|
|
283
|
-
flex-shrink: 0;
|
|
284
|
-
color: var(--aikaara-primary, #6366f1);
|
|
285
|
-
}
|
|
286
|
-
.menu-item-icon svg { width: 16px; height: 16px; }
|
|
287
|
-
.menu-item-label { flex: 1; }
|
|
288
|
-
</style>
|
|
289
|
-
<div class="header">
|
|
290
|
-
<div class="avatar">
|
|
291
|
-
${r?`<img src="${r}" alt="Avatar" />`:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>'}
|
|
292
|
-
</div>
|
|
293
|
-
<div class="info">
|
|
294
|
-
<div class="title">
|
|
295
|
-
${e}
|
|
296
|
-
<span class="status-dot" style="background:${n}"></span>
|
|
297
|
-
</div>
|
|
298
|
-
${t?`<div class="subtitle">${t}</div>`:""}
|
|
299
|
-
</div>
|
|
300
|
-
<div class="actions">
|
|
301
|
-
${this.actions.length>0?`
|
|
302
|
-
<div class="menu-wrap">
|
|
303
|
-
<button class="icon-btn menu-btn" aria-label="More actions" type="button">
|
|
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
|
-
</button>
|
|
306
|
-
<div class="menu" role="menu">
|
|
307
|
-
${s}
|
|
308
|
-
</div>
|
|
309
|
-
</div>`:""}
|
|
310
|
-
<button class="icon-btn close-btn" aria-label="Close chat" type="button">
|
|
311
|
-
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
312
|
-
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
|
313
|
-
</svg>
|
|
314
|
-
</button>
|
|
315
|
-
</div>
|
|
316
|
-
</div>
|
|
317
|
-
`}setStatus(e){this.setAttribute("status",e)}}const _f=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i,Sf=/&(quot|apos|amp|lt|gt|nbsp|#\d+|#x[0-9a-f]+);/i,Ef={""":'"',"'":"'","<":"<",">":">","&":"&"," ":" "};function Af(o){return o.replace(/&(quot|apos|lt|gt|nbsp);/gi,e=>Ef[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 Kt(o){if(_f.test(o))return o;const e=Sf.test(o)?Af(o):o;let t=If(e);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(r,i,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,i,n)=>{const s=/[.,!?;:]+$/.exec(n),a=s?s[0]:"",l=a?n.slice(0,n.length-a.length):n;return`${i}<a href="${l}" target="_self" rel="noopener noreferrer">${l}</a>${a}`}),t=t.replace(/\n/g,"<br>"),t}function If(o){const e={"&":"&","<":"<",">":">",'"':""","'":"'"};return o.replace(/[&<>"']/g,t=>e[t])}const Tf=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Cf={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Gt(o){const e=document.createElement("template");return e.innerHTML=o,fc(e.content),e.innerHTML}function fc(o){const e=Array.from(o.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,i=r.tagName.toLowerCase();if(!Tf.has(i)){const a=document.createTextNode(r.textContent||"");o.replaceChild(a,t);continue}const n=Cf[i]||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")}fc(t)}}function pc(o,e={}){const{width:t=600,height:r=700,closeOnTypes:i}=e,n=Math.round(window.screenX+(window.outerWidth-t)/2),s=Math.round(window.screenY+(window.outerHeight-r)/2),a=window.open(o,"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;i&&typeof d=="string"&&!i.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 Pf(o){const e=Date.now()-o.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 i=Math.round(r/60);if(i<24)return`${i} hr ago`;const n=Math.round(i/24);return n===1?"Yesterday":n<7?`${n} d ago`:o.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class mc 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(i=>r.includes(i)):!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 i=this.linkHandlers.some(s=>oa(r.href,s.match));r.target==="_self"&&!i||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
|
-
<style>
|
|
319
|
-
:host {
|
|
320
|
-
display: flex;
|
|
321
|
-
flex-direction: column;
|
|
322
|
-
min-height: 0;
|
|
323
|
-
}
|
|
324
|
-
.message-list {
|
|
325
|
-
flex: 1;
|
|
326
|
-
overflow-y: auto;
|
|
327
|
-
padding: 16px;
|
|
328
|
-
display: flex;
|
|
329
|
-
flex-direction: column;
|
|
330
|
-
gap: 8px;
|
|
331
|
-
}
|
|
332
|
-
.message-list { scrollbar-width: thin; scrollbar-color: var(--aikaara-border, #e5e7eb) transparent; }
|
|
333
|
-
.message-list::-webkit-scrollbar { width: 6px; height: 6px; }
|
|
334
|
-
.message-list::-webkit-scrollbar-track { background: transparent; }
|
|
335
|
-
.message-list::-webkit-scrollbar-thumb { background: var(--aikaara-border, #e5e7eb); border-radius: 3px; }
|
|
336
|
-
.message-list::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
|
|
337
|
-
.message-list::-webkit-scrollbar-corner { background: transparent; }
|
|
338
|
-
.message-wrap { display: flex; flex-direction: column; }
|
|
339
|
-
.message-wrap.user { align-items: flex-end; }
|
|
340
|
-
.message-wrap.assistant,
|
|
341
|
-
.message-wrap.agent { align-items: flex-start; }
|
|
342
|
-
.message-wrap.system { align-items: center; text-align: center; }
|
|
343
|
-
.message-wrap.system .bubble {
|
|
344
|
-
background: transparent;
|
|
345
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
346
|
-
font-size: 12px;
|
|
347
|
-
font-style: italic;
|
|
348
|
-
padding: 4px 0;
|
|
349
|
-
}
|
|
350
|
-
.attachments {
|
|
351
|
-
display: flex;
|
|
352
|
-
flex-direction: column;
|
|
353
|
-
gap: 4px;
|
|
354
|
-
margin-top: 6px;
|
|
355
|
-
}
|
|
356
|
-
.attachment {
|
|
357
|
-
display: inline-flex;
|
|
358
|
-
align-items: center;
|
|
359
|
-
gap: 6px;
|
|
360
|
-
padding: 6px 10px;
|
|
361
|
-
background: rgba(0,0,0,0.05);
|
|
362
|
-
border-radius: 8px;
|
|
363
|
-
font-size: 12px;
|
|
364
|
-
color: inherit;
|
|
365
|
-
text-decoration: none;
|
|
366
|
-
}
|
|
367
|
-
.attachment:hover { background: rgba(0,0,0,0.08); }
|
|
368
|
-
.status-tick {
|
|
369
|
-
font-size: 10px;
|
|
370
|
-
margin-left: 4px;
|
|
371
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
372
|
-
}
|
|
373
|
-
.status-tick.read { color: var(--aikaara-primary, #6366f1); }
|
|
374
|
-
aikaara-template-renderer { display: block; margin-top: 6px; }
|
|
375
|
-
.bubble {
|
|
376
|
-
max-width: 85%;
|
|
377
|
-
padding: 10px 14px;
|
|
378
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
379
|
-
font-size: 14px;
|
|
380
|
-
line-height: 1.5;
|
|
381
|
-
word-wrap: break-word;
|
|
382
|
-
overflow-wrap: break-word;
|
|
383
|
-
}
|
|
384
|
-
.bubble.user {
|
|
385
|
-
background: var(--aikaara-user-bubble-bg, var(--aikaara-primary, #6366f1));
|
|
386
|
-
color: var(--aikaara-user-bubble-text, var(--aikaara-primary-contrast, #ffffff));
|
|
387
|
-
border-bottom-right-radius: 4px;
|
|
388
|
-
}
|
|
389
|
-
/* Attachment-only user message: strip the colored bubble so the
|
|
390
|
-
file-tile stands on its own. The tile component carries its own
|
|
391
|
-
background, padding, hover state, and click-to-preview affordance. */
|
|
392
|
-
.bubble.user.attachment-only {
|
|
393
|
-
background: transparent;
|
|
394
|
-
padding: 0;
|
|
395
|
-
border-radius: 0;
|
|
396
|
-
}
|
|
397
|
-
.bubble.attachment-only .attachments { margin-top: 0; }
|
|
398
|
-
.bubble.assistant, .bubble.agent {
|
|
399
|
-
background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
|
|
400
|
-
color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
|
|
401
|
-
border-bottom-left-radius: 4px;
|
|
402
|
-
}
|
|
403
|
-
/* Tenant-style: template chips render below bubble as a sibling
|
|
404
|
-
(templateLayout='outside'). Full content width, no clamp. */
|
|
405
|
-
aikaara-template-renderer.template-outside {
|
|
406
|
-
align-self: stretch;
|
|
407
|
-
width: 100%;
|
|
408
|
-
margin-top: 8px;
|
|
409
|
-
background: transparent;
|
|
410
|
-
}
|
|
411
|
-
.bubble pre {
|
|
412
|
-
background: rgba(0,0,0,0.06);
|
|
413
|
-
padding: 8px 12px;
|
|
414
|
-
border-radius: 6px;
|
|
415
|
-
overflow-x: auto;
|
|
416
|
-
font-size: 13px;
|
|
417
|
-
margin: 8px 0;
|
|
418
|
-
}
|
|
419
|
-
.bubble code {
|
|
420
|
-
font-family: 'SF Mono', 'Fira Code', monospace;
|
|
421
|
-
font-size: 13px;
|
|
422
|
-
}
|
|
423
|
-
.bubble.assistant code:not(pre code) {
|
|
424
|
-
background: rgba(0,0,0,0.06);
|
|
425
|
-
padding: 2px 4px;
|
|
426
|
-
border-radius: 3px;
|
|
427
|
-
}
|
|
428
|
-
.bubble a { color: inherit; text-decoration: underline; }
|
|
429
|
-
.timestamp {
|
|
430
|
-
font-size: 11px;
|
|
431
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
432
|
-
margin-top: 2px;
|
|
433
|
-
padding: 0 4px;
|
|
434
|
-
}
|
|
435
|
-
.welcome {
|
|
436
|
-
text-align: center;
|
|
437
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
438
|
-
font-size: 14px;
|
|
439
|
-
padding: 24px 16px;
|
|
440
|
-
}
|
|
441
|
-
.streaming-cursor::after {
|
|
442
|
-
content: '\\25CF';
|
|
443
|
-
animation: blink 1s infinite;
|
|
444
|
-
margin-left: 2px;
|
|
445
|
-
font-size: 10px;
|
|
446
|
-
vertical-align: middle;
|
|
447
|
-
}
|
|
448
|
-
@keyframes blink {
|
|
449
|
-
0%, 100% { opacity: 1; }
|
|
450
|
-
50% { opacity: 0; }
|
|
451
|
-
}
|
|
452
|
-
.typing-indicator {
|
|
453
|
-
display: flex;
|
|
454
|
-
align-items: center;
|
|
455
|
-
gap: 4px;
|
|
456
|
-
padding: 10px 14px;
|
|
457
|
-
align-self: flex-start;
|
|
458
|
-
background: transparent;
|
|
459
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
460
|
-
border-bottom-left-radius: 4px;
|
|
461
|
-
}
|
|
462
|
-
.typing-indicator .dot {
|
|
463
|
-
width: 6px;
|
|
464
|
-
height: 6px;
|
|
465
|
-
border-radius: 50%;
|
|
466
|
-
background: var(--aikaara-text-secondary, #6b7280);
|
|
467
|
-
animation: typing-bounce 1.4s infinite ease-in-out;
|
|
468
|
-
}
|
|
469
|
-
.typing-indicator .dot:nth-child(1) { animation-delay: 0ms; }
|
|
470
|
-
.typing-indicator .dot:nth-child(2) { animation-delay: 200ms; }
|
|
471
|
-
.typing-indicator .dot:nth-child(3) { animation-delay: 400ms; }
|
|
472
|
-
@keyframes typing-bounce {
|
|
473
|
-
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
|
|
474
|
-
30% { transform: translateY(-4px); opacity: 1; }
|
|
475
|
-
}
|
|
476
|
-
</style>
|
|
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">${Gt(Kt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e){const i=r.externalId??r.id;this.appendMessageElement(r,t.get(i))}this.scrollToBottom()}computeConsumedIds(e){const t=new Map;let r=-1;for(let i=e.length-1;i>=0;i--)if(e[i].role==="user"){r=i;break}for(let i=0;i<e.length;i++){const n=e[i];if(n.role==="user"){const s=n.metadata?.attributes?.action;if(s){const a=Of(s);if(s.message_id&&t.set(s.message_id,a),Object.keys(a).length>0)for(let l=i-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&&i<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=Gt(Kt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e))return;if(e.role==="system"){if(!e.content||!e.content.trim())return;const d=document.createElement("div");d.classList.add("message-wrap","system"),d.dataset.messageId=e.id,e.externalId&&(d.dataset.externalId=e.externalId);const p=document.createElement("aikaara-system-pill");p.setAttribute("text",e.content),d.appendChild(p),this.container.appendChild(d);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const i=document.createElement("div");i.classList.add("bubble",e.role);const s=!!e.template?.contentType&&e.role!=="user";e.role==="user"?!!e.attachments?.length&&!e.content?.trim()?i.classList.add("attachment-only"):i.textContent=e.content:s?e.content&&(i.innerHTML=Gt(Kt(e.content))):(i.innerHTML=Gt(Kt(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor"));let a=null;if(e.template?.contentType){const d=document.createElement("aikaara-template-renderer");d.setAttribute("content-type",e.template.contentType),e.template.templateId&&d.setAttribute("template-id",e.template.templateId);const p=e.externalId??e.id;p&&d.setAttribute("message-id",p),d.setPayload(e.template.payload),t!==void 0&&(d.dataset.consumed="true",Object.keys(t).length>0&&d.setConsumedValues?.(t)),this.templateLayout==="outside"?(d.classList.add("template-outside"),a=d):i.appendChild(d)}const l=e.template?.templateId==="7";if(e.attachments?.length&&!l){const d=document.createElement("div");d.classList.add("attachments");for(const p of e.attachments){const g=document.createElement("aikaara-template-renderer");g.setAttribute("content-type","300"),g.setAttribute("template-id","7");const h={elements:[{description:p.fileName,action:{url:p.fileUrl,type:"link",isDeepLink:!0}}]};g.setPayload(h,""),d.appendChild(g)}i.appendChild(d)}const u=!(i.childNodes.length===0&&(i.textContent??"").trim().length===0)||e.status==="streaming";if(u&&r.appendChild(i),a&&r.appendChild(a),(u||a)&&this.showTimestamps&&(e.createdAt||e.role==="user"&&e.status)){const d=document.createElement("div");if(d.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(d.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const p=document.createElement("span");p.classList.add("status-tick"),e.status==="read"&&p.classList.add("read"),p.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",d.appendChild(p)}r.appendChild(d)}r.childNodes.length>0&&this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){const e=()=>{this.scrollTop=this.scrollHeight,this.container.scrollTop=this.container.scrollHeight};requestAnimationFrame(()=>{e(),requestAnimationFrame(e)}),setTimeout(e,150)}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return Pf(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=>oa(e,g.match)),i=r?.target??"iframe";if(i==="tab"){window.open(e,"_blank","noopener,noreferrer");return}if(i==="popup"){pc(e);return}const n=this.getOrCreateModal(),s=r?.title??t??"Link";if(i==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,s));return}const a=Lf(e),l=gc(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(vo(r.fetch.body,a)));let p=null;try{const g=await fetch(l,d);g.ok&&(p=await g.json().catch(()=>null))}catch(g){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",g)}requestAnimationFrame(()=>{n.showElement?.(r.render,s,g=>{const h=r.props??{setData:p};for(const[y,w]of Object.entries(h)){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 Of(o){const e=new Set(["message_id","formAction","requestType"]),t={};for(const[r,i]of Object.entries(o))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}function oa(o,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(o)}function Lf(o){try{const e=new URL(o),t={};return e.searchParams.forEach((r,i)=>{t[i]=r}),t}catch{return{}}}function gc(o,e){return o.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function vo(o,e){if(typeof o=="string")return gc(o,e);if(Array.isArray(o))return o.map(t=>vo(t,e));if(o&&typeof o=="object"){const t={};for(const[r,i]of Object.entries(o))t[r]=vo(i,e);return t}return o}class bc 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")||"",i=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||"":Gt(Kt(t)),c=e==="user"&&i,u=i==="sending"?"○":i==="sent"?"✓":i==="delivered"||i==="read"?"✓✓":"";this.shadow.innerHTML=`
|
|
479
|
-
<style>
|
|
480
|
-
:host { display: flex; flex-direction: column; }
|
|
481
|
-
:host([role="user"]) { align-items: flex-end; }
|
|
482
|
-
:host([role="assistant"]),
|
|
483
|
-
:host([role="agent"]),
|
|
484
|
-
:host([role="system"]) { align-items: flex-start; }
|
|
485
|
-
.bubble {
|
|
486
|
-
max-width: 85%;
|
|
487
|
-
padding: 10px 14px;
|
|
488
|
-
border-radius: var(--aikaara-bubble-radius, var(--aikaara-radius, 12px));
|
|
489
|
-
font-size: 14px;
|
|
490
|
-
line-height: 1.5;
|
|
491
|
-
word-wrap: break-word;
|
|
492
|
-
}
|
|
493
|
-
.bubble.user {
|
|
494
|
-
background: var(--aikaara-user-bubble-bg, var(--aikaara-primary, #6366f1));
|
|
495
|
-
color: var(--aikaara-user-bubble-text, var(--aikaara-primary-contrast, #fff));
|
|
496
|
-
border-bottom-right-radius: 4px;
|
|
497
|
-
}
|
|
498
|
-
.bubble.assistant, .bubble.agent {
|
|
499
|
-
background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
|
|
500
|
-
color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
|
|
501
|
-
border-bottom-left-radius: 4px;
|
|
502
|
-
}
|
|
503
|
-
.bubble.system {
|
|
504
|
-
background: transparent;
|
|
505
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
506
|
-
font-size: 12px;
|
|
507
|
-
font-style: italic;
|
|
508
|
-
}
|
|
509
|
-
.timestamp {
|
|
510
|
-
font-size: 11px;
|
|
511
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
512
|
-
margin-top: 2px;
|
|
513
|
-
padding: 0 4px;
|
|
514
|
-
}
|
|
515
|
-
.status {
|
|
516
|
-
font-size: 10px;
|
|
517
|
-
color: ${i==="read"?"var(--aikaara-primary, #6366f1)":"var(--aikaara-text-secondary, #6b7280)"};
|
|
518
|
-
margin-left: 4px;
|
|
519
|
-
}
|
|
520
|
-
.attachments {
|
|
521
|
-
display: flex;
|
|
522
|
-
flex-direction: column;
|
|
523
|
-
gap: 6px;
|
|
524
|
-
margin-top: 8px;
|
|
525
|
-
}
|
|
526
|
-
.attachment {
|
|
527
|
-
display: inline-flex;
|
|
528
|
-
align-items: center;
|
|
529
|
-
gap: 6px;
|
|
530
|
-
padding: 6px 10px;
|
|
531
|
-
background: rgba(0,0,0,0.05);
|
|
532
|
-
border-radius: 8px;
|
|
533
|
-
font-size: 12px;
|
|
534
|
-
color: inherit;
|
|
535
|
-
text-decoration: none;
|
|
536
|
-
max-width: 100%;
|
|
537
|
-
}
|
|
538
|
-
.attachment:hover { background: rgba(0,0,0,0.08); }
|
|
539
|
-
aikaara-template-renderer { display: block; margin-top: 6px; }
|
|
540
|
-
</style>
|
|
541
|
-
<div class="bubble ${e}">
|
|
542
|
-
<div class="content">${l}</div>
|
|
543
|
-
${n?`<aikaara-template-renderer
|
|
544
|
-
content-type="${n}"
|
|
545
|
-
template-id="${s}"
|
|
546
|
-
inner-message="${sa(a)}"
|
|
547
|
-
></aikaara-template-renderer>`:""}
|
|
548
|
-
${this.renderAttachments()}
|
|
549
|
-
</div>
|
|
550
|
-
${r||c?`
|
|
551
|
-
<div class="timestamp">
|
|
552
|
-
${r}${c?`<span class="status">${u}</span>`:""}
|
|
553
|
-
</div>
|
|
554
|
-
`:""}
|
|
555
|
-
`;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,a),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${sa(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
|
|
556
|
-
📎 ${Mf(t.fileName)}
|
|
557
|
-
</a>`).join("")}</div>`:""}}function sa(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Mf(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class yc 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")??"",i=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",s=this.getAttribute("send-shape")==="square",a=t?`
|
|
558
|
-
<button class="attach-btn" aria-label="Attach file" type="button">
|
|
559
|
-
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
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
|
-
</svg>
|
|
562
|
-
</button>
|
|
563
|
-
<input type="file" ${r?`accept="${r}"`:""} ${i?"multiple":""} />`:"",l=`
|
|
564
|
-
<button class="send-btn" aria-label="Send message" type="button" disabled>
|
|
565
|
-
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
566
|
-
<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
|
|
567
|
-
</svg>
|
|
568
|
-
</button>`,c=s?"border-radius: var(--aikaara-button-radius, 8px);":"border-radius: 50%;";this.shadow.innerHTML=`
|
|
569
|
-
<style>
|
|
570
|
-
.input-container {
|
|
571
|
-
display: flex;
|
|
572
|
-
align-items: flex-end;
|
|
573
|
-
gap: 8px;
|
|
574
|
-
padding: 12px 16px;
|
|
575
|
-
border-top: 1px solid var(--aikaara-border, #e5e7eb);
|
|
576
|
-
background: var(--aikaara-bg, #ffffff);
|
|
577
|
-
}
|
|
578
|
-
textarea {
|
|
579
|
-
flex: 1;
|
|
580
|
-
resize: none;
|
|
581
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
582
|
-
border-radius: 8px;
|
|
583
|
-
padding: 10px 12px;
|
|
584
|
-
font-family: var(--aikaara-font, system-ui, sans-serif);
|
|
585
|
-
font-size: 14px;
|
|
586
|
-
color: var(--aikaara-text, #1f2937);
|
|
587
|
-
background: var(--aikaara-bg, #ffffff);
|
|
588
|
-
outline: none;
|
|
589
|
-
min-height: 40px;
|
|
590
|
-
max-height: 120px;
|
|
591
|
-
line-height: 1.4;
|
|
592
|
-
transition: border-color 200ms ease;
|
|
593
|
-
}
|
|
594
|
-
textarea:focus { border-color: var(--aikaara-primary, #6366f1); }
|
|
595
|
-
textarea::placeholder { color: var(--aikaara-text-secondary, #6b7280); }
|
|
596
|
-
button {
|
|
597
|
-
width: 40px;
|
|
598
|
-
height: 40px;
|
|
599
|
-
border: none;
|
|
600
|
-
cursor: pointer;
|
|
601
|
-
display: flex;
|
|
602
|
-
align-items: center;
|
|
603
|
-
justify-content: center;
|
|
604
|
-
flex-shrink: 0;
|
|
605
|
-
transition: background 200ms, opacity 200ms, color 200ms;
|
|
606
|
-
font-family: inherit;
|
|
607
|
-
}
|
|
608
|
-
.attach-btn {
|
|
609
|
-
background: transparent;
|
|
610
|
-
color: var(--aikaara-text-secondary, #6b7280);
|
|
611
|
-
border-radius: 50%;
|
|
612
|
-
}
|
|
613
|
-
.attach-btn:hover {
|
|
614
|
-
background: rgba(0,0,0,0.05);
|
|
615
|
-
color: var(--aikaara-primary, #6366f1);
|
|
616
|
-
}
|
|
617
|
-
.attach-btn[data-uploading="true"] svg { animation: spin 1s linear infinite; }
|
|
618
|
-
.send-btn {
|
|
619
|
-
background: var(--aikaara-primary, #6366f1);
|
|
620
|
-
color: #ffffff;
|
|
621
|
-
${c}
|
|
622
|
-
}
|
|
623
|
-
.send-btn:hover { background: var(--aikaara-primary-hover, #4f46e5); }
|
|
624
|
-
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
625
|
-
button svg { width: 18px; height: 18px; }
|
|
626
|
-
input[type="file"] { display: none; }
|
|
627
|
-
@keyframes spin { to { transform: rotate(360deg); } }
|
|
628
|
-
</style>
|
|
629
|
-
<div class="input-container">
|
|
630
|
-
${n?"":a}
|
|
631
|
-
<textarea rows="1" placeholder="${e}"></textarea>
|
|
632
|
-
${n?a:""}
|
|
633
|
-
${l}
|
|
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 vc extends HTMLElement{shadow;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
636
|
-
<style>
|
|
637
|
-
:host { display: none; }
|
|
638
|
-
:host([visible]) { display: block; }
|
|
639
|
-
.typing {
|
|
640
|
-
display: flex;
|
|
641
|
-
align-items: center;
|
|
642
|
-
gap: 4px;
|
|
643
|
-
padding: 10px 14px;
|
|
644
|
-
background: var(--aikaara-bg-secondary, #f9fafb);
|
|
645
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
646
|
-
border-bottom-left-radius: 4px;
|
|
647
|
-
width: fit-content;
|
|
648
|
-
}
|
|
649
|
-
.dot {
|
|
650
|
-
width: 6px;
|
|
651
|
-
height: 6px;
|
|
652
|
-
border-radius: 50%;
|
|
653
|
-
background: var(--aikaara-text-secondary, #6b7280);
|
|
654
|
-
animation: bounce 1.4s infinite ease-in-out;
|
|
655
|
-
}
|
|
656
|
-
.dot:nth-child(1) { animation-delay: 0ms; }
|
|
657
|
-
.dot:nth-child(2) { animation-delay: 200ms; }
|
|
658
|
-
.dot:nth-child(3) { animation-delay: 400ms; }
|
|
659
|
-
@keyframes bounce {
|
|
660
|
-
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
|
|
661
|
-
30% { transform: translateY(-4px); opacity: 1; }
|
|
662
|
-
}
|
|
663
|
-
</style>
|
|
664
|
-
<div class="typing">
|
|
665
|
-
<span class="dot"></span>
|
|
666
|
-
<span class="dot"></span>
|
|
667
|
-
<span class="dot"></span>
|
|
668
|
-
</div>
|
|
669
|
-
`}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class wc extends HTMLElement{shadow;bubble;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
670
|
-
<style>
|
|
671
|
-
:host {
|
|
672
|
-
display: flex;
|
|
673
|
-
flex-direction: column;
|
|
674
|
-
align-items: flex-start;
|
|
675
|
-
}
|
|
676
|
-
.bubble {
|
|
677
|
-
max-width: 85%;
|
|
678
|
-
padding: 10px 14px;
|
|
679
|
-
border-radius: var(--aikaara-bubble-radius, var(--aikaara-radius, 12px));
|
|
680
|
-
border-bottom-left-radius: 4px;
|
|
681
|
-
background: var(--aikaara-bot-bubble-bg, var(--aikaara-bg-secondary, #f9fafb));
|
|
682
|
-
color: var(--aikaara-bot-bubble-text, var(--aikaara-text, #1f2937));
|
|
683
|
-
font-size: 14px;
|
|
684
|
-
line-height: 1.5;
|
|
685
|
-
word-wrap: break-word;
|
|
686
|
-
min-height: 20px;
|
|
687
|
-
}
|
|
688
|
-
.bubble pre {
|
|
689
|
-
background: rgba(0,0,0,0.06);
|
|
690
|
-
padding: 8px 12px;
|
|
691
|
-
border-radius: 6px;
|
|
692
|
-
overflow-x: auto;
|
|
693
|
-
font-size: 13px;
|
|
694
|
-
margin: 8px 0;
|
|
695
|
-
}
|
|
696
|
-
.bubble code {
|
|
697
|
-
font-family: 'SF Mono', 'Fira Code', monospace;
|
|
698
|
-
font-size: 13px;
|
|
699
|
-
}
|
|
700
|
-
.bubble code:not(pre code) {
|
|
701
|
-
background: rgba(0,0,0,0.06);
|
|
702
|
-
padding: 2px 4px;
|
|
703
|
-
border-radius: 3px;
|
|
704
|
-
}
|
|
705
|
-
.cursor::after {
|
|
706
|
-
content: '\\25CF';
|
|
707
|
-
animation: blink 1s infinite;
|
|
708
|
-
margin-left: 2px;
|
|
709
|
-
font-size: 10px;
|
|
710
|
-
vertical-align: middle;
|
|
711
|
-
}
|
|
712
|
-
@keyframes blink {
|
|
713
|
-
0%, 100% { opacity: 1; }
|
|
714
|
-
50% { opacity: 0; }
|
|
715
|
-
}
|
|
716
|
-
</style>
|
|
717
|
-
<div class="bubble cursor"></div>
|
|
718
|
-
`,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=Gt(Kt(e)),this.bubble.classList.add("cursor"))}finalize(){this.bubble?.classList.remove("cursor")}}class kc extends HTMLElement{shadow;container;dismissTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
|
|
719
|
-
<style>
|
|
720
|
-
.banner {
|
|
721
|
-
display: none;
|
|
722
|
-
padding: 8px 16px;
|
|
723
|
-
background: #fef2f2;
|
|
724
|
-
color: #dc2626;
|
|
725
|
-
font-size: 13px;
|
|
726
|
-
text-align: center;
|
|
727
|
-
border-top: 1px solid #fecaca;
|
|
728
|
-
}
|
|
729
|
-
.banner.visible {
|
|
730
|
-
display: block;
|
|
731
|
-
}
|
|
732
|
-
.dismiss {
|
|
733
|
-
background: none;
|
|
734
|
-
border: none;
|
|
735
|
-
color: #dc2626;
|
|
736
|
-
cursor: pointer;
|
|
737
|
-
font-size: 12px;
|
|
738
|
-
text-decoration: underline;
|
|
739
|
-
margin-left: 8px;
|
|
740
|
-
}
|
|
741
|
-
</style>
|
|
742
|
-
<div class="banner">
|
|
743
|
-
<span class="message"></span>
|
|
744
|
-
<button class="dismiss">Dismiss</button>
|
|
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 gn=new Map;function xc(o){const e=gn.get(o);if(e)return e;const t=new Promise((r,i)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(o)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>i(new Error(`Failed to load ${o}`)),{once:!0}));return}const s=document.createElement("script");s.src=o,s.async=!0,s.crossOrigin="anonymous",s.dataset.aikaaraSrc=o,s.addEventListener("load",()=>{s.dataset.aikaaraReady="1",r()},{once:!0}),s.addEventListener("error",()=>{gn.delete(o),i(new Error(`Failed to load ${o}`))},{once:!0}),document.head.appendChild(s)});return gn.set(o,t),t}function Nf(o,e=5e3){return new Promise((t,r)=>{const i=setTimeout(()=>r(new Error(`Custom element <${o}> not registered within ${e}ms`)),e);customElements.whenDefined(o).then(()=>{clearTimeout(i),t()})})}const Rf={"aikaara-template-payment-link":()=>Promise.resolve().then(()=>require("./AikaaraPaymentLink-mK1C7vwW.cjs")).then(({registerAikaaraPaymentLink:o})=>o())},jf={"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 Df(o){const e=`template:${o}`,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?.[o]}class _c 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;if(t?.text&&cc(t.text))return;const r=this.getAttribute("message-id");if(r&&t?.attributes?.action){const i=Bf(t.attributes.action);if(Object.keys(i).length>0)try{localStorage.setItem(`aikaara_form:${r}`,JSON.stringify(i))}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 i=localStorage.getItem(`aikaara_form:${r}`);i&&(e=JSON.parse(i))}catch{}}if(e){const r=e;this.querySelectorAll("aikaara-option-list").forEach(i=>{const n=i,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
|
-
<style>
|
|
748
|
-
:host { display: block; }
|
|
749
|
-
::slotted(*) { display: block; }
|
|
750
|
-
/* Consumed forms: hide the submit button, lock option lists to display-only. */
|
|
751
|
-
:host([data-consumed]) ::slotted(aikaara-submit-action) { display: none; }
|
|
752
|
-
:host([data-consumed]) ::slotted(aikaara-modal-action) { display: none; }
|
|
753
|
-
:host([data-consumed]) ::slotted(aikaara-link-button) { display: none; }
|
|
754
|
-
:host([data-consumed]) ::slotted(aikaara-option-list) {
|
|
755
|
-
pointer-events: none;
|
|
756
|
-
opacity: 0.65;
|
|
757
|
-
}
|
|
758
|
-
</style>
|
|
759
|
-
<slot></slot>
|
|
760
|
-
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Df(t):void 0,i=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Rf[i];if(n&&!customElements.get(i)?n().then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] native template ${i} failed to load`,s)):r?.scriptUrl&&!customElements.get(i)&&xc(r.scriptUrl).then(()=>Nf(i)).then(()=>this.render()).catch(s=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,s)),customElements.get(i)){const s=document.createElement(i);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 <${i}>`,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?jf[t.replace(/_/g,"-").toLowerCase()]:void 0;if(r){this.mountScheduleWidget(r,e);return}const i=e.data;if(i){if(t==="text"){const n=document.createElement("aikaara-text-input");n.setPayload(i),this.appendChild(n);return}if(t==="checkbox"||t==="radio"||t==="button"){const n=document.createElement("aikaara-option-list");n.setPayload({name:i.name??"",title:i.title,options:i.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:i.name??"Submit",action:i.action??{message:i.name??"Submit"},messageId:s}),this.appendChild(n);return}t==="modal"&&this.mountModal({message:i.message??"",okLabel:i.okLabel,cancelLabel:i.cancelLabel,action:i.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-DbppaZG0.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:i})=>{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:Uf(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 $f=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Uf(o){const e={};for(const[t,r]of Object.entries(o))$f.has(t)||(e[t]=r);return e}function Bf(o){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,i]of Object.entries(o))e.has(r)||(Array.isArray(i)&&i.every(n=>typeof n=="string")?t[r]=i:typeof i=="string"&&(t[r]=[i]));return t}class Sc 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
|
-
<style>
|
|
762
|
-
:host {
|
|
763
|
-
display: flex;
|
|
764
|
-
flex-direction: column;
|
|
765
|
-
align-items: center;
|
|
766
|
-
gap: 2px;
|
|
767
|
-
padding: 6px 0;
|
|
768
|
-
}
|
|
769
|
-
.pill {
|
|
770
|
-
display: inline-block;
|
|
771
|
-
background: var(--aikaara-system-pill-bg, rgba(0,0,0,0.06));
|
|
772
|
-
color: var(--aikaara-system-pill-color, var(--aikaara-text-secondary, #6b7280));
|
|
773
|
-
padding: var(--aikaara-system-pill-padding, 6px 14px);
|
|
774
|
-
border-radius: var(--aikaara-system-pill-radius, 9999px);
|
|
775
|
-
font-size: var(--aikaara-system-pill-font-size, 12px);
|
|
776
|
-
font-weight: var(--aikaara-system-pill-font-weight, 500);
|
|
777
|
-
border: var(--aikaara-system-pill-border, none);
|
|
778
|
-
line-height: 1.3;
|
|
779
|
-
}
|
|
780
|
-
.sub {
|
|
781
|
-
font-size: 11px;
|
|
782
|
-
color: var(--aikaara-text-secondary, #9ca3af);
|
|
783
|
-
}
|
|
784
|
-
</style>
|
|
785
|
-
<span class="pill">${aa(e)}</span>
|
|
786
|
-
${t?`<span class="sub">${aa(t)}</span>`:""}
|
|
787
|
-
`}}function aa(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Ec 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,i=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
|
-
<style>
|
|
789
|
-
:host { display: block; margin: 8px 0; }
|
|
790
|
-
.row {
|
|
791
|
-
display: flex; align-items: flex-start; gap: 10px;
|
|
792
|
-
${l}
|
|
793
|
-
font-family: inherit;
|
|
794
|
-
color: var(--aikaara-text, #1f2937);
|
|
795
|
-
font-size: var(--aikaara-option-title-font-size, 14px);
|
|
796
|
-
line-height: 1.5;
|
|
797
|
-
}
|
|
798
|
-
.row:focus-visible { outline: 2px solid var(--aikaara-primary, #6366f1); outline-offset: 2px; border-radius: 4px; }
|
|
799
|
-
.box {
|
|
800
|
-
flex-shrink: 0;
|
|
801
|
-
width: 18px; height: 18px;
|
|
802
|
-
border: 1.5px solid var(--aikaara-primary, #6366f1);
|
|
803
|
-
border-radius: 4px;
|
|
804
|
-
margin-top: 3px;
|
|
805
|
-
background: var(--aikaara-option-bg, transparent);
|
|
806
|
-
display: grid; place-items: center;
|
|
807
|
-
transition: background 120ms, border-color 120ms;
|
|
808
|
-
}
|
|
809
|
-
.row[aria-checked="true"] .box {
|
|
810
|
-
background: var(--aikaara-primary, #6366f1);
|
|
811
|
-
border-color: var(--aikaara-primary, #6366f1);
|
|
812
|
-
}
|
|
813
|
-
.check {
|
|
814
|
-
width: 11px; height: 11px;
|
|
815
|
-
stroke: #fff;
|
|
816
|
-
opacity: 0;
|
|
817
|
-
transition: opacity 120ms;
|
|
818
|
-
}
|
|
819
|
-
.row[aria-checked="true"] .check { opacity: 1; }
|
|
820
|
-
.text { flex: 1; }
|
|
821
|
-
</style>
|
|
822
|
-
<div class="row" role="checkbox" tabindex="${this.preSelectedDisabled?"-1":"0"}" aria-checked="${a}" aria-disabled="${this.preSelectedDisabled}" data-value="${bn(s.value)}">
|
|
823
|
-
<span class="box" aria-hidden="true">
|
|
824
|
-
<svg class="check" viewBox="0 0 16 16" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
825
|
-
<path d="M3 8 L7 12 L13 4" />
|
|
826
|
-
</svg>
|
|
827
|
-
</span>
|
|
828
|
-
<span class="text">${Nt(e)}</span>
|
|
829
|
-
</div>
|
|
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
|
-
<style>
|
|
832
|
-
:host { display: block; margin: 8px 0; }
|
|
833
|
-
.title {
|
|
834
|
-
color: var(--aikaara-option-title-color, var(--aikaara-text, #111827));
|
|
835
|
-
font-size: var(--aikaara-option-title-font-size, 14px);
|
|
836
|
-
font-weight: var(--aikaara-option-title-font-weight, 600);
|
|
837
|
-
margin-bottom: 8px;
|
|
838
|
-
}
|
|
839
|
-
.list { display: flex; flex-direction: column; gap: 10px; }
|
|
840
|
-
.row {
|
|
841
|
-
display: flex; align-items: center; gap: 10px;
|
|
842
|
-
cursor: ${s};
|
|
843
|
-
font-family: inherit;
|
|
844
|
-
font-size: 14px;
|
|
845
|
-
color: var(--aikaara-option-color, var(--aikaara-text, #1f2937));
|
|
846
|
-
line-height: 1.4;
|
|
847
|
-
padding: 2px 0;
|
|
848
|
-
}
|
|
849
|
-
.row:focus-visible { outline: 2px solid var(--aikaara-primary, #6366f1); outline-offset: 2px; border-radius: 4px; }
|
|
850
|
-
.circle {
|
|
851
|
-
flex-shrink: 0;
|
|
852
|
-
width: 18px; height: 18px;
|
|
853
|
-
border-radius: 50%;
|
|
854
|
-
border: 2px solid var(--aikaara-primary, #6366f1);
|
|
855
|
-
background: transparent;
|
|
856
|
-
display: grid; place-items: center;
|
|
857
|
-
transition: border-color 120ms;
|
|
858
|
-
}
|
|
859
|
-
.dot {
|
|
860
|
-
width: 9px; height: 9px;
|
|
861
|
-
border-radius: 50%;
|
|
862
|
-
background: var(--aikaara-primary, #6366f1);
|
|
863
|
-
opacity: 0;
|
|
864
|
-
transform: scale(0.4);
|
|
865
|
-
transition: opacity 120ms, transform 120ms;
|
|
866
|
-
}
|
|
867
|
-
.row[aria-checked="true"] .dot { opacity: 1; transform: scale(1); }
|
|
868
|
-
.label { flex: 1; }
|
|
869
|
-
</style>
|
|
870
|
-
${e?`<div class="title">${Nt(e)}</div>`:""}
|
|
871
|
-
<div class="list" role="radiogroup" aria-label="${Nt(e??this.data.name)}">
|
|
872
|
-
${t.map(a=>{const l=this.selected.has(a.value);return`
|
|
873
|
-
<div class="row" role="radio" tabindex="${this.preSelectedDisabled?"-1":"0"}"
|
|
874
|
-
aria-checked="${l}" aria-disabled="${this.preSelectedDisabled}"
|
|
875
|
-
data-value="${bn(a.value)}">
|
|
876
|
-
<span class="circle" aria-hidden="true"><span class="dot"></span></span>
|
|
877
|
-
<span class="label">${Nt(a.label)}</span>
|
|
878
|
-
</div>`}).join("")}
|
|
879
|
-
</div>
|
|
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=`
|
|
881
|
-
<style>
|
|
882
|
-
:host { display: block; margin: 8px 0; }
|
|
883
|
-
.title {
|
|
884
|
-
color: var(--aikaara-option-title-color, var(--aikaara-text, #111827));
|
|
885
|
-
font-size: var(--aikaara-option-title-font-size, 14px);
|
|
886
|
-
font-weight: var(--aikaara-option-title-font-weight, 600);
|
|
887
|
-
margin-bottom: 8px;
|
|
888
|
-
}
|
|
889
|
-
.grid {
|
|
890
|
-
display: flex;
|
|
891
|
-
flex-wrap: wrap;
|
|
892
|
-
gap: var(--aikaara-option-gap, 8px);
|
|
893
|
-
}
|
|
894
|
-
button.opt {
|
|
895
|
-
background: var(--aikaara-option-bg, transparent);
|
|
896
|
-
color: var(--aikaara-option-color, var(--aikaara-text, #1f2937));
|
|
897
|
-
border: var(--aikaara-option-border, 1.5px solid var(--aikaara-primary, #6366f1));
|
|
898
|
-
border-radius: var(--aikaara-option-radius, 10px);
|
|
899
|
-
padding: var(--aikaara-option-padding, 10px 16px);
|
|
900
|
-
font-size: 14px;
|
|
901
|
-
font-family: inherit;
|
|
902
|
-
cursor: ${this.preSelectedDisabled?"default":"pointer"};
|
|
903
|
-
transition: background 120ms, color 120ms, border-color 120ms;
|
|
904
|
-
line-height: 1.2;
|
|
905
|
-
}
|
|
906
|
-
button.opt:hover { filter: ${this.preSelectedDisabled?"none":"brightness(0.96)"}; }
|
|
907
|
-
button.opt[aria-pressed="true"] {
|
|
908
|
-
background: var(--aikaara-option-selected-bg, var(--aikaara-primary, #6366f1));
|
|
909
|
-
color: var(--aikaara-option-selected-color, #fff);
|
|
910
|
-
border-color: var(--aikaara-option-selected-border, var(--aikaara-primary, #6366f1));
|
|
911
|
-
}
|
|
912
|
-
</style>
|
|
913
|
-
${e?`<div class="title">${Nt(e)}</div>`:""}
|
|
914
|
-
<div class="grid" role="${i?"group":"radiogroup"}" aria-label="${Nt(e??this.data.name)}">
|
|
915
|
-
${t.map(s=>`
|
|
916
|
-
<button class="opt" type="button"
|
|
917
|
-
data-value="${bn(s.value)}"
|
|
918
|
-
role="${i?"checkbox":"radio"}"
|
|
919
|
-
aria-pressed="${this.selected.has(s.value)}"
|
|
920
|
-
${this.preSelectedDisabled?'disabled aria-disabled="true"':""}>
|
|
921
|
-
${Nt(s.label)}
|
|
922
|
-
</button>`).join("")}
|
|
923
|
-
</div>
|
|
924
|
-
`,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(s=>{s.addEventListener("click",()=>this.toggle(s.dataset.value||""))})}}function Nt(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}function bn(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Ac 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(i=>{(i.validate?.()??!0)||(r=!1)}),r?(t.querySelectorAll("aikaara-option-list").forEach(i=>{const n=i.getValues?.();n?.name&&(e[n.name]=n.type==="radio"?n.values[0]??"":n.values)}),t.querySelectorAll("aikaara-text-input").forEach(i=>{const n=i.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
|
-
<style>
|
|
926
|
-
:host { display: block; margin: 12px 0 4px; }
|
|
927
|
-
button {
|
|
928
|
-
font-family: inherit;
|
|
929
|
-
background: var(--aikaara-submit-bg, var(--aikaara-primary, #6366f1));
|
|
930
|
-
color: var(--aikaara-submit-color, #ffffff);
|
|
931
|
-
border: var(--aikaara-submit-border, none);
|
|
932
|
-
border-radius: var(--aikaara-submit-radius, 10px);
|
|
933
|
-
padding: var(--aikaara-submit-padding, 12px 22px);
|
|
934
|
-
font-size: var(--aikaara-submit-font-size, 14px);
|
|
935
|
-
font-weight: var(--aikaara-submit-font-weight, 600);
|
|
936
|
-
cursor: pointer;
|
|
937
|
-
transition: background 120ms, opacity 120ms;
|
|
938
|
-
}
|
|
939
|
-
button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
|
|
940
|
-
button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
|
|
941
|
-
</style>
|
|
942
|
-
<button type="button">${Ff(e)}</button>
|
|
943
|
-
`,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Ff(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Ic 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
|
-
<style>
|
|
945
|
-
:host { all: initial; }
|
|
946
|
-
.overlay {
|
|
947
|
-
position: fixed; inset: 0;
|
|
948
|
-
background: var(--aikaara-modal-overlay-bg, rgba(15, 23, 42, 0.45));
|
|
949
|
-
display: flex; align-items: center; justify-content: center;
|
|
950
|
-
z-index: 99999;
|
|
951
|
-
font-family: var(--aikaara-font, inherit);
|
|
952
|
-
}
|
|
953
|
-
.modal {
|
|
954
|
-
background: var(--aikaara-modal-bg, #ffffff);
|
|
955
|
-
color: var(--aikaara-modal-color, #1f2937);
|
|
956
|
-
border-radius: var(--aikaara-modal-radius, 14px);
|
|
957
|
-
padding: var(--aikaara-modal-padding, 24px 28px);
|
|
958
|
-
box-shadow: var(--aikaara-modal-shadow, 0 10px 40px rgba(15, 23, 42, 0.18));
|
|
959
|
-
max-width: 360px;
|
|
960
|
-
text-align: center;
|
|
961
|
-
}
|
|
962
|
-
.msg { font-size: 14px; line-height: 1.5; margin-bottom: 18px; }
|
|
963
|
-
.actions { display: flex; gap: 10px; justify-content: center; }
|
|
964
|
-
button {
|
|
965
|
-
font-family: inherit;
|
|
966
|
-
padding: 8px 22px;
|
|
967
|
-
font-size: 13px;
|
|
968
|
-
font-weight: 500;
|
|
969
|
-
border-radius: var(--aikaara-modal-button-radius, 10px);
|
|
970
|
-
cursor: pointer;
|
|
971
|
-
border: none;
|
|
972
|
-
}
|
|
973
|
-
button.ok {
|
|
974
|
-
background: var(--aikaara-modal-button-bg, var(--aikaara-primary, #6366f1));
|
|
975
|
-
color: var(--aikaara-modal-button-color, #ffffff);
|
|
976
|
-
}
|
|
977
|
-
button.cancel {
|
|
978
|
-
background: transparent;
|
|
979
|
-
color: var(--aikaara-modal-cancel-color, var(--aikaara-text-secondary, #6b7280));
|
|
980
|
-
}
|
|
981
|
-
</style>
|
|
982
|
-
<div class="overlay" role="dialog" aria-modal="true">
|
|
983
|
-
<div class="modal">
|
|
984
|
-
<div class="msg">${yn(this.data.message)}</div>
|
|
985
|
-
<div class="actions">
|
|
986
|
-
${t?`<button class="cancel" type="button">${yn(t)}</button>`:""}
|
|
987
|
-
<button class="ok" type="button">${yn(e)}</button>
|
|
988
|
-
</div>
|
|
989
|
-
</div>
|
|
990
|
-
</div>
|
|
991
|
-
`,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function yn(o){return String(o).replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e])}class Tc 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,i=r?'<span aria-hidden="true" style="color:var(--aikaara-input-error-color,#ef4444);margin-left:2px;">*</span>':"";this.shadow.innerHTML=`
|
|
992
|
-
<style>
|
|
993
|
-
:host { display: block; margin-bottom: 12px; }
|
|
994
|
-
label {
|
|
995
|
-
display: block;
|
|
996
|
-
font-size: 13px;
|
|
997
|
-
font-weight: 500;
|
|
998
|
-
color: var(--aikaara-input-label-color, #374151);
|
|
999
|
-
margin-bottom: 5px;
|
|
1000
|
-
}
|
|
1001
|
-
input {
|
|
1002
|
-
width: 100%;
|
|
1003
|
-
box-sizing: border-box;
|
|
1004
|
-
padding: 9px 12px;
|
|
1005
|
-
border: 1.5px solid var(--aikaara-input-border, #d1d5db);
|
|
1006
|
-
border-radius: var(--aikaara-input-radius, 8px);
|
|
1007
|
-
background: var(--aikaara-input-bg, #ffffff);
|
|
1008
|
-
color: var(--aikaara-input-color, #111827);
|
|
1009
|
-
font-size: 14px;
|
|
1010
|
-
font-family: inherit;
|
|
1011
|
-
outline: none;
|
|
1012
|
-
transition: border-color 120ms;
|
|
1013
|
-
}
|
|
1014
|
-
input::placeholder { color: var(--aikaara-input-placeholder-color, #9ca3af); }
|
|
1015
|
-
input:focus { border-color: var(--aikaara-input-border-focus, var(--aikaara-primary, #6366f1)); }
|
|
1016
|
-
input[aria-invalid="true"] { border-color: var(--aikaara-input-error-color, #ef4444); }
|
|
1017
|
-
.error {
|
|
1018
|
-
margin-top: 4px;
|
|
1019
|
-
font-size: 12px;
|
|
1020
|
-
color: var(--aikaara-input-error-color, #ef4444);
|
|
1021
|
-
min-height: 16px;
|
|
1022
|
-
}
|
|
1023
|
-
:host([data-consumed]) input { pointer-events: none; opacity: 0.65; background: var(--aikaara-input-bg, #f9fafb); }
|
|
1024
|
-
</style>
|
|
1025
|
-
<label>${sr(e)}${i}</label>
|
|
1026
|
-
<input
|
|
1027
|
-
type="text"
|
|
1028
|
-
placeholder="${sr(t)}"
|
|
1029
|
-
value="${sr(this._value)}"
|
|
1030
|
-
aria-label="${sr(e)}"
|
|
1031
|
-
aria-invalid="false"
|
|
1032
|
-
/>
|
|
1033
|
-
<div class="error" role="alert">${sr(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 sr(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Cc 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"),i=this.tokenGetter??r;if(!i){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 Xc({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:i,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 Pc 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 i=!1;this.iframe.addEventListener("load",()=>{i=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{i||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const i=this.shadow.querySelector(".modal-title");i&&(i.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
|
-
<style>
|
|
1036
|
-
:host { display: block; }
|
|
1037
|
-
.backdrop {
|
|
1038
|
-
position: fixed; inset: 0; z-index: 10000;
|
|
1039
|
-
background: rgba(0,0,0,0.45);
|
|
1040
|
-
display: none; align-items: center; justify-content: center;
|
|
1041
|
-
padding: var(--aikaara-modal-padding, 24px);
|
|
1042
|
-
font-family: var(--aikaara-font, system-ui, sans-serif);
|
|
1043
|
-
}
|
|
1044
|
-
:host(.open) .backdrop, .backdrop.open { display: flex; }
|
|
1045
|
-
.modal {
|
|
1046
|
-
background: var(--aikaara-surface, #fff);
|
|
1047
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1048
|
-
width: var(--aikaara-modal-width, min(900px, 100%));
|
|
1049
|
-
height: var(--aikaara-modal-height, min(720px, 90vh));
|
|
1050
|
-
max-width: var(--aikaara-modal-max-width, 100%);
|
|
1051
|
-
max-height: var(--aikaara-modal-max-height, 90vh);
|
|
1052
|
-
display: flex; flex-direction: column;
|
|
1053
|
-
overflow: hidden;
|
|
1054
|
-
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
|
1055
|
-
}
|
|
1056
|
-
.modal-header {
|
|
1057
|
-
display: flex; align-items: center; justify-content: space-between;
|
|
1058
|
-
padding: 12px 16px;
|
|
1059
|
-
background: var(--aikaara-primary, #0f2e5c);
|
|
1060
|
-
color: var(--aikaara-primary-contrast, #fff);
|
|
1061
|
-
font-size: 14px; font-weight: 600;
|
|
1062
|
-
}
|
|
1063
|
-
.modal-title { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1064
|
-
.modal-close {
|
|
1065
|
-
background: transparent; border: none; color: inherit;
|
|
1066
|
-
font-size: 22px; line-height: 1; cursor: pointer;
|
|
1067
|
-
padding: 4px 8px; border-radius: 4px;
|
|
1068
|
-
}
|
|
1069
|
-
.modal-close:hover { background: rgba(255,255,255,0.15); }
|
|
1070
|
-
iframe {
|
|
1071
|
-
flex: 1; border: 0; width: 100%; height: 100%;
|
|
1072
|
-
}
|
|
1073
|
-
</style>
|
|
1074
|
-
<div class="backdrop" part="backdrop">
|
|
1075
|
-
<div class="modal" role="dialog" aria-modal="true">
|
|
1076
|
-
<div class="modal-header">
|
|
1077
|
-
<span class="modal-title">Link</span>
|
|
1078
|
-
<button class="modal-close" aria-label="Close" type="button">×</button>
|
|
1079
|
-
</div>
|
|
1080
|
-
<iframe sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation-by-user-activation allow-downloads" allow="downloads" referrerpolicy="no-referrer-when-downgrade" loading="lazy"></iframe>
|
|
1081
|
-
<div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
|
|
1082
|
-
</div>
|
|
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 qf=[{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"}],Hf=[{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 Oc extends HTMLElement{shadow;data=null;columns=Hf;features=qf;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
|
-
<style>
|
|
1086
|
-
:host {
|
|
1087
|
-
display: block;
|
|
1088
|
-
font-family: var(--aikaara-font, system-ui, sans-serif);
|
|
1089
|
-
color: var(--aikaara-text, #0f2e5c);
|
|
1090
|
-
}
|
|
1091
|
-
table {
|
|
1092
|
-
width: 100%;
|
|
1093
|
-
border-collapse: collapse;
|
|
1094
|
-
font-size: 14px;
|
|
1095
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1096
|
-
overflow: hidden;
|
|
1097
|
-
}
|
|
1098
|
-
thead th {
|
|
1099
|
-
background: var(--aikaara-primary, #0f2e5c);
|
|
1100
|
-
color: var(--aikaara-primary-contrast, #fff);
|
|
1101
|
-
padding: 12px 14px;
|
|
1102
|
-
text-align: left;
|
|
1103
|
-
font-weight: 600;
|
|
1104
|
-
}
|
|
1105
|
-
thead th + th { text-align: center; }
|
|
1106
|
-
tbody td {
|
|
1107
|
-
padding: 11px 14px;
|
|
1108
|
-
border-bottom: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1109
|
-
background: var(--aikaara-surface, #fff);
|
|
1110
|
-
}
|
|
1111
|
-
tbody tr:nth-child(even) td {
|
|
1112
|
-
background: var(--aikaara-surface-muted, #f6fafb);
|
|
1113
|
-
}
|
|
1114
|
-
tbody td + td { text-align: center; }
|
|
1115
|
-
.check { color: #16a34a; font-weight: 700; }
|
|
1116
|
-
.cross { color: #dc2626; font-weight: 700; }
|
|
1117
|
-
.price-row td { font-weight: 600; }
|
|
1118
|
-
.actions {
|
|
1119
|
-
display: flex; flex-direction: column; gap: 8px;
|
|
1120
|
-
margin-top: 12px;
|
|
1121
|
-
}
|
|
1122
|
-
button.action {
|
|
1123
|
-
display: flex; justify-content: space-between; align-items: center;
|
|
1124
|
-
padding: 12px 14px;
|
|
1125
|
-
background: var(--aikaara-primary, #0f2e5c);
|
|
1126
|
-
color: var(--aikaara-primary-contrast, #fff);
|
|
1127
|
-
border: none;
|
|
1128
|
-
border-radius: var(--aikaara-button-radius, 8px);
|
|
1129
|
-
font-size: 14px; font-weight: 600;
|
|
1130
|
-
cursor: pointer;
|
|
1131
|
-
width: 100%; text-align: left;
|
|
1132
|
-
}
|
|
1133
|
-
button.action:hover { background: var(--aikaara-primary-hover, #0a2347); }
|
|
1134
|
-
button.action small { font-weight: 400; opacity: 0.8; font-size: 12px; }
|
|
1135
|
-
</style>
|
|
1136
|
-
<table>
|
|
1137
|
-
<thead>
|
|
1138
|
-
<tr>
|
|
1139
|
-
<th>Feature</th>
|
|
1140
|
-
${e.map(r=>`<th>${vn(r.label)}</th>`).join("")}
|
|
1141
|
-
</tr>
|
|
1142
|
-
</thead>
|
|
1143
|
-
<tbody>
|
|
1144
|
-
${t.map((r,i)=>`
|
|
1145
|
-
<tr>
|
|
1146
|
-
<td>${vn(r.label)}</td>
|
|
1147
|
-
${e.map(n=>n.features[i]?'<td><span class="check">✓</span></td>':'<td><span class="cross">✕</span></td>').join("")}
|
|
1148
|
-
</tr>`).join("")}
|
|
1149
|
-
<tr class="price-row">
|
|
1150
|
-
<td>Price (excl. GST)</td>
|
|
1151
|
-
${e.map(r=>{const i=this.priceFor(r);return`<td>${i!=null?"₹"+Math.round(i):"—"}</td>`}).join("")}
|
|
1152
|
-
</tr>
|
|
1153
|
-
</tbody>
|
|
1154
|
-
</table>
|
|
1155
|
-
<div class="actions">
|
|
1156
|
-
${e.map((r,i)=>{const n=this.priceFor(r),s=r.selectLabel.replace("{price}",n!=null?String(Math.round(n)):"—");return`<button class="action" data-col="${i}" type="button">
|
|
1157
|
-
<span>${vn(s)}</span>
|
|
1158
|
-
<small>Tap to select</small>
|
|
1159
|
-
</button>`}).join("")}
|
|
1160
|
-
</div>
|
|
1161
|
-
`,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const i=Number(r.dataset.col),n=e[i];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function vn(o){return o.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}class Lc 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("[]"),i=r?t.slice(0,-2):t,n=this.data[i];return r?Array.isArray(n)?n:[]:n??null}handleSectionSubmit(e,t){const r=this.schemas.find(i=>i.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
|
-
<span class="header-spacer"></span>
|
|
1163
|
-
<div class="modal-title">Correct Your ITR Details</div>
|
|
1164
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${la}</button>
|
|
1165
|
-
`;const r=this.shadow.querySelector(".modal-body"),i=this.schemas.map(s=>`
|
|
1166
|
-
<button class="chip" type="button" data-section-id="${zf(s.id)}">
|
|
1167
|
-
<span class="chip-icon">${s.icon??"📄"}</span>
|
|
1168
|
-
<span class="chip-label">${ca(s.title)}</span>
|
|
1169
|
-
</button>`).join("");r.innerHTML=`
|
|
1170
|
-
<div class="picker">
|
|
1171
|
-
<div class="intro-card">
|
|
1172
|
-
<span class="intro-icon">✨</span>
|
|
1173
|
-
<div>
|
|
1174
|
-
<div class="intro-title">What would you like to correct?</div>
|
|
1175
|
-
<div class="intro-sub">Select a category to edit</div>
|
|
1176
|
-
</div>
|
|
1177
|
-
</div>
|
|
1178
|
-
<div class="chip-grid">${i}</div>
|
|
1179
|
-
</div>
|
|
1180
|
-
`;const n=this.shadow.querySelector(".modal-footer");n.style.display="",n.innerHTML=`
|
|
1181
|
-
<button class="primary-btn" type="button" data-action="recalculate">Save & Recalculate</button>
|
|
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">${Wf}</button>
|
|
1184
|
-
<div class="modal-title">${ca(t?.title??"Edit")}</div>
|
|
1185
|
-
<button class="icon-btn close-btn" type="button" aria-label="Close">${la}</button>
|
|
1186
|
-
`;const i=this.shadow.querySelector(".modal-footer");i.style.display="none",i.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(i=>i.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",(i=>{const n=i.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
|
-
<style>${this.css()}</style>
|
|
1188
|
-
<div class="backdrop" part="backdrop">
|
|
1189
|
-
<div class="modal view-picker" role="dialog" aria-modal="true" aria-label="Correct Your ITR Details">
|
|
1190
|
-
<div class="modal-header"></div>
|
|
1191
|
-
<div class="modal-body"></div>
|
|
1192
|
-
<div class="modal-footer"></div>
|
|
1193
|
-
</div>
|
|
1194
|
-
</div>
|
|
1195
|
-
`,this.root=this.shadow.querySelector(".backdrop"),this.root.addEventListener("click",e=>{e.target===this.root&&this.close()}),this.keydownHandler||(this.keydownHandler=e=>{e.key!=="Escape"||!this.root?.classList.contains("open")||(this.view==="form"?this.backToPicker():this.close())},document.addEventListener("keydown",this.keydownHandler))}css(){return`
|
|
1196
|
-
:host { display: block; }
|
|
1197
|
-
.backdrop {
|
|
1198
|
-
position: fixed; inset: 0; z-index: 10000;
|
|
1199
|
-
background: rgba(15, 23, 42, 0.55);
|
|
1200
|
-
display: none; align-items: center; justify-content: center;
|
|
1201
|
-
padding: 20px;
|
|
1202
|
-
font-family: var(--aikaara-font, system-ui, -apple-system, sans-serif);
|
|
1203
|
-
}
|
|
1204
|
-
.backdrop.open { display: flex; }
|
|
1205
|
-
.modal {
|
|
1206
|
-
background: var(--aikaara-surface, #ffffff);
|
|
1207
|
-
border-radius: var(--aikaara-radius, 16px);
|
|
1208
|
-
width: min(560px, 100%);
|
|
1209
|
-
max-height: 88vh;
|
|
1210
|
-
display: flex;
|
|
1211
|
-
flex-direction: column;
|
|
1212
|
-
overflow: hidden;
|
|
1213
|
-
box-shadow: 0 28px 80px rgba(15,23,42,0.35);
|
|
1214
|
-
color: var(--aikaara-text, #0f172a);
|
|
1215
|
-
}
|
|
1216
|
-
.modal-header {
|
|
1217
|
-
flex-shrink: 0;
|
|
1218
|
-
display: flex; align-items: center; gap: 8px;
|
|
1219
|
-
padding: 14px 14px;
|
|
1220
|
-
border-bottom: 1px solid var(--aikaara-border, #e3e8ef);
|
|
1221
|
-
}
|
|
1222
|
-
.modal-title {
|
|
1223
|
-
flex: 1;
|
|
1224
|
-
text-align: center;
|
|
1225
|
-
font-size: 15.5px;
|
|
1226
|
-
font-weight: 700;
|
|
1227
|
-
color: var(--aikaara-text-strong, #0f172a);
|
|
1228
|
-
}
|
|
1229
|
-
.header-spacer, .icon-btn { width: 32px; height: 32px; flex-shrink: 0; }
|
|
1230
|
-
.icon-btn {
|
|
1231
|
-
display: flex; align-items: center; justify-content: center;
|
|
1232
|
-
background: transparent; border: none; cursor: pointer;
|
|
1233
|
-
color: var(--aikaara-text-muted, #475569);
|
|
1234
|
-
border-radius: 8px;
|
|
1235
|
-
padding: 0;
|
|
1236
|
-
}
|
|
1237
|
-
.icon-btn:hover { background: var(--aikaara-border, #eef1f5); }
|
|
1238
|
-
.icon-btn svg { width: 18px; height: 18px; }
|
|
1239
|
-
.modal-body {
|
|
1240
|
-
flex: 1;
|
|
1241
|
-
min-height: 0;
|
|
1242
|
-
display: flex;
|
|
1243
|
-
flex-direction: column;
|
|
1244
|
-
}
|
|
1245
|
-
.modal.view-picker .modal-body { overflow-y: auto; padding: 16px 18px; }
|
|
1246
|
-
.modal.view-form .modal-body { overflow: hidden; }
|
|
1247
|
-
/* The schema form is a flex child here — it must be allowed to shrink
|
|
1248
|
-
below its content height (min-height: 0) so its own internal
|
|
1249
|
-
.scroll region can take over, instead of overflowing the modal. */
|
|
1250
|
-
.modal-body aikaara-schema-form { flex: 1 1 auto; min-height: 0; }
|
|
1251
|
-
.modal-footer {
|
|
1252
|
-
flex-shrink: 0;
|
|
1253
|
-
padding: 14px 18px;
|
|
1254
|
-
border-top: 1px solid var(--aikaara-border, #e3e8ef);
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
/* ── picker view ─────────────────────────────────────────── */
|
|
1258
|
-
.picker { display: flex; flex-direction: column; gap: 16px; }
|
|
1259
|
-
.intro-card {
|
|
1260
|
-
display: flex; align-items: flex-start; gap: 12px;
|
|
1261
|
-
padding: 14px 15px;
|
|
1262
|
-
background: var(--aikaara-section-bg, #eaf2fd);
|
|
1263
|
-
border: 1px solid var(--aikaara-section-border, #d4e4fb);
|
|
1264
|
-
border-radius: 12px;
|
|
1265
|
-
}
|
|
1266
|
-
.intro-icon { font-size: 20px; line-height: 1.2; }
|
|
1267
|
-
.intro-title {
|
|
1268
|
-
font-size: 14px; font-weight: 700;
|
|
1269
|
-
color: var(--aikaara-text-strong, #0f2f5c);
|
|
1270
|
-
}
|
|
1271
|
-
.intro-sub {
|
|
1272
|
-
font-size: 12.5px; margin-top: 2px;
|
|
1273
|
-
color: var(--aikaara-text-muted, #5b7798);
|
|
1274
|
-
}
|
|
1275
|
-
.chip-grid { display: flex; flex-wrap: wrap; gap: 9px; }
|
|
1276
|
-
.chip {
|
|
1277
|
-
display: inline-flex; align-items: center; gap: 7px;
|
|
1278
|
-
padding: 9px 13px;
|
|
1279
|
-
border: 1px solid var(--aikaara-input-border, #cbd5e1);
|
|
1280
|
-
border-radius: 999px;
|
|
1281
|
-
background: #ffffff;
|
|
1282
|
-
font: inherit; font-size: 13px; font-weight: 500;
|
|
1283
|
-
color: var(--aikaara-text, #1f2937);
|
|
1284
|
-
cursor: pointer;
|
|
1285
|
-
transition: border-color 150ms, background 150ms, box-shadow 150ms;
|
|
1286
|
-
}
|
|
1287
|
-
.chip:hover {
|
|
1288
|
-
border-color: var(--aikaara-primary, #2563eb);
|
|
1289
|
-
background: var(--aikaara-primary-soft, rgba(37,99,235,0.06));
|
|
1290
|
-
}
|
|
1291
|
-
.chip-icon { font-size: 14px; line-height: 1; }
|
|
1292
|
-
.chip-label { white-space: nowrap; }
|
|
1293
|
-
|
|
1294
|
-
/* ── footer button ──────────────────────────────────────── */
|
|
1295
|
-
.primary-btn {
|
|
1296
|
-
width: 100%;
|
|
1297
|
-
padding: 13px 18px;
|
|
1298
|
-
background: var(--aikaara-primary, #2563eb);
|
|
1299
|
-
color: #ffffff;
|
|
1300
|
-
border: none;
|
|
1301
|
-
border-radius: 10px;
|
|
1302
|
-
font: inherit; font-size: 14.5px; font-weight: 700;
|
|
1303
|
-
cursor: pointer;
|
|
1304
|
-
transition: filter 150ms;
|
|
1305
|
-
}
|
|
1306
|
-
.primary-btn:hover { filter: brightness(1.07); }
|
|
1307
|
-
.primary-btn:active { filter: brightness(0.95); }
|
|
1308
|
-
|
|
1309
|
-
.empty {
|
|
1310
|
-
padding: 40px 12px;
|
|
1311
|
-
text-align: center;
|
|
1312
|
-
color: var(--aikaara-text-muted, #64748b);
|
|
1313
|
-
font-size: 14px;
|
|
1314
|
-
}
|
|
1315
|
-
|
|
1316
|
-
@media (max-width: 600px) {
|
|
1317
|
-
.backdrop { padding: 0; align-items: flex-end; }
|
|
1318
|
-
.modal {
|
|
1319
|
-
width: 100%;
|
|
1320
|
-
max-height: 94vh;
|
|
1321
|
-
border-radius: 16px 16px 0 0;
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
`}}const la='<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>',Wf='<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 zf(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ca(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class Mc 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.renderPreservingScroll()}setEntryNoRender(e,t,r){const i=this.getEntries(),n={...i[e]||{}};n[t]=r,i[e]=n,this.isRepeatable()?this.value=i: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.renderPreservingScroll())}removeEntry(e){if(!this.isRepeatable())return;const t=this.getEntries();t.length<=1||(t.splice(e,1),this.value=t,this.renderPreservingScroll())}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)}renderPreservingScroll(){const e=this.shadow.querySelector(".scroll")?.scrollTop??0;this.render();const t=this.shadow.querySelector(".scroll");if(!t)return;const r=()=>{t.scrollHeight,t.scrollTop=e};r(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(r)}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 i=e[r.id];typeof i=="string"&&i!==i.toUpperCase()&&this.setEntryNoRender(t,r.id,i.toUpperCase())})})}validate(){return this.normalizeUppercase(),this.errors.clear(),this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],i=>{if(!this.fieldVisible(i,t)||i.type==="group")return;const n=t[i.id],s=`${r}.${i.id}`;if(i.required&&(n==null||n==="")){this.errors.set(s,"Required");return}if(i.type==="text"&&typeof n=="string"&&(i.pattern&&n&&!new RegExp(i.pattern).test(n)?this.errors.set(s,"Invalid format"):i.maxLength&&n.length>i.maxLength&&this.errors.set(s,`Max ${i.maxLength} characters`)),i.type==="textarea"&&typeof n=="string"&&i.maxLength&&n.length>i.maxLength&&this.errors.set(s,`Max ${i.maxLength} characters`),i.type==="number"&&n!==void 0&&n!==null&&n!==""){const a=typeof n=="number"?n:Number(n),l=i;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((i,n)=>this.renderEntry(i,n)).join(""),r=this.isRepeatable()&&e.length<(this.schema.repeatable?.maxCount||1);this.shadow.innerHTML=`
|
|
1325
|
-
<style>${this.css()}</style>
|
|
1326
|
-
<div class="container">
|
|
1327
|
-
<div class="scroll">
|
|
1328
|
-
<div class="section-card">
|
|
1329
|
-
<span class="section-icon">${this.schema.icon??"📝"}</span>
|
|
1330
|
-
<div class="section-meta">
|
|
1331
|
-
<div class="section-title">${Ve(this.schema.title)}</div>
|
|
1332
|
-
${this.schema.hint?`<div class="section-hint">${Ve(this.schema.hint)}</div>`:""}
|
|
1333
|
-
</div>
|
|
1334
|
-
</div>
|
|
1335
|
-
<div class="entries">${t}</div>
|
|
1336
|
-
${r?'<button class="add-btn" type="button" data-action="add-entry">+ Add another</button>':""}
|
|
1337
|
-
</div>
|
|
1338
|
-
<div class="footer">
|
|
1339
|
-
<button class="save-btn" type="button" data-action="save">
|
|
1340
|
-
${Ve(this.schema.submitLabel||"Save")}
|
|
1341
|
-
</button>
|
|
1342
|
-
</div>
|
|
1343
|
-
</div>
|
|
1344
|
-
`,this.bindHandlers()}renderEntry(e,t){const i=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">${i?`<div class="entry-header">
|
|
1345
|
-
<span class="entry-label">
|
|
1346
|
-
${this.schema?.entryIcon?`<span class="entry-icon">${this.schema.entryIcon}</span>`:""}
|
|
1347
|
-
${Ve(i)}
|
|
1348
|
-
</span>
|
|
1349
|
-
${n}
|
|
1350
|
-
</div>`:""}<div class="entry-body">${s}</div></section>`}renderField(e,t,r){if(!e.showWhen&&!e.hideWhen)return this.renderFieldInner(e,t,r);const i=this.fieldVisible(e,t);return`<div class="cond" data-cond-key="${ut(`${r}.${e.id}`)}" ${i?"":"hidden"}>${this.renderFieldInner(e,t,r)}</div>`}syncConditionalVisibility(){this.getEntries().forEach((t,r)=>{this.walkFields(this.schema?.fields||[],i=>{if(!i.showWhen&&!i.hideWhen)return;const n=this.shadow.querySelector(`.cond[data-cond-key="${CSS.escape(`${r}.${i.id}`)}"]`);n&&(n.hidden=!this.fieldVisible(i,t))})})}renderFieldInner(e,t,r){if(e.type==="group"){const d=e,p=d.fields.map(b=>this.renderField(b,t,r)).join("");if(!d.collapsible)return`
|
|
1351
|
-
<fieldset class="group">
|
|
1352
|
-
${d.title?`<legend class="group-title">${Ve(d.title)}</legend>`:""}
|
|
1353
|
-
${d.hint?`<div class="group-hint">${Ve(d.hint)}</div>`:""}
|
|
1354
|
-
<div class="group-body">${p}</div>
|
|
1355
|
-
</fieldset>`;const g=`${r}.${d.id}`;d.defaultCollapsed&&!this.collapseSeeded.has(g)&&(this.collapseSeeded.add(g),this.collapsed.add(g));const h=this.collapsed.has(g);return`
|
|
1356
|
-
<fieldset class="group group--collapsible ${h?"is-collapsed":""}">
|
|
1357
|
-
<button type="button" class="group-toggle" data-action="toggle-group" data-group-key="${ut(g)}" aria-expanded="${!h}">
|
|
1358
|
-
<span class="group-title">${Ve(d.title??"")}</span>
|
|
1359
|
-
<span class="group-chevron" aria-hidden="true"></span>
|
|
1360
|
-
</button>
|
|
1361
|
-
${d.hint&&!h?`<div class="group-hint">${Ve(d.hint)}</div>`:""}
|
|
1362
|
-
<div class="group-body" ${h?"hidden":""}>${p}</div>
|
|
1363
|
-
</fieldset>`}const i=`${r}.${e.id}`,n=this.errors.get(i),s=n?"has-error":"",a=e.required?'<span class="req">*</span>':"",l=e.label?`<label class="field-label" for="${this.fieldHtmlId(e,r)}">${Ve(e.label)} ${a}</label>`:"",c=this.renderInput(e,t,r),u=n?`<div class="field-error">${Ve(n)}</div>`:"";return`
|
|
1364
|
-
<div class="field ${s}" data-field-id="${e.id}" data-entry-index="${r}">
|
|
1365
|
-
${l}
|
|
1366
|
-
${c}
|
|
1367
|
-
${u}
|
|
1368
|
-
</div>`}renderInput(e,t,r){const i=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="${ut(String(i??""))}" placeholder="${ut(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="${ut(a.placeholder??"")}" ${a.maxLength?`maxlength="${a.maxLength}"`:""}>${Ve(String(i??""))}</textarea>`}if(e.type==="number"){const a=e,l=a.currency?`<span class="prefix">${Ve(a.currency)}</span>`:"",c=a.readOnly?"disabled":"",u=a.readOnly?"input--readonly":"";return`
|
|
1369
|
-
<div class="input-with-prefix">
|
|
1370
|
-
${l}
|
|
1371
|
-
<input type="number" class="input ${u}" id="${n}" ${s} value="${ut(String(i??""))}" placeholder="${ut(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="${ut(String(i??""))}"/>`;if(e.type==="select"){const a=e,l=a.options.map(c=>`<option value="${ut(c.value)}" ${i===c.value?"selected":""}>${Ve(c.label)}</option>`).join("");return`<select class="input" id="${n}" ${s}><option value="">${Ve(a.placeholder??"Select…")}</option>${l}</select>`}if(e.type==="radio")return`
|
|
1373
|
-
<div class="radio-group">
|
|
1374
|
-
${e.options.map(l=>{const c=i===l.value?"checked":"",u=`${n}-${l.value}`;return`
|
|
1375
|
-
<label class="radio-item ${c?"selected":""}" for="${u}">
|
|
1376
|
-
<input type="radio" id="${u}" ${s} name="${n}" value="${ut(l.value)}" ${c}/>
|
|
1377
|
-
<span class="radio-label">${Ve(l.label)}</span>
|
|
1378
|
-
</label>`}).join("")}
|
|
1379
|
-
</div>`;if(e.type==="yes-no"){const a=i===!0?"checked":"",l=i===!1?"checked":"";return`
|
|
1380
|
-
<div class="radio-group">
|
|
1381
|
-
<label class="radio-item ${a?"selected":""}">
|
|
1382
|
-
<input type="radio" ${s} name="${n}" value="true" ${a}/>
|
|
1383
|
-
<span class="radio-label">Yes</span>
|
|
1384
|
-
</label>
|
|
1385
|
-
<label class="radio-item ${l?"selected":""}">
|
|
1386
|
-
<input type="radio" ${s} name="${n}" value="false" ${l}/>
|
|
1387
|
-
<span class="radio-label">No</span>
|
|
1388
|
-
</label>
|
|
1389
|
-
</div>`}return e.type==="checkbox"?`
|
|
1390
|
-
<label class="checkbox-item">
|
|
1391
|
-
<input type="checkbox" id="${n}" ${s} ${i===!0?"checked":""}/>
|
|
1392
|
-
<span class="checkbox-label">${Ve(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,i=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(i,r,a),this.syncConditionalVisibility()):this.setEntry(i,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.renderPreservingScroll()})}),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
|
-
/* Pure-flex height chain — no percentage heights, which do not
|
|
1395
|
-
resolve reliably through a max-height-only flex ancestor. The
|
|
1396
|
-
modal makes this element a flex item (flex:1; min-height:0); we
|
|
1397
|
-
then flex all the way down to .scroll so it owns the overflow. */
|
|
1398
|
-
:host {
|
|
1399
|
-
display: flex;
|
|
1400
|
-
flex-direction: column;
|
|
1401
|
-
min-height: 0;
|
|
1402
|
-
color: var(--aikaara-text, #0f172a);
|
|
1403
|
-
font-family: var(--aikaara-font, system-ui, -apple-system, sans-serif);
|
|
1404
|
-
}
|
|
1405
|
-
.container { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; }
|
|
1406
|
-
.scroll {
|
|
1407
|
-
flex: 1; min-height: 0; overflow-y: auto;
|
|
1408
|
-
padding: 16px 18px 8px;
|
|
1409
|
-
display: flex; flex-direction: column; gap: 14px;
|
|
1410
|
-
}
|
|
1411
|
-
/* Flex children with overflow:hidden get an automatic min-height of 0
|
|
1412
|
-
and can be squashed (clipping fields) instead of letting .scroll
|
|
1413
|
-
scroll. Keep every card at its natural height. */
|
|
1414
|
-
.scroll > *, .entries > *, .entry-body > * { flex-shrink: 0; }
|
|
1415
|
-
/* Conditional-field wrapper: layout-transparent when shown, gone when
|
|
1416
|
-
hidden, so parent flex gaps behave as if it were not there. */
|
|
1417
|
-
.cond { display: contents; }
|
|
1418
|
-
.cond[hidden] { display: none; }
|
|
1419
|
-
.section-card {
|
|
1420
|
-
display: flex; align-items: center; gap: 12px;
|
|
1421
|
-
padding: 13px 15px;
|
|
1422
|
-
background: var(--aikaara-section-bg, #eaf2fd);
|
|
1423
|
-
border: 1px solid var(--aikaara-section-border, #d4e4fb);
|
|
1424
|
-
border-radius: 12px;
|
|
1425
|
-
}
|
|
1426
|
-
.section-icon { font-size: 20px; line-height: 1; flex-shrink: 0; }
|
|
1427
|
-
.section-meta { min-width: 0; }
|
|
1428
|
-
.section-title { font-size: 15px; font-weight: 700; color: var(--aikaara-text-strong, #0f2f5c); }
|
|
1429
|
-
.section-hint { font-size: 12px; color: var(--aikaara-text-muted, #5b7798); margin-top: 2px; }
|
|
1430
|
-
.entries { display: flex; flex-direction: column; gap: 14px; }
|
|
1431
|
-
.entry-card {
|
|
1432
|
-
border: 1px solid var(--aikaara-border, #e3e8ef);
|
|
1433
|
-
border-radius: 12px;
|
|
1434
|
-
overflow: hidden;
|
|
1435
|
-
background: #ffffff;
|
|
1436
|
-
}
|
|
1437
|
-
.entry-header {
|
|
1438
|
-
display: flex; align-items: center; justify-content: space-between;
|
|
1439
|
-
padding: 10px 14px;
|
|
1440
|
-
background: var(--aikaara-entry-bg, #e8f1fd);
|
|
1441
|
-
border-bottom: 1px solid var(--aikaara-section-border, #d4e4fb);
|
|
1442
|
-
}
|
|
1443
|
-
.entry-label {
|
|
1444
|
-
display: inline-flex; align-items: center; gap: 7px;
|
|
1445
|
-
font-size: 13.5px; font-weight: 700;
|
|
1446
|
-
color: var(--aikaara-primary, #2563eb);
|
|
1447
|
-
}
|
|
1448
|
-
.entry-icon { font-size: 15px; }
|
|
1449
|
-
.remove-btn {
|
|
1450
|
-
background: transparent; border: none; cursor: pointer;
|
|
1451
|
-
font: inherit; font-size: 12px; font-weight: 600;
|
|
1452
|
-
color: #b91c1c;
|
|
1453
|
-
padding: 3px 8px; border-radius: 6px;
|
|
1454
|
-
}
|
|
1455
|
-
.remove-btn:hover { background: rgba(185,28,28,0.10); }
|
|
1456
|
-
.entry-body { padding: 14px; display: flex; flex-direction: column; gap: 14px; }
|
|
1457
|
-
.group {
|
|
1458
|
-
border: 1px solid var(--aikaara-group-border, #dbe7e0);
|
|
1459
|
-
border-radius: 10px;
|
|
1460
|
-
padding: 0;
|
|
1461
|
-
margin: 0;
|
|
1462
|
-
background: var(--aikaara-group-bg, #f1f7f3);
|
|
1463
|
-
overflow: hidden;
|
|
1464
|
-
}
|
|
1465
|
-
.group-title {
|
|
1466
|
-
display: block;
|
|
1467
|
-
float: none;
|
|
1468
|
-
width: 100%;
|
|
1469
|
-
box-sizing: border-box;
|
|
1470
|
-
padding: 10px 13px;
|
|
1471
|
-
font-size: 12.5px; font-weight: 700;
|
|
1472
|
-
color: var(--aikaara-text-strong, #1f3b2e);
|
|
1473
|
-
background: var(--aikaara-group-head, #e6f1ea);
|
|
1474
|
-
border-bottom: 1px solid var(--aikaara-group-border, #dbe7e0);
|
|
1475
|
-
}
|
|
1476
|
-
.group-hint {
|
|
1477
|
-
font-size: 11.5px;
|
|
1478
|
-
color: var(--aikaara-text-muted, #5b7798);
|
|
1479
|
-
font-style: italic;
|
|
1480
|
-
padding: 8px 13px 0;
|
|
1481
|
-
}
|
|
1482
|
-
.group-body { padding: 12px 13px; display: flex; flex-direction: column; gap: 12px; }
|
|
1483
|
-
/* The display:flex above is an author rule and so beats the UA
|
|
1484
|
-
stylesheet's [hidden] rule. Without this, the hidden attribute
|
|
1485
|
-
toggles but nothing moves and a collapsible group looks stuck open. */
|
|
1486
|
-
.group-body[hidden] { display: none; }
|
|
1487
|
-
.group--collapsible { padding: 0; }
|
|
1488
|
-
.group-toggle {
|
|
1489
|
-
width: 100%; display: flex; align-items: center; justify-content: space-between;
|
|
1490
|
-
gap: 8px; padding: 12px 13px; background: none; border: 0; cursor: pointer;
|
|
1491
|
-
font: inherit; text-align: left; color: inherit;
|
|
1492
|
-
}
|
|
1493
|
-
.group-toggle .group-title { padding: 0; }
|
|
1494
|
-
.group-chevron {
|
|
1495
|
-
flex: none; width: 9px; height: 9px; border-right: 2px solid currentColor;
|
|
1496
|
-
border-bottom: 2px solid currentColor; opacity: .55; margin-right: 3px;
|
|
1497
|
-
transform: rotate(45deg) translate(-2px, -2px);
|
|
1498
|
-
transition: transform .15s ease;
|
|
1499
|
-
}
|
|
1500
|
-
.group--collapsible:not(.is-collapsed) .group-chevron {
|
|
1501
|
-
transform: rotate(-135deg) translate(-3px, -3px);
|
|
1502
|
-
}
|
|
1503
|
-
.field { display: flex; flex-direction: column; gap: 6px; }
|
|
1504
|
-
.field-label {
|
|
1505
|
-
font-size: 12.5px; font-weight: 600;
|
|
1506
|
-
color: var(--aikaara-text, #334155);
|
|
1507
|
-
}
|
|
1508
|
-
.req { color: #dc2626; }
|
|
1509
|
-
.input {
|
|
1510
|
-
width: 100%;
|
|
1511
|
-
padding: 10px 12px;
|
|
1512
|
-
font: inherit;
|
|
1513
|
-
font-size: 13.5px;
|
|
1514
|
-
border: 1px solid var(--aikaara-input-border, #cbd5e1);
|
|
1515
|
-
border-radius: 8px;
|
|
1516
|
-
background: #ffffff;
|
|
1517
|
-
color: inherit;
|
|
1518
|
-
box-sizing: border-box;
|
|
1519
|
-
outline: none;
|
|
1520
|
-
transition: border-color 150ms, box-shadow 150ms;
|
|
1521
|
-
}
|
|
1522
|
-
.input--readonly, .input--readonly:focus, .input[disabled] {
|
|
1523
|
-
background: var(--aikaara-readonly-bg, #f1f5f9);
|
|
1524
|
-
color: var(--aikaara-text-muted, #64748b);
|
|
1525
|
-
cursor: not-allowed;
|
|
1526
|
-
border-color: var(--aikaara-input-border, #e2e8f0);
|
|
1527
|
-
box-shadow: none;
|
|
1528
|
-
}
|
|
1529
|
-
.textarea { resize: vertical; min-height: 70px; line-height: 1.45; }
|
|
1530
|
-
.input:focus {
|
|
1531
|
-
border-color: var(--aikaara-primary, #2563eb);
|
|
1532
|
-
box-shadow: 0 0 0 3px rgba(37,99,235,0.16);
|
|
1533
|
-
}
|
|
1534
|
-
.field.has-error .input,
|
|
1535
|
-
.field.has-error .input-with-prefix { border-color: #dc2626; }
|
|
1536
|
-
.input-with-prefix {
|
|
1537
|
-
display: flex; align-items: stretch;
|
|
1538
|
-
border: 1px solid var(--aikaara-input-border, #cbd5e1);
|
|
1539
|
-
border-radius: 8px;
|
|
1540
|
-
background: #ffffff;
|
|
1541
|
-
overflow: hidden;
|
|
1542
|
-
}
|
|
1543
|
-
.input-with-prefix .prefix {
|
|
1544
|
-
padding: 0 11px;
|
|
1545
|
-
display: flex; align-items: center;
|
|
1546
|
-
background: var(--aikaara-prefix-bg, #f1f5f9);
|
|
1547
|
-
color: var(--aikaara-text-muted, #475569);
|
|
1548
|
-
font-size: 13.5px;
|
|
1549
|
-
border-right: 1px solid var(--aikaara-input-border, #cbd5e1);
|
|
1550
|
-
}
|
|
1551
|
-
.input-with-prefix .input { border: none; border-radius: 0; }
|
|
1552
|
-
.input-with-prefix:focus-within {
|
|
1553
|
-
border-color: var(--aikaara-primary, #2563eb);
|
|
1554
|
-
box-shadow: 0 0 0 3px rgba(37,99,235,0.16);
|
|
1555
|
-
}
|
|
1556
|
-
.radio-group { display: flex; flex-wrap: wrap; gap: 10px; padding: 2px 0; }
|
|
1557
|
-
.radio-item {
|
|
1558
|
-
display: inline-flex; align-items: center; gap: 8px;
|
|
1559
|
-
font-size: 13px; cursor: pointer;
|
|
1560
|
-
padding: 8px 13px;
|
|
1561
|
-
border: 1px solid var(--aikaara-input-border, #cbd5e1);
|
|
1562
|
-
border-radius: 8px;
|
|
1563
|
-
background: #ffffff;
|
|
1564
|
-
transition: border-color 150ms, background 150ms;
|
|
1565
|
-
}
|
|
1566
|
-
.radio-item.selected {
|
|
1567
|
-
border-color: var(--aikaara-primary, #2563eb);
|
|
1568
|
-
background: var(--aikaara-primary-soft, rgba(37,99,235,0.08));
|
|
1569
|
-
}
|
|
1570
|
-
.radio-item input[type="radio"] { accent-color: var(--aikaara-primary, #2563eb); }
|
|
1571
|
-
.checkbox-item {
|
|
1572
|
-
display: inline-flex; align-items: center; gap: 8px;
|
|
1573
|
-
font-size: 13px; cursor: pointer;
|
|
1574
|
-
}
|
|
1575
|
-
.checkbox-item input[type="checkbox"] { accent-color: var(--aikaara-primary, #2563eb); }
|
|
1576
|
-
.field-error { font-size: 11.5px; color: #dc2626; }
|
|
1577
|
-
.add-btn {
|
|
1578
|
-
align-self: flex-start;
|
|
1579
|
-
background: transparent;
|
|
1580
|
-
border: 1px dashed var(--aikaara-primary, #2563eb);
|
|
1581
|
-
color: var(--aikaara-primary, #2563eb);
|
|
1582
|
-
font: inherit; font-size: 13px; font-weight: 600;
|
|
1583
|
-
padding: 9px 15px;
|
|
1584
|
-
border-radius: 8px;
|
|
1585
|
-
cursor: pointer;
|
|
1586
|
-
}
|
|
1587
|
-
.add-btn:hover { background: var(--aikaara-primary-soft, rgba(37,99,235,0.08)); }
|
|
1588
|
-
.footer {
|
|
1589
|
-
flex-shrink: 0;
|
|
1590
|
-
padding: 12px 18px;
|
|
1591
|
-
border-top: 1px solid var(--aikaara-border, #e3e8ef);
|
|
1592
|
-
background: var(--aikaara-surface, #ffffff);
|
|
1593
|
-
}
|
|
1594
|
-
.save-btn {
|
|
1595
|
-
width: 100%;
|
|
1596
|
-
padding: 13px 18px;
|
|
1597
|
-
background: var(--aikaara-primary, #2563eb);
|
|
1598
|
-
color: #ffffff;
|
|
1599
|
-
border: none;
|
|
1600
|
-
border-radius: 10px;
|
|
1601
|
-
font: inherit; font-size: 14.5px; font-weight: 700;
|
|
1602
|
-
cursor: pointer;
|
|
1603
|
-
transition: filter 150ms;
|
|
1604
|
-
}
|
|
1605
|
-
.save-btn:hover { filter: brightness(1.07); }
|
|
1606
|
-
.save-btn:active { filter: brightness(0.95); }
|
|
1607
|
-
`}}function ut(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ve(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Pe(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Jt(o){return Pe(o)}function tt(o){return`₹${Math.round(Number.isFinite(o)?o:0).toLocaleString("en-IN")}`}function Zr(o){const e=Number(o.basePrice)||0,t=o.gstRate??.18,r=Math.round(e*t),i=Number(o.discount)||0;return{base:e,gst:r,discount:i,total:e+r-i}}function Bo(o){const[e,t,r]=o.split("-").map(Number);return new Date(e||1970,(t||1)-1,r||1)}function ua(o){const e=o.getFullYear(),t=String(o.getMonth()+1).padStart(2,"0"),r=String(o.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Vf(o,e){const t=new Date(o);return t.setDate(t.getDate()+e),t}function wo(o){return Bo(o).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}function Kf(o){const e=Bo(o);return{weekday:e.toLocaleDateString("en-GB",{weekday:"short"}),day:String(e.getDate()),month:e.toLocaleDateString("en-GB",{month:"short"})}}function dr(o){const[e=0,t=0]=o.split(":").map(Number);return`${da(e*60+t)} – ${da(e*60+t+30)}`}function da(o){const e=(o%1440+1440)%1440,t=Math.floor(e/60),r=e%60,i=(t+11)%12+1,n=t<12?"AM":"PM";return`${i}:${String(r).padStart(2,"0")} ${n}`}const Gf="serviceId";class Nc 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??Gf}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(i=>`
|
|
1608
|
-
<button class="service" type="button" role="radio" aria-checked="${i.id===this.selectedId}"
|
|
1609
|
-
data-id="${Jt(i.id)}" ${this.locked()?"disabled":""}>
|
|
1610
|
-
<span class="info">
|
|
1611
|
-
<span class="name">${Pe(i.name)}</span>
|
|
1612
|
-
${i.tagline?`<span class="tagline">${Pe(i.tagline)}</span>`:""}
|
|
1613
|
-
</span>
|
|
1614
|
-
${t?`<span class="from">from ${Pe(tt(i.basePrice))}</span>`:""}
|
|
1615
|
-
</button>`).join("");this.shadow.innerHTML=`
|
|
1616
|
-
<style>${Yf}</style>
|
|
1617
|
-
<div class="card" part="card">
|
|
1618
|
-
${this.data?.title?`<div class="title">${Pe(this.data.title)}</div>`:""}
|
|
1619
|
-
${this.data?.subtitle?`<div class="subtitle">${Pe(this.data.subtitle)}</div>`:""}
|
|
1620
|
-
<div class="list" role="radiogroup" aria-label="${Jt(this.data?.title??"Select a service")}">
|
|
1621
|
-
${r||'<div class="empty">No services available.</div>'}
|
|
1622
|
-
</div>
|
|
1623
|
-
</div>
|
|
1624
|
-
`,this.shadow.querySelectorAll("button.service").forEach(i=>{i.addEventListener("click",()=>{const n=i.dataset.id,s=e.find(a=>a.id===n);s&&this.select(s)})})}}const Yf=`
|
|
1625
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1626
|
-
.card {
|
|
1627
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1628
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1629
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1630
|
-
padding: 14px;
|
|
1631
|
-
}
|
|
1632
|
-
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1633
|
-
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1634
|
-
.list { display: flex; flex-direction: column; gap: 10px; margin-top: 12px; }
|
|
1635
|
-
.empty { padding: 16px 4px; text-align: center; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1636
|
-
.service {
|
|
1637
|
-
display: flex; align-items: flex-start; justify-content: space-between; gap: 12px;
|
|
1638
|
-
width: 100%; text-align: left; cursor: pointer; font-family: inherit;
|
|
1639
|
-
background: var(--aikaara-service-card-bg, var(--aikaara-surface, #fff));
|
|
1640
|
-
border: 1.5px solid var(--aikaara-border, #e5e7eb);
|
|
1641
|
-
border-radius: 12px; padding: 14px;
|
|
1642
|
-
transition: border-color 120ms, background 120ms;
|
|
1643
|
-
}
|
|
1644
|
-
.service:hover:not(:disabled) { border-color: var(--aikaara-primary, #6366f1); }
|
|
1645
|
-
.service[aria-checked="true"] { border-color: var(--aikaara-primary, #6366f1); background: var(--aikaara-primary-soft, #eef2ff); }
|
|
1646
|
-
.service:disabled { cursor: default; opacity: 0.85; }
|
|
1647
|
-
.info { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
|
1648
|
-
.name { font-weight: 600; font-size: 14px; }
|
|
1649
|
-
.tagline { font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1650
|
-
.from { flex-shrink: 0; font-size: 13px; font-weight: 600; color: var(--aikaara-primary, #6366f1); white-space: nowrap; }
|
|
1651
|
-
`,Jf="serviceDetails";class Rc 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??Jf}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=Zr({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:i=[],limitations:n=[],extraInclusions:s=[],extraLimitations:a=[]}=this.data,c=(this.data.showPricing??!0)&&typeof this.data.basePrice=="number"?Zr({basePrice:this.data.basePrice??0,discount:this.data.discount,gstRate:this.data.gstRate}):null,u=[...i,...s],d=[...n,...a],p=u.map(y=>`<li class="row"><span class="mark ok">✓</span><span>${Pe(y)}</span></li>`).join(""),g=d.map(y=>`<li class="row muted"><span class="mark no">✕</span><span>${Pe(y)}</span></li>`).join(""),h=c?`
|
|
1652
|
-
<div class="section">
|
|
1653
|
-
<h3>Pricing</h3>
|
|
1654
|
-
<div class="price">
|
|
1655
|
-
<div class="prow"><span>Service price</span><span>${Pe(tt(c.base))}</span></div>
|
|
1656
|
-
<div class="prow"><span>GST (${Math.round((this.data.gstRate??.18)*100)}%)</span><span>${Pe(tt(c.gst))}</span></div>
|
|
1657
|
-
${c.discount>0?`<div class="prow green"><span>Offer discount</span><span>-${Pe(tt(c.discount))}</span></div>`:""}
|
|
1658
|
-
<div class="prow total"><span>Final payable</span><span>${Pe(tt(c.total))}</span></div>
|
|
1659
|
-
</div>
|
|
1660
|
-
</div>`:"",b=this.locked()?"":`<button class="cta" type="button">${Pe(this.data.continueLabel??"Continue")}</button>`;this.shadow.innerHTML=`
|
|
1661
|
-
<style>${Qf}</style>
|
|
1662
|
-
<div class="card" part="card">
|
|
1663
|
-
<div class="section">
|
|
1664
|
-
${r?`<span class="badge">${Pe(r)}</span>`:""}
|
|
1665
|
-
<h2 class="name">${Pe(e)}</h2>
|
|
1666
|
-
${t?`<p class="tagline">${Pe(t)}</p>`:""}
|
|
1667
|
-
</div>
|
|
1668
|
-
${p?`<div class="section"><h3>What's Included</h3><ul>${p}</ul></div>`:""}
|
|
1669
|
-
${g?`<div class="section"><h3>Not Included</h3><ul>${g}</ul></div>`:""}
|
|
1670
|
-
${h}
|
|
1671
|
-
${b}
|
|
1672
|
-
</div>
|
|
1673
|
-
`,this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}const Qf=`
|
|
1674
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1675
|
-
.card {
|
|
1676
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1677
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1678
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1679
|
-
padding: 14px;
|
|
1680
|
-
}
|
|
1681
|
-
.section + .section { margin-top: 14px; border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 14px; }
|
|
1682
|
-
.badge {
|
|
1683
|
-
display: inline-block; padding: 3px 10px; border-radius: 999px; font-size: 12px; font-weight: 500;
|
|
1684
|
-
background: var(--aikaara-primary-soft, #eef2ff); color: var(--aikaara-primary, #6366f1);
|
|
1685
|
-
}
|
|
1686
|
-
.name { margin: 8px 0 0; font-size: 19px; font-weight: 700; color: var(--aikaara-text, #111827); }
|
|
1687
|
-
.tagline { margin: 2px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1688
|
-
h3 { margin: 0; font-size: 14px; font-weight: 600; }
|
|
1689
|
-
ul { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
|
|
1690
|
-
.row { display: flex; gap: 8px; font-size: 13px; align-items: flex-start; }
|
|
1691
|
-
.row.muted { color: var(--aikaara-text-secondary, #6b7280); }
|
|
1692
|
-
.mark { flex-shrink: 0; font-weight: 700; line-height: 1.4; }
|
|
1693
|
-
.mark.ok { color: #16a34a; }
|
|
1694
|
-
.mark.no { color: #9ca3af; }
|
|
1695
|
-
.price { margin-top: 8px; display: flex; flex-direction: column; gap: 6px; font-size: 13px; }
|
|
1696
|
-
.prow { display: flex; justify-content: space-between; }
|
|
1697
|
-
.prow.green span:last-child { color: #16a34a; }
|
|
1698
|
-
.prow.total { border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 8px; font-size: 15px; font-weight: 700; }
|
|
1699
|
-
.cta {
|
|
1700
|
-
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1701
|
-
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1702
|
-
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1703
|
-
font-family: inherit; cursor: pointer;
|
|
1704
|
-
}
|
|
1705
|
-
.cta:hover { filter: brightness(0.96); }
|
|
1706
|
-
`,Xf="priceAccepted";class jc 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??Xf}locked(){return this.dataset.consumed==="true"}handleContinue(){if(this.locked()||!this.data)return;const e=this.data.continueLabel??"Continue",t=Zr(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=Zr(this.data),t=Math.round((this.data.gstRate??.18)*100),r=this.data.feeLabel??"Service Fee",i=this.data.discountLabel??"Discount",n=this.data.totalLabel??"Total Payable",s=this.data.name?`${Pe(this.data.name)} Consultation`:"Price Breakdown",a=this.locked()?"":`<button class="cta" type="button">${Pe(this.data.continueLabel??"Continue to Schedule")}</button>`;this.shadow.innerHTML=`
|
|
1707
|
-
<style>${Zf}</style>
|
|
1708
|
-
<div class="card" part="card">
|
|
1709
|
-
<h2>${s}</h2>
|
|
1710
|
-
<p class="sub">30 minute call with a tax expert</p>
|
|
1711
|
-
<table>
|
|
1712
|
-
<thead><tr><th>Particular</th><th class="right">Amount</th></tr></thead>
|
|
1713
|
-
<tbody>
|
|
1714
|
-
<tr><td>${Pe(r)}</td><td class="right">${Pe(tt(e.base))}</td></tr>
|
|
1715
|
-
<tr><td>GST (${t}%)</td><td class="right">${Pe(tt(e.gst))}</td></tr>
|
|
1716
|
-
<tr class="green"><td>${Pe(i)}</td><td class="right">${e.discount?"-"+Pe(tt(e.discount)):Pe(tt(0))}</td></tr>
|
|
1717
|
-
<tr class="total"><td>${Pe(n)}</td><td class="right">${Pe(tt(e.total))}</td></tr>
|
|
1718
|
-
</tbody>
|
|
1719
|
-
</table>
|
|
1720
|
-
${this.data.note?`<p class="note">${Pe(this.data.note)}</p>`:""}
|
|
1721
|
-
${a}
|
|
1722
|
-
</div>
|
|
1723
|
-
`,this.shadow.querySelector("button.cta")?.addEventListener("click",()=>this.handleContinue())}}const Zf=`
|
|
1724
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1725
|
-
.card {
|
|
1726
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1727
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1728
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1729
|
-
padding: 14px;
|
|
1730
|
-
}
|
|
1731
|
-
h2 { margin: 0; font-size: 16px; font-weight: 700; color: var(--aikaara-text, #111827); }
|
|
1732
|
-
.sub { margin: 2px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1733
|
-
table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: 13px; }
|
|
1734
|
-
th { padding: 8px 0; text-align: left; font-weight: 500; color: var(--aikaara-text-secondary, #6b7280); border-bottom: 1px solid var(--aikaara-border, #eef1f4); }
|
|
1735
|
-
td { padding: 9px 0; }
|
|
1736
|
-
.right { text-align: right; }
|
|
1737
|
-
tr.green td { color: #16a34a; }
|
|
1738
|
-
tr.total td { border-top: 1px solid var(--aikaara-border, #eef1f4); font-size: 15px; font-weight: 700; }
|
|
1739
|
-
.note { margin: 8px 0 0; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1740
|
-
.cta {
|
|
1741
|
-
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1742
|
-
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1743
|
-
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1744
|
-
font-family: inherit; cursor: pointer;
|
|
1745
|
-
}
|
|
1746
|
-
.cta:hover { filter: brightness(0.96); }
|
|
1747
|
-
`,ep=["09:00","10:00","11:00","12:00","14:00","15:00","16:00","17:00"],tp=7,rp="callSlot";class Dc 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??rp}setConsumedValues(e){const t=e?.[this.getName()],r=Array.isArray(t)?t[0]:t;if(typeof r=="string"&&r.trim()){const[i,n]=r.trim().split(/[ T]/);i&&(this.selectedDate=i),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(np)})).filter(l=>!t.has(l.iso));const i=e.startDate?Bo(e.startDate):new Date,n=Math.max(1,e.daysAhead??tp),s=e.times&&e.times.length?e.times:ep,a=[];for(let l=0;l<n;l++){const c=ua(Vf(i,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!==ua(new Date))return!0;const[r=0,i=0]=t.start.split(":").map(Number),n=new Date;return r*60+i>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:dr(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=`
|
|
1748
|
-
<style>${ha}</style>
|
|
1749
|
-
<div class="card" part="card">
|
|
1750
|
-
${this.data.title?`<div class="title">${Pe(this.data.title)}</div>`:""}
|
|
1751
|
-
${this.data.subtitle?`<div class="subtitle">${Pe(this.data.subtitle)}</div>`:""}
|
|
1752
|
-
${this.renderBody(e,t)}
|
|
1753
|
-
</div>
|
|
1754
|
-
`,this.attachListeners()}renderBody(e,t){if(this.loading)return'<div class="state">Loading available times…</div>';if(this.errorMessage)return`<div class="state error">${Pe(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}=Kf(a.iso);return`
|
|
1755
|
-
<button class="day" type="button" role="radio" aria-checked="${a.iso===this.selectedDate}" data-date="${Jt(a.iso)}">
|
|
1756
|
-
<span class="day-weekday">${Pe(l)}</span>
|
|
1757
|
-
<span class="day-num">${Pe(c)}</span>
|
|
1758
|
-
<span class="day-month">${Pe(u)}</span>
|
|
1759
|
-
</button>`}).join(""),i=(t?.slots??[]).map(a=>{const l=t?this.isSelectable(t.iso,a):!1;return`
|
|
1760
|
-
<button class="slot" type="button" role="radio" aria-checked="${a.start===this.selectedSlot}"
|
|
1761
|
-
data-time="${Jt(a.start)}" ${l?"":"disabled"}>
|
|
1762
|
-
${Pe(dr(a.start))}
|
|
1763
|
-
</button>`}).join(""),n=this.selectedDate&&this.selectedSlot?`<div class="summary">${Pe(wo(this.selectedDate))} · ${Pe(dr(this.selectedSlot))}</div>`:"",s=this.isLocked()?"":`<button class="cta" type="button" ${this.selectedDate&&this.selectedSlot?"":"disabled"}>
|
|
1764
|
-
${Pe(this.data?.continueLabel??"Continue")}
|
|
1765
|
-
</button>`;return`
|
|
1766
|
-
<section><h3>Select Date</h3><div class="days" role="radiogroup" aria-label="Select a date">${r}</div></section>
|
|
1767
|
-
<section>
|
|
1768
|
-
<h3>Select Time Slot</h3>
|
|
1769
|
-
${t?`<div class="times" role="radiogroup" aria-label="Select a time">${i}</div>`:'<p class="hint">Pick a date to see available slots.</p>'}
|
|
1770
|
-
</section>
|
|
1771
|
-
${n}
|
|
1772
|
-
${s}
|
|
1773
|
-
`}lockedTemplate(){return`
|
|
1774
|
-
<style>${ha}</style>
|
|
1775
|
-
<div class="card locked" part="card">
|
|
1776
|
-
<div class="locked-head"><span class="tick" aria-hidden="true">✓</span> Slot selected</div>
|
|
1777
|
-
<div class="locked-when">${Pe(wo(this.selectedDate))} · ${Pe(dr(this.selectedSlot))}</div>
|
|
1778
|
-
${this.data?.timezone?`<div class="locked-tz">${Pe(this.data.timezone)}</div>`:""}
|
|
1779
|
-
</div>
|
|
1780
|
-
`}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 np(o){return typeof o=="string"?{start:o,available:!0}:{start:o.start,available:o.available}}const ha=`
|
|
1781
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1782
|
-
.card {
|
|
1783
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1784
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1785
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1786
|
-
padding: 14px;
|
|
1787
|
-
}
|
|
1788
|
-
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1789
|
-
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1790
|
-
section { margin-top: 12px; }
|
|
1791
|
-
h3 { margin: 0 0 8px; font-size: 14px; font-weight: 600; }
|
|
1792
|
-
.state, .hint { padding: 12px 2px; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1793
|
-
.state { text-align: center; }
|
|
1794
|
-
.state.error { color: var(--aikaara-input-error-color, #ef4444); }
|
|
1795
|
-
.days { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 4px; }
|
|
1796
|
-
.day {
|
|
1797
|
-
flex: 0 0 auto; display: flex; flex-direction: column; align-items: center; gap: 1px;
|
|
1798
|
-
min-width: 54px; padding: 8px 6px; cursor: pointer; font-family: inherit;
|
|
1799
|
-
background: var(--aikaara-slot-day-bg, transparent);
|
|
1800
|
-
color: var(--aikaara-text, #1f2937);
|
|
1801
|
-
border: 1.5px solid var(--aikaara-border, #e5e7eb);
|
|
1802
|
-
border-radius: 10px; transition: border-color 120ms, background 120ms, color 120ms;
|
|
1803
|
-
}
|
|
1804
|
-
.day:hover { border-color: var(--aikaara-primary, #6366f1); }
|
|
1805
|
-
.day[aria-checked="true"] { background: var(--aikaara-primary, #6366f1); color: #fff; border-color: var(--aikaara-primary, #6366f1); }
|
|
1806
|
-
.day-weekday, .day-month { font-size: 11px; opacity: 0.85; }
|
|
1807
|
-
.day-num { font-size: 16px; font-weight: 700; line-height: 1.1; }
|
|
1808
|
-
.times { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
|
1809
|
-
.slot {
|
|
1810
|
-
padding: 9px 8px; font-size: 13px; font-family: inherit; cursor: pointer;
|
|
1811
|
-
background: var(--aikaara-slot-bg, transparent);
|
|
1812
|
-
color: var(--aikaara-text, #1f2937);
|
|
1813
|
-
border: 1.5px solid var(--aikaara-slot-border, var(--aikaara-border, #e5e7eb));
|
|
1814
|
-
border-radius: 9px; transition: background 120ms, color 120ms, border-color 120ms;
|
|
1815
|
-
}
|
|
1816
|
-
.slot:hover:not(:disabled) { border-color: var(--aikaara-primary, #6366f1); }
|
|
1817
|
-
.slot[aria-checked="true"] { background: var(--aikaara-primary, #6366f1); color: #fff; border-color: var(--aikaara-primary, #6366f1); font-weight: 600; }
|
|
1818
|
-
.slot:disabled { cursor: not-allowed; text-decoration: line-through; opacity: 0.55; }
|
|
1819
|
-
.summary {
|
|
1820
|
-
margin-top: 12px; padding: 10px 12px; border-radius: 10px; font-size: 13px; font-weight: 600;
|
|
1821
|
-
background: var(--aikaara-primary-soft, #eef2ff); color: var(--aikaara-primary, #6366f1);
|
|
1822
|
-
}
|
|
1823
|
-
.cta {
|
|
1824
|
-
width: 100%; margin-top: 12px; padding: 12px 16px;
|
|
1825
|
-
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1826
|
-
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1827
|
-
font-family: inherit; cursor: pointer;
|
|
1828
|
-
}
|
|
1829
|
-
.cta:hover:not(:disabled) { filter: brightness(0.96); }
|
|
1830
|
-
.cta:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
1831
|
-
.card.locked { background: var(--aikaara-surface-muted, #f6fafb); }
|
|
1832
|
-
.locked-head { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; }
|
|
1833
|
-
.tick { color: #16a34a; font-weight: 700; }
|
|
1834
|
-
.locked-when { margin-top: 6px; font-size: 14px; }
|
|
1835
|
-
.locked-tz { margin-top: 2px; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1836
|
-
`,ip="callDetails";class $c 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??ip}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(i=>i.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(),i=this.fileNames.length?`<ul class="files">${this.fileNames.map((c,u)=>`<li><span class="fname">${Pe(c)}</span>${r?"":`<button class="rm" type="button" data-i="${u}" aria-label="Remove file">✕</button>`}</li>`).join("")}</ul>`:"",n=e.enabled===!1?"":`
|
|
1837
|
-
<div class="section">
|
|
1838
|
-
<h3>${Pe(e.label??"Upload Documents")} <span class="opt">(Optional)</span></h3>
|
|
1839
|
-
<p class="hint">${Pe(e.hint??"ITR / tax documents, GST documents, notices, statements or anything that helps the expert understand your case.")}</p>
|
|
1840
|
-
${r?"":`<label class="drop">
|
|
1841
|
-
<span class="drop-title">Tap to upload</span>
|
|
1842
|
-
<span class="drop-hint">PDF, JPG, PNG · up to ${e.maxFiles??10} files</span>
|
|
1843
|
-
<input type="file" multiple accept="${Jt(e.accept??".pdf,.jpg,.jpeg,.png")}" />
|
|
1844
|
-
</label>`}
|
|
1845
|
-
${i}
|
|
1846
|
-
</div>`,s=t.enabled===!1?"":`
|
|
1847
|
-
<div class="section">
|
|
1848
|
-
<h3>${Pe(t.label??"Briefly describe your query")}</h3>
|
|
1849
|
-
${r?`<p class="locked-query">${Pe(this.query||"—")}</p>`:`<textarea rows="5" maxlength="${t.maxLength??1e3}"
|
|
1850
|
-
placeholder="${Jt(t.placeholder??"Briefly tell us what you would like to discuss with the expert.")}">${Pe(this.query)}</textarea>
|
|
1851
|
-
<p class="counter">${this.query.length}/${t.maxLength??1e3}</p>`}
|
|
1852
|
-
</div>`,a=r?"":`<button class="cta" type="button">${Pe(this.data.submitLabel??"Schedule Call")}</button>`;this.shadow.innerHTML=`
|
|
1853
|
-
<style>${op}</style>
|
|
1854
|
-
<div class="card" part="card">
|
|
1855
|
-
${this.data.title?`<div class="title">${Pe(this.data.title)}</div>`:""}
|
|
1856
|
-
${this.data.subtitle?`<div class="subtitle">${Pe(this.data.subtitle)}</div>`:""}
|
|
1857
|
-
${n}
|
|
1858
|
-
${s}
|
|
1859
|
-
${this.error?`<p class="error">${Pe(this.error)}</p>`:""}
|
|
1860
|
-
${a}
|
|
1861
|
-
</div>
|
|
1862
|
-
`,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,p)=>p!==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 op=`
|
|
1863
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1864
|
-
.card {
|
|
1865
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1866
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1867
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1868
|
-
padding: 14px;
|
|
1869
|
-
}
|
|
1870
|
-
.title { font-size: 15px; font-weight: 600; color: var(--aikaara-text, #111827); }
|
|
1871
|
-
.subtitle { font-size: 13px; margin-top: 2px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1872
|
-
.section + .section { margin-top: 14px; border-top: 1px solid var(--aikaara-border, #eef1f4); padding-top: 14px; }
|
|
1873
|
-
h3 { margin: 0; font-size: 14px; font-weight: 600; }
|
|
1874
|
-
.opt { font-weight: 400; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1875
|
-
.hint { margin: 4px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1876
|
-
.drop {
|
|
1877
|
-
display: flex; flex-direction: column; align-items: center; gap: 3px; margin-top: 10px;
|
|
1878
|
-
padding: 18px; border: 2px dashed var(--aikaara-input-border, #d1d5db); border-radius: 10px;
|
|
1879
|
-
cursor: pointer; text-align: center;
|
|
1880
|
-
}
|
|
1881
|
-
.drop:hover { border-color: var(--aikaara-primary, #6366f1); }
|
|
1882
|
-
.drop input { display: none; }
|
|
1883
|
-
.drop-title { font-size: 13px; font-weight: 600; color: var(--aikaara-primary, #6366f1); }
|
|
1884
|
-
.drop-hint { font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1885
|
-
.files { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
|
1886
|
-
.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; }
|
|
1887
|
-
.fname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1888
|
-
.rm { border: none; background: transparent; cursor: pointer; color: var(--aikaara-text-secondary, #6b7280); font-size: 12px; }
|
|
1889
|
-
textarea {
|
|
1890
|
-
width: 100%; box-sizing: border-box; margin-top: 8px; padding: 10px 12px; resize: vertical;
|
|
1891
|
-
border: 1.5px solid var(--aikaara-input-border, #d1d5db); border-radius: 8px;
|
|
1892
|
-
background: var(--aikaara-input-bg, #fff); color: var(--aikaara-input-color, #111827);
|
|
1893
|
-
font-size: 14px; font-family: inherit; outline: none;
|
|
1894
|
-
}
|
|
1895
|
-
textarea:focus { border-color: var(--aikaara-primary, #6366f1); }
|
|
1896
|
-
.counter { margin: 4px 0 0; text-align: right; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1897
|
-
.locked-query { margin: 8px 0 0; font-size: 13px; white-space: pre-wrap; }
|
|
1898
|
-
.error { margin: 10px 0 0; font-size: 12px; color: var(--aikaara-input-error-color, #ef4444); }
|
|
1899
|
-
.cta {
|
|
1900
|
-
width: 100%; margin-top: 14px; padding: 12px 16px;
|
|
1901
|
-
background: var(--aikaara-primary, #6366f1); color: #fff; border: none;
|
|
1902
|
-
border-radius: var(--aikaara-button-radius, 10px); font-size: 14px; font-weight: 600;
|
|
1903
|
-
font-family: inherit; cursor: pointer;
|
|
1904
|
-
}
|
|
1905
|
-
.cta:hover { filter: brightness(0.96); }
|
|
1906
|
-
`;class Uc 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)?wo(e):e}displayTime(e){return/^\d{2}:\d{2}$/.test(e)?dr(e):e}render(){if(!this.data){this.shadow.innerHTML="";return}const{expert:e,service:t,date:r,time:i,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)]),i&&l.push(["Time",this.displayTime(i)]),typeof n=="number"&&l.push(["Amount paid",tt(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">${Pe(u)}</span><span class="value">${Pe(d)}</span></div>`).join("");this.shadow.innerHTML=`
|
|
1907
|
-
<style>${sp}</style>
|
|
1908
|
-
<div class="card" part="card">
|
|
1909
|
-
<div class="head">
|
|
1910
|
-
<div class="icon" aria-hidden="true">✓</div>
|
|
1911
|
-
<h2>${Pe(this.data.title??"Call Scheduled Successfully!")}</h2>
|
|
1912
|
-
${e?`<p class="with">Your call has been scheduled with</p><p class="expert">${Pe(e)}</p>`:""}
|
|
1913
|
-
</div>
|
|
1914
|
-
${c?`<div class="summary">${c}</div>`:""}
|
|
1915
|
-
<p class="note">${Pe(this.data.note??"A Google Meet link will be shared on your registered email & WhatsApp.")}</p>
|
|
1916
|
-
</div>
|
|
1917
|
-
`}}const sp=`
|
|
1918
|
-
:host { display: block; font-family: var(--aikaara-font, system-ui, sans-serif); color: var(--aikaara-text, #1f2937); }
|
|
1919
|
-
.card {
|
|
1920
|
-
background: var(--aikaara-service-bg, var(--aikaara-surface, #ffffff));
|
|
1921
|
-
border: 1px solid var(--aikaara-border, #e5e7eb);
|
|
1922
|
-
border-radius: var(--aikaara-radius, 12px);
|
|
1923
|
-
padding: 18px 14px;
|
|
1924
|
-
}
|
|
1925
|
-
.head { text-align: center; }
|
|
1926
|
-
.icon {
|
|
1927
|
-
width: 60px; height: 60px; margin: 4px auto 10px; border-radius: 50%;
|
|
1928
|
-
display: flex; align-items: center; justify-content: center;
|
|
1929
|
-
background: var(--aikaara-success-soft, #dcfce7); color: #16a34a; font-size: 30px; font-weight: 700;
|
|
1930
|
-
}
|
|
1931
|
-
h2 { margin: 0; font-size: 19px; font-weight: 700; }
|
|
1932
|
-
.with { margin: 6px 0 0; font-size: 13px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1933
|
-
.expert { margin: 2px 0 0; font-size: 15px; font-weight: 600; color: var(--aikaara-primary, #6366f1); }
|
|
1934
|
-
.summary { margin-top: 14px; border: 1px solid var(--aikaara-border, #eef1f4); border-radius: 10px; padding: 6px 12px; }
|
|
1935
|
-
.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; }
|
|
1936
|
-
.row:last-child { border-bottom: none; }
|
|
1937
|
-
.label { color: var(--aikaara-text-secondary, #6b7280); }
|
|
1938
|
-
.value { font-weight: 600; text-align: right; }
|
|
1939
|
-
.note { margin: 12px 0 0; text-align: center; font-size: 12px; color: var(--aikaara-text-secondary, #6b7280); }
|
|
1940
|
-
`;function Bc(){const o=[["aikaara-chat-widget",uc],["aikaara-chat-bubble",dc],["aikaara-chat-header",hc],["aikaara-message-list",mc],["aikaara-message-bubble",bc],["aikaara-chat-input",yc],["aikaara-typing-indicator",vc],["aikaara-streaming-message",wc],["aikaara-error-banner",kc],["aikaara-template-renderer",_c],["aikaara-system-pill",Sc],["aikaara-option-list",Ec],["aikaara-submit-action",Ac],["aikaara-modal-action",Ic],["aikaara-text-input",Tc],["aikaara-chat",Cc],["aikaara-link-modal",Pc],["aikaara-compare-plans",Oc],["aikaara-smart-edit-modal",Lc],["aikaara-schema-form",Mc],["aikaara-service-picker",Nc],["aikaara-service-details",Rc],["aikaara-price-breakdown",jc],["aikaara-slot-picker",Dc],["aikaara-call-upload",$c],["aikaara-call-confirmation",Uc]];for(const[e,t]of o)customElements.get(e)||customElements.define(e,t)}Bc();function xr(o,e,t=""){if(!e)return t;const r=e.split(".");let i=o;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function fa(o){try{const e=o.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Yt(o){return typeof o=="function"?await o():o}class Fc{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=fa(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 Yt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",s={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",s.body=JSON.stringify(this.descriptor.body??{}));const a=await fetch(this.descriptor.endpoint,s);if(!a.ok){const w=await a.text().catch(()=>"");throw new Error(`Session auth failed: ${a.status} ${w.slice(0,200)}`)}const l=await a.json().catch(()=>({})),c=xr(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=xr(l,this.descriptor.requestIdPath??"data.requestId"),g=this.cache?.requestId||p||"",h=xr(l,this.descriptor.fullNamePath??"data.fullName"),b=xr(l,this.descriptor.userPath??"data.userId"),y=fa(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:g,fullName:h,userId:b,expiresAt:y},this.cache}}async function qc(o){const e={};for(const t of o.spec){const r=await ap(t,o.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function ap(o,e){const t=o.key??o.name;switch(o.source){case"cookie":return lp(t);case"localStorage":return _r(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return _r(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return _r(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return _r(()=>document.querySelector(`meta[name="${cp(t)}"]`)?.content??void 0);case"callback":{const r=e?.[o.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function lp(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===o||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function _r(o){try{return o()}catch{return}}function cp(o){return o.replace(/["\\]/g,"\\$&")}const up=1800;class Hc{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 qc({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const a=(await n.json().catch(()=>({}))).user??{},l=String(a.ext_uid??a.extUid??""),c=String(a.token??a.user_token??a.userToken??"");if(!l)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:a.id,extUid:l,userToken:c,email:typeof a.email=="string"?a.email:void 0,displayName:typeof a.display_name=="string"?a.display_name:typeof a.displayName=="string"?a.displayName:void 0,properties:a.properties&&typeof a.properties=="object"?a.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??up;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 dp=3e4,hp=2e3,fp=100;async function Wc(o){const{descriptor:e}=o,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!o.initToken)throw new Ze("init","No init token supplied to Aikaara.init({token})");return{token:o.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=pp(r);if(!i)throw new Ze("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=mp(r);if(!i)throw new Ze("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=wp(typeof t.origins=="string"?t.origins:""),s=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:dp;return{token:await vp({type:r,key:i,origins:n,timeoutMs:s}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ze("cookie","cookie.name not configured");const i=gp(r);if(!i)throw new Ze("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ze("storage","storage.key not configured");const s=bp(r,i,n);if(!s)throw new Ze("storage",`${r}Storage["${i}"] not set`);return{token:s,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ze("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:hp,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:fp,s=await yp(r,i,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 zc{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 pp(o){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===o)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function mp(o){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(o)??void 0}catch{return}}function gp(o){if(typeof document>"u")return;const e=encodeURIComponent(o),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===o||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function bp(o,e,t){if(!(typeof window>"u"))try{const i=(o==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const s=Vc(n,t);return typeof s=="string"?s:void 0}catch{return}}async function yp(o,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Vc(window,o);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function vp(o){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ze("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ze("postmsg",`timeout after ${o.timeoutMs}ms`))},o.timeoutMs),n=s=>{if(o.origins.length>0&&!o.origins.includes(s.origin))return;const a=s.data;if(!a||typeof a!="object")return;const l=a;if(o.type&&l.type!==o.type)return;const c=l[o.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function wp(o){return o?o.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vc(o,e){if(!e)return o;const t=e.split(".").filter(Boolean);let r=o;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function kp(){const o=typeof crypto<"u"?crypto:null;if(o?.randomUUID)return o.randomUUID();if(o?.getRandomValues){const e=new Uint8Array(16);o.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const xp="aikaara_chat:requestId";function Fo(o,e,t){const r=`${xp}:${o}:${e}`;return t?`${r}:${t}`:r}function Kc(o,e,t){try{return localStorage.getItem(Fo(o,e,t))}catch{return null}}function _p(o,e,t,r){try{localStorage.setItem(Fo(o,e,r),t)}catch{}}function Sp(o,e,t){try{localStorage.removeItem(Fo(o,e,t))}catch{}}async function ko(o,e,t="before-chat"){const r=o.filter(u=>(u.trigger??"before-chat")===t);console.log("[aikaara-chat-sdk] preflight running",r.length,"steps",`(trigger=${t})`);const i={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[u,d]of Object.entries(e.identity))typeof d=="string"&&(i[u]=d);typeof e.serviceType=="string"&&(i.serviceType=e.serviceType),typeof e.userType=="string"&&(i.userType=e.userType);const n=u=>u.replace(/\{(\w+)\}/g,(d,p)=>p in i?i[p]:""),s=u=>{if(typeof u=="string")return n(u);if(Array.isArray(u))return u.map(s);if(u&&typeof u=="object"){const d={};for(const[p,g]of Object.entries(u))d[p]=s(g);return d}return u},a=await Yt(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"),h={accept:"application/json",...d.headers??{}};if((d.authHeader??"session")==="session"){const _=d.authHeaderTemplate??"Bearer {token}";h.authorization=_.replace("{token}",a)}const b={method:g,headers:h};d.body&&(h["content-type"]="application/json",b.body=JSON.stringify(s(d.body)));let y=0,w="",m=0,k=null;for(;;)try{const _=await fetch(p,b);if(_.ok){k=_;break}if(y=_.status,w=await _.text().catch(()=>""),m<c.length&&Ap(y,w)){const E=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} ${g} ${p} → ${y} (transient). Retry #${m} in ${E}ms.`),await new Promise(S=>setTimeout(S,E));continue}const v=`Preflight #${u} ${g} ${p} → ${y} ${w.slice(0,200)}`;if(d.soft){console.warn("[aikaara-chat-sdk]",v);break}throw new Error(v)}catch(_){if(m<c.length){const v=c[m++];console.warn(`[aikaara-chat-sdk] preflight #${u} threw, retry #${m} in ${v}ms`,_),await new Promise(E=>setTimeout(E,v));continue}if(d.soft){console.warn(`[aikaara-chat-sdk] preflight #${u} soft-failed:`,_);break}throw _}if(k&&d.capture&&d.capture.as)try{const _=await k.clone().text();let v=_;try{v=JSON.parse(_)}catch{}if(d.capture.path)for(const E of d.capture.path.split("."))if(v&&typeof v=="object"&&E in v)v=v[E];else{v=void 0;break}if(typeof v=="string"&&v.length>0){let E=v;d.capture.stripPrefix&&E.startsWith(d.capture.stripPrefix)&&(E=E.slice(d.capture.stripPrefix.length)),l[d.capture.as]=E,i[d.capture.as]=E,console.log(`[aikaara-chat-sdk] preflight #${u} captured ${d.capture.as} (${E.slice(0,24)}…)`)}}catch(_){console.warn(`[aikaara-chat-sdk] preflight #${u} capture failed`,_)}}return{captured:l}}async function Ep(o){const e=o.steps??[];return e.some(r=>r.trigger==="on-method-select")?(await ko(e,{sessionToken:o.sessionToken,userId:o.userId,projectId:o.projectId??"",slug:o.slug??"",identity:o.identity,serviceType:o.serviceType,userType:o.userType},"on-method-select")).captured:{}}function Ap(o,e){if(o===503||o===504||o===502)return!0;if(o===401||o===403)return e.trim().length===0;if(o===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Gc(o,e){const t=await fetch(o,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Yc(o,e){return o.replace("{projectId}",e).replace("{uuid}",kp().replace(/-/g,""))}function Jc(o){const e=o._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>xc(r)))}async function Qc(o){const e={...o.config??(o.configUrl?await Gc(o.configUrl,o.configHeaders):{}),...o.overrides??{}};Jc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=o.identity.userId,s=o.conversationScope||void 0,a=o.forceNewConversation?null:Kc(n,i,s),l=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",c=o.conversationId??a??Yc(l,i);(o.conversationId||!a||o.forceNewConversation)&&i&&_p(n,i,c,s);const u=await o.tokenProvider(),d=o.tokenProvider,p=o.historyTokenProvider??d,g=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:u,userId:n,userName:o.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...o.identity.departmentId?{departmentId:o.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:o.identity.senderFullname??o.identity.userName,tokenProvider:d}:void 0,h=o.uploadAdapter??(e.uploadEndpoint?$o({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),b=o.historyAdapter??(e.historyApiBase?nc({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:p}):void 0),y={transport:t,baseUrl:"",userToken:o.userToken??n,conversationId:c,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:o.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:g,tiledeskIdentity:{userId:n,userName:o.identity.userName,departmentId:o.identity.departmentId,senderFullname:o.identity.senderFullname??o.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:h,historyAdapter:b,onError:o.onError,onMessage:o.onMessage},w=document.createElement("aikaara-chat-widget");return w.configure(y),y.title&&w.setAttribute("title",y.title),y.primaryColor&&w.setAttribute("primary-color",y.primaryColor),y.display&&w.setAttribute("display",y.display),y.display==="embed"&&(w.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),o.container.appendChild(w),{widget:w,requestId:c,config:y,destroy(){w.remove()}}}function Ip(o){if(typeof o!="string")return o;const e=document.querySelector(o);if(!e)throw new Error(`mountFromSlug: container "${o}" not found`);return e}async function Xc(o){const e=(o.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(o.slug)}`;let r=null;try{r=await Gc(t,o.configHeaders)}catch(I){if(!o.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${o.slug}" — using fallbackConfig.`,I)}const i={...o.fallbackConfig??{},...r??{},...o.overrides??{}};if(Jc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,P]of Object.entries(i.templates)){const O=`template:${I}`;i.components[O]||!P?.scriptUrl||!P?.render||(i.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:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth,smartEdit:i.smartEdit??n.__aikaara_descriptor__?.smartEdit},!i.auth)throw new Error(`mountFromSlug: widget_configs/${o.slug} descriptor must include "auth" block`);let s=null,a=o.user.id,l=o.user.name,c="",u=o.user.token,d=null;const p=await Yt(o.user.token).catch(()=>""),g=typeof p=="string"&&p.length>0;if(!g&&i.sso?.tokenSource){d=new zc({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:o.user.partnerToken});const I=await d.get();u=async()=>(await d.get()).token,o.user.identity&&!o.user.identity.partnerToken&&(o.user.identity.partnerToken=I.token)}else if(!g&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(o.slug)}/sso_exchange`;s=await new Hc({descriptor:i.sso,providers:o.user.credentialProviders,exchangeUrl:I}).get(),a=s.extUid||a,l=l??s.displayName,c=s.userToken}let h="",b="";if(i.preflight&&i.preflight.length){const I=await ko(i.preflight,{sessionToken:u,userId:a,projectId:i.tiledesk?.projectId??"",slug:o.slug,identity:o.user.identity});if(I.captured.sessionToken){h=I.captured.sessionToken;const P=h;u=()=>P}I.captured.userId&&(a=I.captured.userId),I.captured.requestId&&(b=I.captured.requestId)}const y=new Fc(i.auth,u);if(h){const I=i.tiledesk?.projectId??"",P=I?Kc(a,I):null,O=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",j=P??(I?Yc(O,I):"");y.prime(h,{requestId:j,fullName:l})}const w=await y.get();a=a||w.userId;const m=w.fullName||l||a;window.__aikaara_runtime__={getChatJwt:async()=>(await y.get()).token,getSessionToken:()=>Yt(o.user.token),identity:o.user.identity,slug:o.slug,configBase:e};const k=d&&i.sso?.autoRefresh?async()=>{try{return await d.refresh(),y.reset(),(await y.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,_=i.upload,v=async()=>`Bearer ${_&&"tokenSource"in _&&_.tokenSource==="chat"?(await y.get()).token:await Yt(o.user.token)}`,E=o.hooks?.upload??(_&&_.mode==="presigned-3step"?rc({..._,authHeader:v}):_&&_.mode==="direct"?$o({endpoint:_.endpoint,fieldName:_.fieldName,extraFields:_.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Qc({container:Ip(o.container),config:i,userToken:c||void 0,identity:{userId:a,userName:m,departmentId:o.user.departmentId,senderFullname:m},tokenProvider:async()=>(await y.get()).token,historyTokenProvider:async()=>(await y.get()).token,uploadAdapter:E,historyAdapter:o.hooks?.history,conversationId:w.requestId||b||void 0,conversationScope:o.conversationScope,onError:o.hooks?.onError,onMessage:o.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await y.get()).token:Yt(o.user.token)});return Object.assign(S,{fullName:m,requestId:w.requestId,descriptor:i,async refreshAuth(){y.reset(),await y.get()},async refreshPartnerAuth(){return k?k():null},async runMethodSelectPreflight(I){const P=i.preflight;return!P||!P.length?{}:P.some(j=>j.trigger==="on-method-select")?(await ko(P,{sessionToken:u,userId:a,projectId:i.tiledesk?.projectId??"",slug:o.slug,identity:{...o.user.identity??{},...I?.identity??{}},serviceType:I?.serviceType,userType:I?.userType},"on-method-select")).captured:{}}})}exports.ActionCableClient=wn;exports.AikaaraCallConfirmation=Uc;exports.AikaaraCallUpload=$c;exports.AikaaraChat=Cc;exports.AikaaraChatBubble=dc;exports.AikaaraChatClient=tc;exports.AikaaraChatHeader=hc;exports.AikaaraChatInput=yc;exports.AikaaraChatWidget=uc;exports.AikaaraComparePlans=Oc;exports.AikaaraErrorBanner=kc;exports.AikaaraLinkModal=Pc;exports.AikaaraMessageBubble=bc;exports.AikaaraMessageList=mc;exports.AikaaraModalAction=Ic;exports.AikaaraOptionList=Ec;exports.AikaaraPriceBreakdown=jc;exports.AikaaraSchemaForm=Mc;exports.AikaaraServiceDetails=Rc;exports.AikaaraServicePicker=Nc;exports.AikaaraSlotPicker=Dc;exports.AikaaraSmartEditModal=Lc;exports.AikaaraStreamingMessage=wc;exports.AikaaraSubmitAction=Ac;exports.AikaaraSystemPill=Sc;exports.AikaaraTemplateRenderer=_c;exports.AikaaraTextInput=Tc;exports.AikaaraTypingIndicator=vc;exports.ApiClient=ga;exports.ChannelSubscription=pa;exports.ConnectionManager=ma;exports.ConversationManager=va;exports.EventEmitter=xo;exports.MessageStore=ba;exports.SessionAuthAdapter=Fc;exports.SsoExchangeAdapter=Hc;exports.TiledeskTransport=Ql;exports.TokenDiscoveryError=Ze;exports.TokenDiscoveryReader=zc;exports.clearPersistedConversationId=Sp;exports.collectSsoCredentials=qc;exports.createFetchUploadAdapter=$o;exports.createPresigned3StepUploadAdapter=rc;exports.createTiledeskHistoryAdapter=nc;exports.discoverToken=Wc;exports.extractTiledeskFileEnvelope=ec;exports.inferTiledeskRole=Zl;exports.isTiledeskSelfEcho=Xl;exports.mount=Qc;exports.mountFromSlug=Xc;exports.openInPopupWindow=pc;exports.parseTiledeskTemplate=Do;exports.registerComponents=Bc;exports.runMethodSelectPreflight=Ep;
|