@aikaara/chat-sdk 1.5.2 → 1.5.3
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-BQB_myLX.cjs → AikaaraLinkButton-CBAy6ItK.cjs} +1 -1
- package/dist/{AikaaraLinkButton-DHQbtHiT.mjs → AikaaraLinkButton-DsJc3CEK.mjs} +1 -1
- package/dist/{MountTenant-DYzXut6V.cjs → MountTenant-BEaYaZMk.cjs} +2 -2
- package/dist/{MountTenant-nlS1ZOcJ.mjs → MountTenant-DcEbdQPG.mjs} +4 -5
- package/dist/cdn/aikaara-chat.iife.js +1 -1
- 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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./MountTenant-BEaYaZMk.cjs");class l extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
|
|
2
2
|
<style>
|
|
3
3
|
:host { display: block; margin-top: 8px; }
|
|
4
4
|
button {
|
|
@@ -5,7 +5,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
5
5
|
`+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
|
|
6
6
|
`+ie.prev}function ke(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Te=0;Te<z.length;Te++)Ae[Te]=oe(z,Te)?ie(z[Te],z):""}var Oe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Oe.length;tt++)et["$"+Oe[tt]]=Oe[tt]}for(var qe in z)oe(z,qe)&&(Ee&&String(Number(qe))===qe&&qe<z.length||D&&et["$"+qe]instanceof Symbol||(E.call(/[^\w$]/,qe)?Ae.push(ie(qe,z)+": "+ie(z[qe],z)):Ae.push(qe+": "+ie(z[qe],z))));if(typeof T=="function")for(var rt=0;rt<Oe.length;rt++)ae.call(z,Oe[rt])&&Ae.push("["+ie(Oe[rt])+"]: "+ie(z[Oe[rt]],z));return Ae}return Lr}function Rh(){if(ro)return jr;ro=!0;var s=Gt(),e=yh(),t=Mh(),r=cr(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=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),h=e("Map.prototype.has",!0),p=function(y,w){for(var m=y,_;(_=m.next)!==null;m=_)if(_.key===w)return m.next=_.next,_.next=y.next,y.next=_,_},b=function(y,w){var m=p(y,w);return m&&m.value},d=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},g=function(y,w){return!!p(y,w)};return jr=function(){var y,w,m,_={assert:function(x){if(!_.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return i(y,x)}else if(n){if(w)return c(w,x)}else if(m)return b(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return h(w,x)}else if(m)return g(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),d(m,x,v))}};return _},jr}function Eo(){if(no)return Ur;no=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Ur={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Ur}function dl(){if(io)return Br;io=!0;var s=Eo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var _=[],x=0;x<m.length;++x)typeof m[x]<"u"&&_.push(m[x]);w.obj[w.prop]=_}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},_=0;_<y.length;++_)typeof y[_]<"u"&&(m[_]=y[_]);return m},i=function y(w,m,_){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(_&&(_.plainObjects||_.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,_)),t(w)&&t(m)?(m.forEach(function(v,E){if(e.call(w,E)){var S=w[E];S&&typeof S=="object"&&v&&typeof v=="object"?w[E]=y(S,v,_):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,_):v[E]=S,v},x)},a=function(y,w){return Object.keys(w).reduce(function(m,_){return m[_]=w[_],m},y)},l=function(y,w,m){var _=y.replace(/\+/g," ");if(m==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},c=1024,u=function(y,w,m,_,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var E="",S=0;S<v.length;S+=c){for(var I=v.length>=c?v.slice(S,S+c):v,O=[],P=0;P<I.length;++P){var j=I.charCodeAt(P);if(j===45||j===46||j===95||j===126||j>=48&&j<=57||j>=65&&j<=90||j>=97&&j<=122||x===s.RFC1738&&(j===40||j===41)){O[O.length]=I.charAt(P);continue}if(j<128){O[O.length]=r[j];continue}if(j<2048){O[O.length]=r[192|j>>6]+r[128|j&63];continue}if(j<55296||j>=57344){O[O.length]=r[224|j>>12]+r[128|j>>6&63]+r[128|j&63];continue}P+=1,j=65536+((j&1023)<<10|I.charCodeAt(P)&1023),O[O.length]=r[240|j>>18]+r[128|j>>12&63]+r[128|j>>6&63]+r[128|j&63]}E+=O.join("")}return E},h=function(y){for(var w=[{obj:{o:y},prop:"o"}],m=[],_=0;_<w.length;++_)for(var x=w[_],v=x.obj[x.prop],E=Object.keys(v),S=0;S<E.length;++S){var I=E[S],O=v[I];typeof O=="object"&&O!==null&&m.indexOf(O)===-1&&(w.push({obj:v,prop:I}),m.push(O))}return o(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},b=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},d=function(y,w){return[].concat(y,w)},g=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Br={arrayToObject:n,assign:a,combine:d,compact:h,decode:l,encode:u,isBuffer:b,isRegExp:p,maybeMap:g,merge:i},Br}function Lh(){if(oo)return Dr;oo=!0;var s=Rh(),e=dl(),t=Eo(),r=Object.prototype.hasOwnProperty,o={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,y){return g+"["+y+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,a=function(g,y){i.apply(g,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(g){return l.call(g)},skipNulls:!1,strictNullHandling:!1},h=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},b=function g(y,w,m,_,x,v,E,S,I,O,P,j,T,q,D,U,ae,Y){for(var V=y,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var M=re.get(y);if(F+=1,typeof M<"u"){if(M===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof O=="function"?V=O(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(h(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(O))te=O;else{var we=Object.keys(V);te=P?we.sort(P):we}var K=S?w.replace(/\./g,"%2E"):w,N=_&&n(V)&&V.length===1?K+"[]":K;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],G=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&G===null)){var J=j&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,F);var oe=s();oe.set(p,Y),a(be,g(G,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,O,P,j,T,q,D,U,ae,oe))}}return be},d=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");w=g.format}var m=t.formatters[w],_=u.filter;(typeof g.filter=="function"||n(g.filter))&&(_=g.filter);var x;if(g.arrayFormat in o?x=g.arrayFormat:"indices"in g?x=g.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Dr=function(g,y){var w=g,m=d(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=s(),O=0;O<_.length;++O){var P=_[O];m.skipNulls&&w[P]===null||a(v,b(w[P],P,E,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var 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:""},Dr}function Nh(){if(so)return Fr;so=!0;var s=dl(),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:s.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(p){return p.replace(/&#(\d+);/g,function(b,d){return String.fromCharCode(parseInt(d,10))})},n=function(p,b){return p&&typeof p=="string"&&b.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(p,b){var d={__proto__:null},g=b.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=b.parameterLimit===1/0?void 0:b.parameterLimit,w=g.split(b.delimiter,y),m=-1,_,x=b.charset;if(b.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===a?x="utf-8":w[_]===i&&(x="iso-8859-1"),m=_,_=w.length);for(_=0;_<w.length;++_)if(_!==m){var v=w[_],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,O;S===-1?(I=b.decoder(v,r.decoder,x,"key"),O=b.strictNullHandling?null:""):(I=b.decoder(v.slice(0,S),r.decoder,x,"key"),O=s.maybeMap(n(v.slice(S+1),b),function(j){return b.decoder(j,r.decoder,x,"value")})),O&&b.interpretNumericEntities&&x==="iso-8859-1"&&(O=o(O)),v.indexOf("[]=")>-1&&(O=t(O)?[O]:O);var P=e.call(d,I);P&&b.duplicates==="combine"?d[I]=s.combine(d[I],O):(!P||b.duplicates==="last")&&(d[I]=O)}return d},c=function(p,b,d,g){for(var y=g?b:n(b,d),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&d.parseArrays)m=d.allowEmptyArrays&&(y===""||d.strictNullHandling&&y===null)?[]:[].concat(y);else{m=d.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=d.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!d.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&d.parseArrays&&E<=d.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,b,d,g){if(p){var y=d.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=d.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!d.plainObjects&&e.call(Object.prototype,x)&&!d.allowPrototypes)return;v.push(x)}for(var E=0;d.depth>0&&(_=m.exec(y))!==null&&E<d.depth;){if(E+=1,!d.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!d.allowPrototypes)return;v.push(_[1])}if(_){if(d.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+d.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,b,d,g)}},h=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var b=typeof p.charset>"u"?r.charset:p.charset,d=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(d!=="combine"&&d!=="first"&&d!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:b,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||s.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:d,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 Fr=function(p,b){var d=h(b);if(p===""||p===null||typeof p>"u")return d.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?l(p,d):p,y=d.plainObjects?Object.create(null):{},w=Object.keys(g),m=0;m<w.length;++m){var _=w[m],x=u(_,g[_],d,typeof p=="string");y=s.merge(y,x,d)}return d.allowSparse===!0?y:s.compact(y)},Fr}function jh(){if(ao)return $r;ao=!0;var s=Lh(),e=Nh(),t=Eo();return $r={formats:t,parse:e,stringify:s},$r}function Uh(){if(lo)return xt;lo=!0;var s=kt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
7
|
`," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=jh();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("?"),O=I!==-1&&I<v.indexOf("#")?"?":"#",P=v.split(O),j=/\\/g;P[0]=P[0].replace(j,"/"),v=P.join(O);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var q=o.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&d[D])&&(T=T.substr(2),this.slashes=!0)}if(!d[D]&&(ae||D&&!g[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var V=0;V<l.length;V++){var re=T.indexOf(l[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,be=Q.length;V<be;V++){var te=Q[V];if(te&&!te.match(h)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(h)){var ne=Q.slice(0,V),W=Q.slice(V+1),G=te.match(p);G&&(ne.push(G[1]),W.unshift(G[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!b[U])for(var V=0,be=a.length;V<be;V++){var oe=a[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),g[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",de=this.search||"";this.path=J+de}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||"",O=!1,P="";this.host?O=v+this.host:this.hostname&&(O=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(O+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(P=y.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var j=this.search||P&&"?"+P||"";return E&&E.substr(-1)!==":"&&(E+=":"),this.slashes||(!E||g[E])&&O!==!1?(O="//"+(O||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):O||(O=""),I&&I.charAt(0)!=="#"&&(I="#"+I),j&&j.charAt(0)!=="?"&&(j="?"+j),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),j=j.replace("#","%23"),E+O+S+j+I};function _(v,E){return w(v,!1,!0).resolve(E)}e.prototype.resolve=function(v){return this.resolveObject(w(v,!1,!0)).format()};function x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,I=Object.keys(this),O=0;O<I.length;O++){var P=I[O];S[P]=this[P]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var j=Object.keys(v),T=0;T<j.length;T++){var q=j[T];q!=="protocol"&&(S[q]=v[q])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!d[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||Q[0]==="")),F)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Q=be;else if(be.length)Q||(Q=[]),Q.pop(),Q=Q.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,W=Q.length;W>=0;W--)K=Q[W],K==="."?Q.splice(W,1):K===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},xt.parse=w,xt.resolve=_,xt.resolveObject=x,xt.format=m,xt.Url=e,xt}function fl(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Wr?Bh(s):Dh(s)}function Bh(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Al,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<Sl||r>El||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Dh(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.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 pl(s){let e=eo.resolve(s),t=s.charCodeAt(s.length-1);(t===xl||Wr&&t===kl)&&e[e.length-1]!==eo.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Il,"%25")),!Wr&&e.includes("\\")&&(e=e.replace(Tl,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(Cl,"%0A")),e.includes("\r")&&(e=e.replace(Ol,"%0D")),e.includes(" ")&&(e=e.replace(Pl,"%09")),r.pathname=e,r}var ml,Lr,to,Nr,jr,ro,Ur,no,Br,io,Dr,oo,Fr,so,$r,ao,xt,lo,ze,Fs,gl,bl,yl,vl,wl,_l,kl,xl,Sl,El,Wr,Al,Il,Tl,Cl,Ol,Pl,Fh=Je(()=>{le(),ue(),ce(),nh(),vh(),Ph(),ul(),ml=Object.freeze(Object.create(null)),Lr={},to=!1,Nr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,$r={},ao=!1,xt={},lo=!1,ze=Uh(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Fs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=pl,ze.fileURLToPath=fl,gl=ze.Url,bl=ze.format,yl=ze.resolve,vl=ze.resolveObject,wl=ze.parse,_l=ze.URL,kl=92,xl=47,Sl=97,El=122,Wr=Fs==="win32",Al=/\//g,Il=/%/g,Tl=/\\/g,Cl=/\n/g,Ol=/\r/g,Pl=/\t/g}),$h=pe((s,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")}}),Ao=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=jt(),t=($e(),Me(Fe));function r(n,i){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",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,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,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),pr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=($e(),Me(Fe)),r=e($h()),o=e(pt()),n=jt(),i=e(Qr()),a=Ao(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function d(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=d(w,m),I=P(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new a.BufferedDuplex(m,I,S),O?S.addEventListener("open",j):S.onopen=j),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=y}),Io={};zt(Io,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Ml,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ml,Rl=Je(()=>{le(),ue(),ce(),Ml={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),Ll=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),$s=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((Rl(),Me(Io))),r=e(pt()),o=e(Ll()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),Nl={};zt(Nl,{default:()=>jl});var jl,qh=Je(()=>{le(),ue(),ce(),jl={}}),qs=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(qh(),Me(Nl)),r=e((Rl(),Me(Io))),o=e(pt()),n=e(Ll()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let d=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:d})}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,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=a(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};s.default=l}),Hs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i;function a(){let p=new t.Transform;return p._write=(b,d,g)=>{o.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{o.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let d=p.protocol==="wxs"?"wss":"ws",g=`${d}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${d}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let d=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);o=wx.connectSocket({url:g,protocols:[d]}),n=a(),i=new r.BufferedDuplex(b,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=h}),Ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(d,g,y)=>{o.sendSocketMessage({data:d.buffer,success(){y()},fail(){y(new Error)}})},b._flush=d=>{o.closeSocket({success(){d()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,d){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,d)),y}function h(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(b=>{if(typeof b.data=="string"){let d=e.Buffer.from(b.data,"base64");n.push(d)}else{let d=new FileReader;d.addEventListener("load",()=>{if(d.result instanceof ArrayBuffer){n.push(e.Buffer.from(d.result));return}n.push(e.Buffer.from(d.result,"utf-8"))}),d.readAsArrayBuffer(b.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(b=>{i.destroy(b)}))}var p=(b,d)=>{if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");let g=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";c(d);let y=u(d,b);return o=d.my,o.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(d,n,o),h(),i};s.default=p}),Hh=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Fh(),Me(hl))),o=e(_i()),n=e(Qr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,d]=p;h.username=b,h.password=d}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=pr().streamBuilder,a.wss=pr().streamBuilder,a.mqtt=$s().default,a.tcp=$s().default,a.ssl=qs().default,a.tls=a.ssl,a.mqtts=qs().default):(a.ws=pr().browserStreamBuilder,a.wss=pr().browserStreamBuilder,a.wx=Hs().default,a.wxs=Hs().default,a.ali=Ws().default,a.alis=Ws().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&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 b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let d=new o.default(b,p);return d.on("error",()=>{}),d}function u(h,p,b=!0){return new Promise((d,g)=>{let y=c(h,p),w={connect:_=>{m(),d(y)},end:()=>{m(),d(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}s.default=c}),zs=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(b,d,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(d,g);(!w||("get"in w?!d.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return d[g]}}),Object.defineProperty(b,y,w)}:function(b,d,g,y){y===void 0&&(y=g),b[y]=d[g]}),t=s&&s.__setModuleDefault||(Object.create?function(b,d){Object.defineProperty(b,"default",{enumerable:!0,value:d})}:function(b,d){b.default=d}),r=s&&s.__importStar||(function(){var b=function(d){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(d)};return function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var y=b(d),w=0;w<y.length;w++)y[w]!=="default"&&e(g,d,y[w]);return t(g,d),g}})(),o=s&&s.__exportStar||function(b,d){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(d,g)&&e(d,b,g)},n=s&&s.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Xa());s.DefaultMessageIdProvider=a.default;var l=n(th());s.UniqueMessageIdProvider=l.default;var c=n(Na());s.Store=c.default;var u=r(Hh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ol());s.KeepaliveManager=h.default,s.Client=i.default,o(_i(),s),o(Kt(),s),o(La(),s);var p=Yr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Wh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,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(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(zs());s.default=n,o(zs(),s)});const zh=Wh();const Vh={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}/#"},Kh=300,Gh={templateId:"7",type:"link",isDeepLink:!0},Yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ul{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={...Vh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=h=>{a||(a=!0,clearTimeout(u),h())},c=(h,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=zh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),a||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Gh,...this.config.fileTemplate??{},...Jh(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Kh){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:h,raw:o};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Yh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Jh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Bl(s,e){return(s.sender??"").toString()===e}function Dl(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function To(s){const e={raw:s},t=s.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 s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Fl(s){const e=To(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Vs(s,e,t){const r=Dl(s,t),o=To(s),n=Fl(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Qh(s.status):"delivered",h={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(h.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:o}}function Qh(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class $l extends fo{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 ra(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new na,this.conversationManager=new oa(e.conversationId),this.usesAikaara()&&(this.connection=new ta(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 Ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Vs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(h){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",h)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Vs(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Bl(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ks={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(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Zh(s,e,t){const r=Xh(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Ks[r]?Ks[r]:t}function rn(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ed(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function ql(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Zh(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=rn(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=ed(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const d=s.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):b,g=await fetch(d,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(rn(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:s.viewerTemplate?rn(s.viewerTemplate,i):b.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Co(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const td="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Hl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??td;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const rd="^[A-Z]{4}[0-9]{5}[A-Z]$",nd="^[A-Z]{4}0[A-Z0-9]{6}$",id={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:rd,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"},od={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"},sd={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"},ad={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},ld={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:nd,maxLength:11}]}],submitLabel:"Save"},cd=[id,ad,od,sd,ld];function ud(s,e){const t=s||{},r={userId:Yt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=co(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Pe(t.bizName)!==void 0||o>0;r.businessName=Pe(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Pe(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Pe(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Pe(t.bankAccountNumber),r.bankIfscCode=Pe(t.bankIfscCode),(Pe(t.bankAccountNumber)||Pe(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Pe(t.bankAccountNumber),bankIfscCode:Pe(t.bankIfscCode)}]);const a={description:Pe(t.immovableAssetDescription),flatNo:Pe(t.immovableAssetFlatNo),area:Pe(t.immovableAssetArea),pinCode:Pe(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=nn(t.hpDetails,hd);l.length&&(r.hpDetails=l);const c=nn(t.salaryDetails,dd);if(c.length){r.salaryIncome=c;const u=nn(t.salaryDetails,p=>({grossSalary:Ie(p.grossSalary),employerName:Pe(p.employerName)}));u.length&&(r.salary=u);const h=Wl(t.salaryDetails)[0]??{};r.hraAmount=Ie(h.hraReceived),r.leaveTravelAllowanceAmount=Ie(h.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(h.leaveEncashment),r.anyOtherAllowanceAmount=Ie(h.anyOtherAllowance),r.salaryIncomeFlag=!0}return zr(r)}function hd(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Pe(s.loanTakenFrom),bankOrInstituteName:Pe(s.lenderName),loanAccountNo:Pe(s.loanAccountNumber),loanSanctionDate:yd(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Pe(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:co(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Pe(s.housePropertyAddress),housePropertyPincode:Pe(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Pe(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:co(s.hasCoOwnedProperty),coOwnerName:Pe(s.coOwnerName),coOwnerPan:Pe(s.coOwnerPan),coOwnerShare:Pe(s.coOwnerShare),loanDetails:t?[e]:void 0}}function dd(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Pe(s.employerName),employerTan:Pe(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function fd(s,e){const t=[];for(const r of s){const o=Pe(r.employerName),n=Pe(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function pd(s,e){const t=Pe(s.aadhaarNumber),r=Pe(s.bankAccountNumber),o=Pe(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function md(s,e){return{userId:Yt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function gd(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,cryptoSellValue:t??0,cryptoPurchaseAmount:r??0,vdaPurchaseCost:r??0}}function bd(s,e){const t=(o,n,i,a)=>{const l=Pe(s[o]),c=Pe(s[n]),u=Ie(s[i]),h=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&h===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:h??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Yt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Pe(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function co(s){return s===!0||s===!1?s:void 0}function yd(s){const e=Pe(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Wl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function nn(s,e){return Wl(s).map(t=>zr(e(t))).filter(t=>t!==void 0)}function zr(s){if(Array.isArray(s)){const e=s.map(zr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=zr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function vd(s){const e=s&&typeof s=="object"?s:{},t={},r=De(e.employers),o=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(h=>{const p=on(h.salary),b=on(h.perquisites),d=on(h.profitsInLieuOfSalaryType),g=p+b+d,y=_d(h.allowance);return{employerName:Re(h.employerName),employerTan:Re(h.employerTAN),basicSalary:p||void 0,grossSalary:g||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:wd(h,o,r)??Ne(h.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(h=>{const p=De(h.loanDetails),b=p.length?p[0]:void 0,d=Ne(h.grossAnnualRentReceived),g=p.length?p.reduce((x,v)=>x+(Ne(v.interest)??0),0):void 0,y=De(h.tenant),w=De(h.coOwners),m=y[0],_=w[0];return{typeOfHouseProperty:Re(h.propertyType),loanTakenFrom:Re(b?.loanTakenFrom),lenderName:Re(b?.bankOrInstituteName),loanAccountNumber:Re(b?.loanAccountNo),sanctionDate:Re(b?.loanSanctionDate),totalLoanAmount:Ne(b?.totalLoanAmount),outstandingAmount:Ne(b?.loanOutstandingAmount),homeLoanInterest:g,homeLoanPrinciple:void 0,housePropertyAddress:Re(h.address),housePropertyPincode:Re(h.pinCode),rentalIncome:d,nameOfTenant:Re(m?.name),propertyTax:Ne(h.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Re(_?.name),coOwnerPan:Re(_?.panNumber),coOwnerShare:Ne(_?.share)?.toString()}})),t.us80cAmount=Tt(De(e.deductionUS80CDetails).map(h=>Ne(h.amount))),t.us80dForSelfAndFamilyAmount=Tt(De(e.deductionUS80DDetails).map(h=>Ne(h.healthInsuranceAmount)));const i=De(e.incomes),a=h=>Tt(i.filter(p=>Re(p.incomeType)===h).map(p=>Ne(p.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Tt(De(e.dividendIncomes).map(h=>Ne(h.income)));const l=e.business;if(l){const h=De(l.presumptiveIncomes),p=g=>{const y=De(g.incomes),w=m=>Ne(y.find(_=>Re(_.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Re(g.businessType)?.toUpperCase().includes("PROFESSION")},b=g=>h.find(y=>p(y)===g),d=(g,y)=>{if(!g)return;const w=De(g.incomes),m=x=>Ne(w.find(v=>Re(v.incomeType)===x)?.receipts),_=m("BANK")||m("ANY_OTHER");t[y.name]=Re(g.businessType),t[y.nature]=Re(g.natureOfBusiness),t[y.bank]=_||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Tt(w.map(x=>Ne(x.presumptiveIncome)))||void 0};d(b(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),d(b(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=De(e.capitalGain).filter(h=>Re(h.assetType)?.toUpperCase()==="VDA").flatMap(h=>De(h.assetDetails));c.length&&(t.cryptoSellPrice=Tt(c.map(h=>Ne(h.sellValue))),t.cryptoPurchasePrice=Tt(c.map(h=>Ne(h.purchaseCost)))),t.agricultureIncome=Ne(e.agriculturalDetails?.income),t.aadhaarNumber=Re(e.aadharNumber);const u=De(e.bankDetails)[0];return u&&(t.bankAccountNumber=Re(u.accountNumber),t.bankIfscCode=Re(u.ifsCode)),zl(t)}function on(s){return De(s).reduce((e,t)=>e+(Ne(t.taxableAmount)??0),0)}function wd(s,e,t){if(!e.length)return;const r=Re(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Re(n.deductorTAN)?.trim().toUpperCase()===r)return Ne(n.totalTdsDeposited)}const o=Re(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Re(n.deductorName)?.trim().toLowerCase()===o)return Ne(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ne(e[0].totalTdsDeposited)}function _d(s){const e=De(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ne(i.exemptAmount)??Ne(i.allowanceAmount);switch(Re(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ne(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Tt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ne(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Re(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function zl(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?zl(o):o):e[t]=r);return e}function sn(){if(typeof window>"u")return null;const s=window,e=s.__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=s.__aikaara_descriptor__??{},r=Cd(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=Od(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):Md(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Pd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Rd(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function kd(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return vd(Oo(await r.json().catch(()=>({}))))}async function xd(s,e){const t=await s.getToken(),r=s.userId,o={...ud(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Oo(await a.json().catch(()=>({})))}async function Sd(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function Ed(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Ad(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Id(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Td(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function ur(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Oo(await n.json().catch(()=>({})))}function Cd(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.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 Od(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);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 Pd(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function Md(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Oo(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Rd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class Ld{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new $l(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:cd,data:{}});const t=sn();if(!(!t||!t.baseUrl))try{const r=await kd(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=sn();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=fd(n,o);i&&await Sd(r,i)}else if(e==="bank-details"){const n=pd(t,o);n&&await Ed(r,n)}else if(e==="other-sources")await Ad(r,md(t,o));else if(e==="business-profession"){const n=bd(t,o);n&&await Id(r,n)}else if(e==="crypto-income"){const n=gd(t,o);n&&await Td(r,n)}}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=sn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await xd(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 Vl 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||jc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Mo,position:this.getAttribute("position")||this._config.position||Nc,width:Number(this.getAttribute("width"))||this._config.width||Pc,height:Number(this.getAttribute("height"))||this._config.height||Mc,fontFamily:this._config.fontFamily||Lc,borderRadius:this._config.borderRadius??Rc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ro,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||Uc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
8
|
+
`)&&(e=e.replace(Cl,"%0A")),e.includes("\r")&&(e=e.replace(Ol,"%0D")),e.includes(" ")&&(e=e.replace(Pl,"%09")),r.pathname=e,r}var ml,Lr,to,Nr,jr,ro,Ur,no,Br,io,Dr,oo,Fr,so,$r,ao,xt,lo,ze,Fs,gl,bl,yl,vl,wl,_l,kl,xl,Sl,El,Wr,Al,Il,Tl,Cl,Ol,Pl,Fh=Je(()=>{le(),ue(),ce(),nh(),vh(),Ph(),ul(),ml=Object.freeze(Object.create(null)),Lr={},to=!1,Nr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,$r={},ao=!1,xt={},lo=!1,ze=Uh(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Fs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=pl,ze.fileURLToPath=fl,gl=ze.Url,bl=ze.format,yl=ze.resolve,vl=ze.resolveObject,wl=ze.parse,_l=ze.URL,kl=92,xl=47,Sl=97,El=122,Wr=Fs==="win32",Al=/\//g,Il=/%/g,Tl=/\\/g,Cl=/\n/g,Ol=/\r/g,Pl=/\t/g}),$h=pe((s,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")}}),Ao=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=jt(),t=($e(),Me(Fe));function r(n,i){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",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,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,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),pr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=($e(),Me(Fe)),r=e($h()),o=e(pt()),n=jt(),i=e(Qr()),a=Ao(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let _=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(_=w.transformWsUrl(_,w,m)),_}function h(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.default&&!w.forceNativeWebSocket&&w.protocol==="wss"&&c.forEach(_=>{Object.prototype.hasOwnProperty.call(w,_)&&!Object.prototype.hasOwnProperty.call(w.wsOptions,_)&&(m.wsOptions[_]=w[_])}),m}function p(w){let m=h(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);m.hostname=_.hostname,m.port||(m.port=Number(_.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function b(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function d(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var g=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=b(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=g;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=d(w,m),I=P(m,U,ae);m.objectMode||(I._writev=a.writev.bind(I)),I.on("close",()=>{S.close()});let O=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new a.BufferedDuplex(m,I,S),O?S.addEventListener("open",j):S.onopen=j),O?(S.addEventListener("close",T),S.addEventListener("error",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function P(Y,V,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function j(){l("WebSocket onOpen"),_ instanceof a.BufferedDuplex&&_.socketReady()}function T(Y){l("WebSocket onClose",Y),_.end(),_.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,_.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return _};s.browserStreamBuilder=y}),Io={};zt(Io,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>Ml,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ml,Rl=Je(()=>{le(),ue(),ce(),Ml={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),Ll=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),$s=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((Rl(),Me(Io))),r=e(pt()),o=e(Ll()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,h=l.hostname;return n("port %d and host %s",c,h),t.default.createConnection({port:c,host:h,path:u})};s.default=i}),Nl={};zt(Nl,{default:()=>jl});var jl,qh=Je(()=>{le(),ue(),ce(),jl={}}),qs=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(qh(),Me(Nl)),r=e((Rl(),Me(Io))),o=e(pt()),n=e(Ll()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:h,socksProxy:p,...b}=c;if(p!==void 0){let d=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...b,socket:d})}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,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=a(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(b){u.rejectUnauthorized&&c.emit("error",b),h.end()}return h.on("error",p),h};s.default=l}),Hs=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i;function a(){let p=new t.Transform;return p._write=(b,d,g)=>{o.send({data:b.buffer,success(){g()},fail(y){g(new Error(y))}})},p._flush=b=>{o.close({success(){b()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,b){let d=p.protocol==="wxs"?"wss":"ws",g=`${d}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${d}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,b)),g}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:b}=p;b instanceof ArrayBuffer?b=e.Buffer.from(b):b=e.Buffer.from(b,"utf8"),n.push(b)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let b=new Error(p.errMsg);i.destroy(b)})}var h=(p,b)=>{if(b.hostname=b.hostname||b.host,!b.hostname)throw new Error("Could not determine host. Specify host manually.");let d=b.protocolId==="MQIsdp"&&b.protocolVersion===3?"mqttv3.1":"mqtt";l(b);let g=c(b,p);o=wx.connectSocket({url:g,protocols:[d]}),n=a(),i=new r.BufferedDuplex(b,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=h}),Ws=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=($e(),Me(Fe)),t=jt(),r=Ao(),o,n,i,a=!1;function l(){let b=new t.Transform;return b._write=(d,g,y)=>{o.sendSocketMessage({data:d.buffer,success(){y()},fail(){y(new Error)}})},b._flush=d=>{o.closeSocket({success(){d()}})},b}function c(b){b.hostname||(b.hostname="localhost"),b.path||(b.path="/"),b.wsOptions||(b.wsOptions={})}function u(b,d){let g=b.protocol==="alis"?"wss":"ws",y=`${g}://${b.hostname}${b.path}`;return b.port&&b.port!==80&&b.port!==443&&(y=`${g}://${b.hostname}:${b.port}${b.path}`),typeof b.transformWsUrl=="function"&&(y=b.transformWsUrl(y,b,d)),y}function h(){a||(a=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(b=>{if(typeof b.data=="string"){let d=e.Buffer.from(b.data,"base64");n.push(d)}else{let d=new FileReader;d.addEventListener("load",()=>{if(d.result instanceof ArrayBuffer){n.push(e.Buffer.from(d.result));return}n.push(e.Buffer.from(d.result,"utf-8"))}),d.readAsArrayBuffer(b.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(b=>{i.destroy(b)}))}var p=(b,d)=>{if(d.hostname=d.hostname||d.host,!d.hostname)throw new Error("Could not determine host. Specify host manually.");let g=d.protocolId==="MQIsdp"&&d.protocolVersion===3?"mqttv3.1":"mqtt";c(d);let y=u(d,b);return o=d.my,o.connectSocket({url:y,protocols:g}),n=l(),i=new r.BufferedDuplex(d,n,o),h(),i};s.default=p}),Hh=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Fh(),Me(hl))),o=e(_i()),n=e(Qr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,b,d]=p;h.username=b,h.password=d}else h.username=h.auth}function c(h,p){if(i("connecting to an MQTT broker..."),typeof h=="object"&&!p&&(p=h,h=""),p=p||{},h&&typeof h=="string"){let g=r.default.parse(h,!0),y={};if(g.port!=null&&(y.port=Number(g.port)),y.host=g.hostname,y.query=g.query,y.auth=g.auth,y.protocol=g.protocol,y.path=g.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!p.forceNativeWebSocket?(a.ws=pr().streamBuilder,a.wss=pr().streamBuilder,a.mqtt=$s().default,a.tcp=$s().default,a.ssl=qs().default,a.tls=a.ssl,a.mqtts=qs().default):(a.ws=pr().browserStreamBuilder,a.wss=pr().browserStreamBuilder,a.wx=Hs().default,a.wxs=Hs().default,a.ali=Ws().default,a.alis=Ws().default)),!a[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>g&&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 b(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),a[p.protocol](g,p)}let d=new o.default(b,p);return d.on("error",()=>{}),d}function u(h,p,b=!0){return new Promise((d,g)=>{let y=c(h,p),w={connect:_=>{m(),d(y)},end:()=>{m(),d(y)},error:_=>{m(),y.end(),g(_)}};b===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}s.default=c}),zs=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(b,d,g,y){y===void 0&&(y=g);var w=Object.getOwnPropertyDescriptor(d,g);(!w||("get"in w?!d.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return d[g]}}),Object.defineProperty(b,y,w)}:function(b,d,g,y){y===void 0&&(y=g),b[y]=d[g]}),t=s&&s.__setModuleDefault||(Object.create?function(b,d){Object.defineProperty(b,"default",{enumerable:!0,value:d})}:function(b,d){b.default=d}),r=s&&s.__importStar||(function(){var b=function(d){return b=Object.getOwnPropertyNames||function(g){var y=[];for(var w in g)Object.prototype.hasOwnProperty.call(g,w)&&(y[y.length]=w);return y},b(d)};return function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var y=b(d),w=0;w<y.length;w++)y[w]!=="default"&&e(g,d,y[w]);return t(g,d),g}})(),o=s&&s.__exportStar||function(b,d){for(var g in b)g!=="default"&&!Object.prototype.hasOwnProperty.call(d,g)&&e(d,b,g)},n=s&&s.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Xa());s.DefaultMessageIdProvider=a.default;var l=n(th());s.UniqueMessageIdProvider=l.default;var c=n(Na());s.Store=c.default;var u=r(Hh());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(ol());s.KeepaliveManager=h.default,s.Client=i.default,o(_i(),s),o(Kt(),s),o(La(),s);var p=Yr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Wh=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,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(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(zs());s.default=n,o(zs(),s)});const zh=Wh();const Vh={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}/#"},Kh=300,Gh={templateId:"7",type:"link",isDeepLink:!0},Yh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ul{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={...Vh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=h=>{a||(a=!0,clearTimeout(u),h())},c=(h,p)=>{a||(this.debugLog("CONNECT_FAIL",{reason:h,message:p?.message}),l(()=>i(p??new Error(`tiledesk-transport: ${h}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=zh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const h=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(h),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:h})}}),this.client.on("message",(h,p)=>{this.dispatchInbound(h,p)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),a||c("mqtt-error",h)}),this.client.on("disconnect",h=>{this.debugLog("DISCONNECT",{reasonCode:h?.reasonCode,properties:h?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",h=>{(h.cmd==="subscribe"||h.cmd==="unsubscribe"||h.cmd==="pingreq")&&this.debugLog(h.cmd.toUpperCase(),{topic:h.topic,packetId:h.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Gh,...this.config.fileTemplate??{},...Jh(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=Kh){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",h=typeof o.status=="number"?o.status:Number(o.status??0),p={conversationId:c,messageId:u,status:h,raw:o};this.statusUpdateHandlers.forEach(b=>b(p)),this.messageHandlers.forEach(b=>b(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Yh,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Jh(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function Bl(s,e){return(s.sender??"").toString()===e}function Dl(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function To(s){const e={raw:s},t=s.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 s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Fl(s){const e=To(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Vs(s,e,t){const r=Dl(s,t),o=To(s),n=Fl(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Qh(s.status):"delivered",h={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(h.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(h.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:h,template:o}}function Qh(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class $l extends fo{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 ra(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new na,this.conversationManager=new oa(e.conversationId),this.usesAikaara()&&(this.connection=new ta(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 Ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Vs(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(h){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",h)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Vs(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(Bl(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Ks={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(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Zh(s,e,t){const r=Xh(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Ks[r]?Ks[r]:t}function rn(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ed(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function ql(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Zh(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=rn(c,i),h=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),b=ed(p,e);if(!b)throw new Error(`Sign response missing path "${e}"`);const d=s.s3HostRewrite?b.replace(/^https:\/\/[^/]+/i,s.s3HostRewrite):b,g=await fetch(d,{method:"PUT",headers:{"content-type":n},body:t});if(!g.ok){const w=await g.text().catch(()=>"");throw new Error(`S3 PUT failed: ${g.status} ${w.slice(0,200)}`)}if(s.registerEndpoint){const w=JSON.parse(rn(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.registerEndpoint,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify(w)});if(!m.ok){const _=await m.text().catch(()=>"");throw new Error(`Register failed: ${m.status} ${_.slice(0,200)}`)}}return{url:s.viewerTemplate?rn(s.viewerTemplate,i):b.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function Co(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[p,b]of Object.entries(n))r.append(p,b);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.parseResponse(l,t);const c=l,u=c.url??c.fileUrl??c.publicUrl,h=c.fileName??c.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:h,cloudFileId:typeof c.cloudFileId=="string"?c.cloudFileId:void 0,relativePath:typeof c.path=="string"?c.path:void 0,contentType:typeof c.contentType=="string"?c.contentType:void 0,byteSize:typeof c.byteSize=="number"?c.byteSize:void 0,meta:c}}}}const td="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Hl(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??td;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const p=await s.getToken();p&&(l.authorization=p)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.parseResponse(u);if(Array.isArray(u))return u;const h=u;if(h&&Array.isArray(h.result))return h.result;if(!c.ok)throw new Error(`History fetch failed: ${c.status} ${c.statusText}`);return[]}}}const rd="^[A-Z]{4}[0-9]{5}[A-Z]$",nd="^[A-Z]{4}0[A-Z0-9]{6}$",id={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:rd,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"},od={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"},sd={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"},ad={id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},ld={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:nd,maxLength:11}]}],submitLabel:"Save"},cd=[id,ad,od,sd,ld];function ud(s,e){const t=s||{},r={userId:Yt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=co(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Pe(t.bizName)!==void 0||o>0;r.businessName=Pe(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Pe(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Pe(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Pe(t.bankAccountNumber),r.bankIfscCode=Pe(t.bankIfscCode),(Pe(t.bankAccountNumber)||Pe(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Pe(t.bankAccountNumber),bankIfscCode:Pe(t.bankIfscCode)}]);const a={description:Pe(t.immovableAssetDescription),flatNo:Pe(t.immovableAssetFlatNo),area:Pe(t.immovableAssetArea),pinCode:Pe(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=nn(t.hpDetails,hd);l.length&&(r.hpDetails=l);const c=nn(t.salaryDetails,dd);if(c.length){r.salaryIncome=c;const u=nn(t.salaryDetails,p=>({grossSalary:Ie(p.grossSalary),employerName:Pe(p.employerName)}));u.length&&(r.salary=u);const h=Wl(t.salaryDetails)[0]??{};r.hraAmount=Ie(h.hraReceived),r.leaveTravelAllowanceAmount=Ie(h.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(h.leaveEncashment),r.anyOtherAllowanceAmount=Ie(h.anyOtherAllowance),r.salaryIncomeFlag=!0}return zr(r)}function hd(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Pe(s.loanTakenFrom),bankOrInstituteName:Pe(s.lenderName),loanAccountNo:Pe(s.loanAccountNumber),loanSanctionDate:yd(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Pe(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:co(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Pe(s.housePropertyAddress),housePropertyPincode:Pe(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Pe(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:co(s.hasCoOwnedProperty),coOwnerName:Pe(s.coOwnerName),coOwnerPan:Pe(s.coOwnerPan),coOwnerShare:Pe(s.coOwnerShare),loanDetails:t?[e]:void 0}}function dd(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Pe(s.employerName),employerTan:Pe(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function fd(s,e){const t=[];for(const r of s){const o=Pe(r.employerName),n=Pe(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function pd(s,e){const t=Pe(s.aadhaarNumber),r=Pe(s.bankAccountNumber),o=Pe(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function md(s,e){return{userId:Yt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function gd(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:Yt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function bd(s,e){const t=(o,n,i,a)=>{const l=Pe(s[o]),c=Pe(s[n]),u=Ie(s[i]),h=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&h===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:h??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:Yt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function Yt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Pe(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function co(s){return s===!0||s===!1?s:void 0}function yd(s){const e=Pe(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Wl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function nn(s,e){return Wl(s).map(t=>zr(e(t))).filter(t=>t!==void 0)}function zr(s){if(Array.isArray(s)){const e=s.map(zr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=zr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function vd(s){const e=s&&typeof s=="object"?s:{},t={},r=De(e.employers),o=De(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(h=>{const p=on(h.salary),b=on(h.perquisites),d=on(h.profitsInLieuOfSalaryType),g=p+b+d,y=_d(h.allowance);return{employerName:Re(h.employerName),employerTan:Re(h.employerTAN),basicSalary:p||void 0,grossSalary:g||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:wd(h,o,r)??Ne(h.totalTdsDeposited)}}));const n=De(e.houseProperties);n.length&&(t.hpDetails=n.map(h=>{const p=De(h.loanDetails),b=p.length?p[0]:void 0,d=Ne(h.grossAnnualRentReceived),g=p.length?p.reduce((x,v)=>x+(Ne(v.interest)??0),0):void 0,y=De(h.tenant),w=De(h.coOwners),m=y[0],_=w[0];return{typeOfHouseProperty:Re(h.propertyType),loanTakenFrom:Re(b?.loanTakenFrom),lenderName:Re(b?.bankOrInstituteName),loanAccountNumber:Re(b?.loanAccountNo),sanctionDate:Re(b?.loanSanctionDate),totalLoanAmount:Ne(b?.totalLoanAmount),outstandingAmount:Ne(b?.loanOutstandingAmount),homeLoanInterest:g,homeLoanPrinciple:void 0,housePropertyAddress:Re(h.address),housePropertyPincode:Re(h.pinCode),rentalIncome:d,nameOfTenant:Re(m?.name),propertyTax:Ne(h.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Re(_?.name),coOwnerPan:Re(_?.panNumber),coOwnerShare:Ne(_?.share)?.toString()}})),t.us80cAmount=Tt(De(e.deductionUS80CDetails).map(h=>Ne(h.amount))),t.us80dForSelfAndFamilyAmount=Tt(De(e.deductionUS80DDetails).map(h=>Ne(h.healthInsuranceAmount)));const i=De(e.incomes),a=h=>Tt(i.filter(p=>Re(p.incomeType)===h).map(p=>Ne(p.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Tt(De(e.dividendIncomes).map(h=>Ne(h.income)));const l=e.business;if(l){const h=De(l.presumptiveIncomes),p=g=>{const y=De(g.incomes),w=m=>Ne(y.find(_=>Re(_.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Re(g.businessType)?.toUpperCase().includes("PROFESSION")},b=g=>h.find(y=>p(y)===g),d=(g,y)=>{if(!g)return;const w=De(g.incomes),m=x=>Ne(w.find(v=>Re(v.incomeType)===x)?.receipts),_=m("BANK")||m("ANY_OTHER");t[y.name]=Re(g.businessType),t[y.nature]=Re(g.natureOfBusiness),t[y.bank]=_||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Tt(w.map(x=>Ne(x.presumptiveIncome)))||void 0};d(b(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),d(b(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=De(e.capitalGain).filter(h=>Re(h.assetType)?.toUpperCase()==="VDA").flatMap(h=>De(h.assetDetails));c.length&&(t.cryptoSellPrice=Tt(c.map(h=>Ne(h.sellValue))),t.cryptoPurchasePrice=Tt(c.map(h=>Ne(h.purchaseCost)))),t.agricultureIncome=Ne(e.agriculturalDetails?.income),t.aadhaarNumber=Re(e.aadharNumber);const u=De(e.bankDetails)[0];return u&&(t.bankAccountNumber=Re(u.accountNumber),t.bankIfscCode=Re(u.ifsCode)),zl(t)}function on(s){return De(s).reduce((e,t)=>e+(Ne(t.taxableAmount)??0),0)}function wd(s,e,t){if(!e.length)return;const r=Re(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Re(n.deductorTAN)?.trim().toUpperCase()===r)return Ne(n.totalTdsDeposited)}const o=Re(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Re(n.deductorName)?.trim().toLowerCase()===o)return Ne(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ne(e[0].totalTdsDeposited)}function _d(s){const e=De(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ne(i.exemptAmount)??Ne(i.allowanceAmount);switch(Re(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ne(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Tt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function De(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ne(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Re(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function zl(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?zl(o):o):e[t]=r);return e}function sn(){if(typeof window>"u")return null;const s=window,e=s.__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=s.__aikaara_descriptor__??{},r=Cd(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=Od(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):Md(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:Pd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||Rd(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function kd(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return vd(Oo(await r.json().catch(()=>({}))))}async function xd(s,e){const t=await s.getToken(),r=s.userId,o={...ud(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Oo(await a.json().catch(()=>({})))}async function Sd(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function Ed(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function Ad(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Id(s,e){return ur(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function Td(s,e){return ur(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function ur(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Oo(await n.json().catch(()=>({})))}function Cd(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.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 Od(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);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 Pd(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function Md(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Oo(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function Rd(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class Ld{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new $l(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:cd,data:{}});const t=sn();if(!(!t||!t.baseUrl))try{const r=await kd(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=sn();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=fd(n,o);i&&await Sd(r,i)}else if(e==="bank-details"){const n=pd(t,o);n&&await Ed(r,n)}else if(e==="other-sources")await Ad(r,md(t,o));else if(e==="business-profession"){const n=bd(t,o);n&&await Id(r,n)}else if(e==="crypto-income"){const n=gd(t,o);n&&await Td(r,n)}}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=sn();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await xd(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 Vl 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||jc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Mo,position:this.getAttribute("position")||this._config.position||Nc,width:Number(this.getAttribute("width"))||this._config.width||Pc,height:Number(this.getAttribute("height"))||this._config.height||Mc,fontFamily:this._config.fontFamily||Lc,borderRadius:this._config.borderRadius??Rc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Ro,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||Uc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
|
@@ -757,7 +757,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
757
757
|
}
|
|
758
758
|
</style>
|
|
759
759
|
<slot></slot>
|
|
760
|
-
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Yd(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Gd[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&ic(r.scriptUrl).then(()=>Kd(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof i[a]=="function")try{i[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.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:i.map(c=>{const u=typeof c.title=="string"?c.title:"",h=c.message;return{label:u||h,value:h}})}),this.appendChild(l);return}for(const l of i)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-
|
|
760
|
+
`;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Yd(t):void 0,o=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`),n=Gd[o];if(n&&!customElements.get(o)?n().then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] native template ${o} failed to load`,i)):r?.scriptUrl&&!customElements.get(o)&&ic(r.scriptUrl).then(()=>Kd(o)).then(()=>this.render()).catch(i=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,i)),customElements.get(o)){const i=document.createElement(o);if(r?.props){for(const[a,l]of Object.entries(r.props))if(typeof i[a]=="function")try{i[a](l)}catch(c){console.warn(`[aikaara-template-renderer] props.${a} threw on <${o}>`,c)}}i.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(i),this.dataset.consumed==="true"&&(this._consumedValues&&Object.keys(this._consumedValues).length>0&&i.setConsumedValues?.(this._consumedValues),i.dataset.consumed="true");return}if(Array.isArray(this.payloadData)){const i=this.payloadData;if(i.length>0&&i.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:i.map(c=>{const u=typeof c.title=="string"?c.title:"",h=c.message;return{label:u||h,value:h}})}),this.appendChild(l);return}for(const l of i)this.mountField(l)}else if(this.payloadData&&typeof this.payloadData=="object"){const i=this.payloadData;typeof i.message=="string"&&(i.okLabel||i.action||i.ok)&&this.mountModal(i)}this.dataset.consumed==="true"&&this._applyConsumedToChildren()}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="text"){const o=document.createElement("aikaara-text-input");o.setPayload(r),this.appendChild(o);return}if(t==="checkbox"||t==="radio"||t==="button"){const o=document.createElement("aikaara-option-list");o.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(o);return}if(t==="submit"){const o=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;o.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(o);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>require("./AikaaraLinkButton-CBAy6ItK.cjs")).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:o})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Qd(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Jd=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Qd(s){const e={};for(const[t,r]of Object.entries(s))Jd.has(t)||(e[t]=r);return e}function Xd(s){const e=new Set(["message_id","formAction","requestType","serviceType"]),t={};for(const[r,o]of Object.entries(s))e.has(r)||(Array.isArray(o)&&o.every(n=>typeof n=="string")?t[r]=o:typeof o=="string"&&(t[r]=[o]));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
761
|
<style>
|
|
762
762
|
:host {
|
|
763
763
|
display: flex;
|
|
@@ -12259,9 +12259,8 @@ function Fh(s, e) {
|
|
|
12259
12259
|
return t === void 0 && r === void 0 ? null : {
|
|
12260
12260
|
userId: Yt(e.userId),
|
|
12261
12261
|
assessmentYear: e.assessmentYear,
|
|
12262
|
-
|
|
12263
|
-
|
|
12264
|
-
vdaPurchaseCost: r ?? 0
|
|
12262
|
+
vdaPurchaseCost: r ?? 0,
|
|
12263
|
+
vdaSellCost: t ?? 0
|
|
12265
12264
|
};
|
|
12266
12265
|
}
|
|
12267
12266
|
function qh(s, e) {
|
|
@@ -12549,7 +12548,7 @@ async function Xh(s, e) {
|
|
|
12549
12548
|
return ur(s, s.submitUrl || `${s.baseUrl}/itr/v1/automation/data`, e);
|
|
12550
12549
|
}
|
|
12551
12550
|
async function Zh(s, e) {
|
|
12552
|
-
return ur(s,
|
|
12551
|
+
return ur(s, `${s.baseUrl}/itr/v1/automation/vda`, e);
|
|
12553
12552
|
}
|
|
12554
12553
|
async function ur(s, e, t) {
|
|
12555
12554
|
const o = {
|
|
@@ -14721,7 +14720,7 @@ class Pd extends HTMLElement {
|
|
|
14721
14720
|
*/
|
|
14722
14721
|
mountLinkButton(e) {
|
|
14723
14722
|
const t = this.renderGen;
|
|
14724
|
-
import("./AikaaraLinkButton-
|
|
14723
|
+
import("./AikaaraLinkButton-DsJc3CEK.mjs").then(({ registerAikaaraLinkButton: r, AikaaraLinkButton: o }) => {
|
|
14725
14724
|
if (t !== this.renderGen) return;
|
|
14726
14725
|
r();
|
|
14727
14726
|
const n = document.createElement("aikaara-link-button");
|
|
@@ -5,7 +5,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
5
5
|
`+ie.prev+ie.base;return Ee+I.call(z,","+Ee)+`
|
|
6
6
|
`+ie.prev}function _e(z,ie){var Ee=be(z),Ae=[];if(Ee){Ae.length=z.length;for(var Te=0;Te<z.length;Te++)Ae[Te]=oe(z,Te)?ie(z[Te],z):""}var Oe=typeof T=="function"?T(z):[],nt;if(D){nt={};for(var it=0;it<Oe.length;it++)nt["$"+Oe[it]]=Oe[it]}for(var Ve in z)oe(z,Ve)&&(Ee&&String(Number(Ve))===Ve&&Ve<z.length||D&&nt["$"+Ve]instanceof Symbol||(E.call(/[^\w$]/,Ve)?Ae.push(ie(Ve,z)+": "+ie(z[Ve],z)):Ae.push(Ve+": "+ie(z[Ve],z))));if(typeof T=="function")for(var ot=0;ot<Oe.length;ot++)ae.call(z,Oe[ot])&&Ae.push("["+ie(Oe[ot])+"]: "+ie(z[Oe[ot]],z));return Ae}return qr}function Td(){if(co)return Wr;co=!0;var s=Ht(),e=fd(),t=Id(),r=ir(),o=s("%WeakMap%",!0),n=s("%Map%",!0),i=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),f=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=f(y,w);return m&&m.value},h=function(y,w,m){var k=f(y,w);k?k.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!f(y,w)};return Wr=function(){var y,w,m,k={assert:function(x){if(!k.has(x))throw new r("Side channel does not contain "+t(x))},get:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return i(y,x)}else if(n){if(w)return c(w,x)}else if(m)return g(m,x)},has:function(x){if(o&&x&&(typeof x=="object"||typeof x=="function")){if(y)return l(y,x)}else if(n){if(w)return d(w,x)}else if(m)return b(m,x);return!1},set:function(x,v){o&&x&&(typeof x=="object"||typeof x=="function")?(y||(y=new o),a(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),h(m,x,v))}};return k},Wr}function ao(){if(uo)return zr;uo=!0;var s=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return zr={default:t.RFC3986,formatters:{RFC1738:function(r){return s.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},zr}function Ka(){if(ho)return Vr;ho=!0;var s=ao(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var y=[],w=0;w<256;++w)y.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return y})(),o=function(y){for(;y.length>1;){var w=y.pop(),m=w.obj[w.prop];if(t(m)){for(var k=[],x=0;x<m.length;++x)typeof m[x]<"u"&&k.push(m[x]);w.obj[w.prop]=k}}},n=function(y,w){for(var m=w&&w.plainObjects?Object.create(null):{},k=0;k<y.length;++k)typeof y[k]<"u"&&(m[k]=y[k]);return m},i=function y(w,m,k){if(!m)return w;if(typeof m!="object"){if(t(w))w.push(m);else if(w&&typeof w=="object")(k&&(k.plainObjects||k.allowPrototypes)||!e.call(Object.prototype,m))&&(w[m]=!0);else return[w,m];return w}if(!w||typeof w!="object")return[w].concat(m);var x=w;return t(w)&&!t(m)&&(x=n(w,k)),t(w)&&t(m)?(m.forEach(function(v,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},x)},a=function(y,w){return Object.keys(w).reduce(function(m,k){return m[k]=w[k],m},y)},l=function(y,w,m){var k=y.replace(/\+/g," ");if(m==="iso-8859-1")return k.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(k)}catch{return k}},c=1024,u=function(y,w,m,k,x){if(y.length===0)return y;var v=y;if(typeof y=="symbol"?v=Symbol.prototype.toString.call(y):typeof y!="string"&&(v=String(y)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var 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||x===s.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 x=w[k],v=x.obj[x.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 o(w),y},f=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 Vr={arrayToObject:n,assign:a,combine:h,compact:d,decode:l,encode:u,isBuffer:g,isRegExp:f,maybeMap:b,merge:i},Vr}function Cd(){if(fo)return Kr;fo=!0;var s=Td(),e=Ka(),t=ao(),r=Object.prototype.hasOwnProperty,o={brackets:function(b){return b+"[]"},comma:"comma",indices:function(b,y){return b+"["+y+"]"},repeat:function(b){return b}},n=Array.isArray,i=Array.prototype.push,a=function(b,y){i.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"},f={},g=function b(y,w,m,k,x,v,E,S,I,P,O,j,T,q,D,U,ae,Y){for(var V=y,re=Y,$=0,Z=!1;(re=re.get(f))!==void 0&&!Z;){var M=re.get(y);if($+=1,typeof M<"u"){if(M===$)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(f)>"u"&&($=0)}if(typeof P=="function"?V=P(w,V):V instanceof Date?V=T(V):m==="comma"&&n(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!U?I(w,u.encoder,ae,"key",q):w;V=""}if(d(V)||e.isBuffer(V)){if(I){var Q=U?w:I(w,u.encoder,ae,"key",q);return[D(Q)+"="+D(I(V,u.encoder,ae,"value",q))]}return[D(w)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(m==="comma"&&n(V))U&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(n(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var K=S?w.replace(/\./g,"%2E"):w,N=k&&n(V)&&V.length===1?K+"[]":K;if(x&&n(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],G=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&G===null)){var J=j&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(N,J):N:N+(j?"."+J:"["+J+"]");Y.set(y,$);var oe=s();oe.set(f,Y),a(be,b(G,ge,m,k,x,v,E,S,m==="comma"&&U&&n(V)?null:I,P,O,j,T,q,D,U,ae,oe))}}return be},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 x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:k,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return Kr=function(b,y){var w=b,m=h(y),k,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,k=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;k||(k=Object.keys(w)),m.sort&&k.sort(m.sort);for(var I=s(),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:""},Kr}function Pd(){if(po)return Gr;po=!0;var s=Ka(),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:s.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(f){return f.replace(/&#(\d+);/g,function(g,h){return String.fromCharCode(parseInt(h,10))})},n=function(f,g){return f&&typeof f=="string"&&g.comma&&f.indexOf(",")>-1?f.split(","):f},i="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,g){var h={__proto__:null},b=g.ignoreQueryPrefix?f.replace(/^\?/,""):f;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,k,x=g.charset;if(g.charsetSentinel)for(k=0;k<w.length;++k)w[k].indexOf("utf8=")===0&&(w[k]===a?x="utf-8":w[k]===i&&(x="iso-8859-1"),m=k,k=w.length);for(k=0;k<w.length;++k)if(k!==m){var v=w[k],E=v.indexOf("]="),S=E===-1?v.indexOf("="):E+1,I,P;S===-1?(I=g.decoder(v,r.decoder,x,"key"),P=g.strictNullHandling?null:""):(I=g.decoder(v.slice(0,S),r.decoder,x,"key"),P=s.maybeMap(n(v.slice(S+1),g),function(j){return g.decoder(j,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(h,I);O&&g.duplicates==="combine"?h[I]=s.combine(h[I],P):(!O||g.duplicates==="last")&&(h[I]=P)}return h},c=function(f,g,h,b){for(var y=b?g:n(g,h),w=f.length-1;w>=0;--w){var m,k=f[w];if(k==="[]"&&h.parseArrays)m=h.allowEmptyArrays&&(y===""||h.strictNullHandling&&y===null)?[]:[].concat(y);else{m=h.plainObjects?Object.create(null):{};var x=k.charAt(0)==="["&&k.charAt(k.length-1)==="]"?k.slice(1,-1):k,v=h.decodeDotInKeys?x.replace(/%2E/g,"."):x,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(f,g,h,b){if(f){var y=h.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,k=h.depth>0&&w.exec(y),x=k?y.slice(0,k.index):y,v=[];if(x){if(!h.plainObjects&&e.call(Object.prototype,x)&&!h.allowPrototypes)return;v.push(x)}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(f){if(!f)return r;if(typeof f.allowEmptyArrays<"u"&&typeof f.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof f.decodeDotInKeys<"u"&&typeof f.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(f.decoder!==null&&typeof f.decoder<"u"&&typeof f.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof f.charset<"u"&&f.charset!=="utf-8"&&f.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var g=typeof f.charset>"u"?r.charset:f.charset,h=typeof f.duplicates>"u"?r.duplicates:f.duplicates;if(h!=="combine"&&h!=="first"&&h!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:r.allowDots:!!f.allowDots;return{allowDots:b,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:r.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:r.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:r.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:r.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:r.decoder,delimiter:typeof f.delimiter=="string"||s.isRegExp(f.delimiter)?f.delimiter:r.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:r.depth,duplicates:h,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:r.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:r.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:r.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:r.strictNullHandling}};return Gr=function(f,g){var h=d(g);if(f===""||f===null||typeof f>"u")return h.plainObjects?Object.create(null):{};for(var b=typeof f=="string"?l(f,h):f,y=h.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var k=w[m],x=u(k,b[k],h,typeof f=="string");y=s.merge(y,x,h)}return h.allowSparse===!0?y:s.compact(y)},Gr}function Od(){if(mo)return Yr;mo=!0;var s=Cd(),e=Pd(),t=ao();return Yr={formats:t,parse:e,stringify:s},Yr}function Md(){if(go)return St;go=!0;var s=_t;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
7
|
`," "],i=["{","}","|","\\","^","`"].concat(n),a=["'"].concat(i),l=["%","/","?",";","#"].concat(a),c=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,f=/^([+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=Od();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 q=o.exec(T);if(q)return this.path=T,this.href=T,this.pathname=q[1],q[2]?(this.search=q[2],E?this.query=y.parse(this.search.substr(1)):this.query=this.search.substr(1)):E&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var U=D.toLowerCase();this.protocol=U,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&h[D])&&(T=T.substr(2),this.slashes=!0)}if(!h[D]&&(ae||D&&!b[D])){for(var Y=-1,V=0;V<c.length;V++){var re=T.indexOf(c[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var $,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&($=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent($)),Y=-1;for(var V=0;V<l.length;V++){var re=T.indexOf(l[V]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var M=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!M)for(var Q=this.hostname.split(/\./),V=0,be=Q.length;V<be;V++){var te=Q[V];if(te&&!te.match(d)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(d)){var ne=Q.slice(0,V),W=Q.slice(V+1),G=te.match(f);G&&(ne.push(G[1]),W.unshift(G[2])),W.length&&(T="/"+W.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=s.toASCII(this.hostname));var J=this.port?":"+this.port:"",ge=this.hostname||"";this.host=ge+J,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!g[U])for(var V=0,be=a.length;V<be;V++){var oe=a[V];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var F=T.indexOf("#");F!==-1&&(this.hash=T.substr(F),T=T.slice(0,F));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),E&&(this.query=y.parse(this.query)),T=T.slice(0,ee)):E&&(this.search="",this.query={}),T&&(this.pathname=T),b[U]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var J=this.pathname||"",he=this.search||"";this.path=J+he}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=w(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var E=this.protocol||"",S=this.pathname||"",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 x(v,E){return v?w(v,!1,!0).resolveObject(E):E}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var E=new e;E.parse(v,!1,!0),v=E}for(var S=new e,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 q=j[T];q!=="protocol"&&(S[q]=v[q])}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 D=Object.keys(v),U=0;U<D.length;U++){var ae=D[U];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!h[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",V=S.search||"";S.path=Y+V}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",$=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=$||re||S.host&&v.pathname,M=Z,Q=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!b[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(Q[0]===""?Q[0]=S.host:Q.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||Q[0]==="")),$)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,Q=be;else if(be.length)Q||(Q=[]),Q.pop(),Q=Q.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=Q.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!Q.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var K=Q.slice(-1)[0],N=(S.host||v.host||Q.length>1)&&(K==="."||K==="..")||K==="",ne=0,W=Q.length;W>=0;W--)K=Q[W],K==="."?Q.splice(W,1):K===".."?(Q.splice(W,1),ne++):ne&&(Q.splice(W,1),ne--);if(!Z&&!M)for(;ne--;ne)Q.unshift("..");Z&&Q[0]!==""&&(!Q[0]||Q[0].charAt(0)!=="/")&&Q.unshift(""),N&&Q.join("/").substr(-1)!=="/"&&Q.push("");var G=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=G?"":Q.length?Q.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&Q.length,Z&&!G&&Q.unshift(""),Q.length>0?S.pathname=Q.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,E=r.exec(v);E&&(E=E[0],E!==":"&&(this.port=E.substr(1)),v=v.substr(0,v.length-E.length)),v&&(this.hostname=v)},St.parse=w,St.resolve=k,St.resolveObject=x,St.format=m,St.Url=e,St}function Ga(s){if(typeof s=="string")s=new URL(s);else if(!(s instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(s.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Jr?Rd(s):Ld(s)}function Rd(s){let e=s.hostname,t=s.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let o=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&o===102||t[r+1]==="5"&&o===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(ll,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<sl||r>al||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Ld(s){if(s.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=s.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 Ya(s){let e=so.resolve(s),t=s.charCodeAt(s.length-1);(t===ol||Jr&&t===il)&&e[e.length-1]!==so.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(cl,"%25")),!Jr&&e.includes("\\")&&(e=e.replace(ul,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(dl,"%0A")),e.includes("\r")&&(e=e.replace(hl,"%0D")),e.includes(" ")&&(e=e.replace(fl,"%09")),r.pathname=e,r}var Ja,qr,lo,Hr,Wr,co,zr,uo,Vr,ho,Kr,fo,Gr,po,Yr,mo,St,go,ze,Qa,Xa,Za,el,tl,rl,nl,il,ol,sl,al,Jr,ll,cl,ul,dl,hl,fl,Nd=Ye(()=>{le(),ue(),ce(),Xu(),pd(),Ad(),za(),Ja=Object.freeze(Object.create(null)),qr={},lo=!1,Hr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Wr={},co=!1,zr={},uo=!1,Vr={},ho=!1,Kr={},fo=!1,Gr={},po=!1,Yr={},mo=!1,St={},go=!1,ze=Md(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Qa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Ya,ze.fileURLToPath=Ga,Xa=ze.Url,Za=ze.format,el=ze.resolve,tl=ze.resolveObject,rl=ze.parse,nl=ze.URL,il=92,ol=47,sl=97,al=122,Jr=Qa==="win32",ll=/\//g,cl=/%/g,ul=/\\/g,dl=/\n/g,hl=/\r/g,fl=/\t/g}),jd=pe((s,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")}}),bo=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Ot(),t=(Fe(),Re($e));function r(n,i){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",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,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,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),Qr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=(Fe(),Re($e)),r=e(jd()),o=e(pt()),n=Ot(),i=e(Er()),a=bo(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.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 f(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=f(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,ae);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",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function O(Y,V,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=V,$._flush=re,$}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,k.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function ae(Y){S.close(),Y()}return k};s.browserStreamBuilder=y}),yo={};Bt(yo,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>pl,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var pl,ml=Ye(()=>{le(),ue(),ce(),pl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),gl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),bl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((ml(),Re(yo))),r=e(pt()),o=e(gl()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};s.default=i}),yl={};Bt(yl,{default:()=>vl});var vl,Ud=Ye(()=>{le(),ue(),ce(),vl={}}),wl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(Ud(),Re(yl)),r=e((ml(),Re(yo))),o=e(pt()),n=e(gl()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:f,...g}=c;if(f!==void 0){let h=(0,n.default)(u,d,f,{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,i("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",f)});function f(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",f),d};s.default=l}),kl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i;function a(){let f=new t.Transform;return f._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},f._flush=g=>{o.close({success(){g()}})},f}function l(f){f.hostname||(f.hostname="localhost"),f.path||(f.path="/"),f.wsOptions||(f.wsOptions={})}function c(f,g){let h=f.protocol==="wxs"?"wss":"ws",b=`${h}://${f.hostname}${f.path}`;return f.port&&f.port!==80&&f.port!==443&&(b=`${h}://${f.hostname}:${f.port}${f.path}`),typeof f.transformWsUrl=="function"&&(b=f.transformWsUrl(b,f,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(f=>{let{data:g}=f;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(f=>{let g=new Error(f.errMsg);i.destroy(g)})}var d=(f,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,f);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),i=new r.BufferedDuplex(g,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=d}),_l=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.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,o.onSocketOpen(()=>{i.socketReady()}),o.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)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var f=(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 o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(h,n,o),d(),i};s.default=f}),Bd=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Nd(),Re(Va))),o=e(_i()),n=e(Er());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(d){let f;if(d.auth)if(f=d.auth.match(/^(.+):(.+)$/),f){let[,g,h]=f;d.username=g,d.password=h}else d.username=d.auth}function c(d,f){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!f&&(f=d,d=""),f=f||{},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,f={...y,...f},!f.protocol)throw new Error("Missing protocol");f.protocol=f.protocol.replace(/:$/,"")}if(f.unixSocket=f.unixSocket||f.protocol?.includes("+unix"),f.unixSocket?f.protocol=f.protocol.replace("+unix",""):!f.protocol?.startsWith("ws")&&!f.protocol?.startsWith("wx")&&delete f.path,l(f),f.query&&typeof f.query.clientId=="string"&&(f.clientId=f.query.clientId),n.default||f.unixSocket?f.socksProxy=void 0:f.socksProxy===void 0&&typeof Ne<"u"&&(f.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),f.cert&&f.key)if(f.protocol){if(["mqtts","wss","wxs","alis"].indexOf(f.protocol)===-1)switch(f.protocol){case"mqtt":f.protocol="mqtts";break;case"ws":f.protocol="wss";break;case"wx":f.protocol="wxs";break;case"ali":f.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${f.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!f.forceNativeWebSocket?(a.ws=Qr().streamBuilder,a.wss=Qr().streamBuilder,a.mqtt=bl().default,a.tcp=bl().default,a.ssl=wl().default,a.tls=a.ssl,a.mqtts=wl().default):(a.ws=Qr().browserStreamBuilder,a.wss=Qr().browserStreamBuilder,a.wx=kl().default,a.wxs=kl().default,a.ali=_l().default,a.alis=_l().default)),!a[f.protocol]){let b=["mqtts","wss"].indexOf(f.protocol)!==-1;f.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(f.clean===!1&&!f.clientId)throw new Error("Missing clientId for unclean clients");f.protocol&&(f.defaultProtocol=f.protocol);function g(b){return f.servers&&((!b._reconnectCount||b._reconnectCount===f.servers.length)&&(b._reconnectCount=0),f.host=f.servers[b._reconnectCount].host,f.port=f.servers[b._reconnectCount].port,f.protocol=f.servers[b._reconnectCount].protocol?f.servers[b._reconnectCount].protocol:f.defaultProtocol,f.hostname=f.host,b._reconnectCount++),i("calling streambuilder for",f.protocol),a[f.protocol](b,f)}let h=new o.default(g,f);return h.on("error",()=>{}),h}function u(d,f,g=!0){return new Promise((h,b)=>{let y=c(d,f),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])})})}s.default=c}),xl=pe(s=>{le(),ue(),ce();var e=s&&s.__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=s&&s.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=s&&s.__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}})(),o=s&&s.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Ps());s.DefaultMessageIdProvider=a.default;var l=n(Ju());s.UniqueMessageIdProvider=l.default;var c=n(xs());s.Store=c.default;var u=r(Bd());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Us());s.KeepaliveManager=d.default,s.Client=i.default,o(_i(),s),o(qt(),s),o(_s(),s);var f=xr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return f.ReasonCodes}})}),Dd=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,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(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(xl());s.default=n,o(xl(),s)});const $d=Dd();const Fd={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},qd=300,Hd={templateId:"7",type:"link",isDeepLink:!0},Wd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Sl{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={...Fd,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,f)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:f?.message}),l(()=>i(f??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=$d.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,f)=>{this.dispatchInbound(d,f)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Hd,...this.config.fileTemplate??{},...zd(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=qd){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),f={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(f)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Wd,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function zd(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function El(s,e){return(s.sender??"").toString()===e}function Al(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function vo(s){const e={raw:s},t=s.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 s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Il(s){const e=vo(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Tl(s,e,t){const r=Al(s,t),o=vo(s),n=Il(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Vd(s.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function Vd(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class Cl extends mr{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 Fo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new qo,this.conversationManager=new Ko(e.conversationId),this.usesAikaara()&&(this.connection=new $o(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Sl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Tl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Tl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(El(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Kd extends mr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Pl={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 Gd(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Yd(s,e,t){const r=Gd(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Pl[r]?Pl[r]:t}function wo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Jd(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Ol(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Yd(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=wo(c,i),d=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const f=await d.json().catch(()=>({})),g=Jd(f,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.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(s.registerEndpoint){const w=JSON.parse(wo(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.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:s.viewerTemplate?wo(s.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function ko(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[f,g]of Object.entries(n))r.append(f,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.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 Qd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Ml(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Qd;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const f=await s.getToken();f&&(l.authorization=f)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.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 Xd=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function Zd(s,e){const t=s||{},r={userId:zt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=_o(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Me(t.bizName)!==void 0||o>0;r.businessName=Me(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const a={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=xo(t.hpDetails,eh);l.length&&(r.hpDetails=l);const c=xo(t.salaryDetails,th);if(c.length){r.salaryIncome=c;const u=xo(t.salaryDetails,f=>({grossSalary:Ie(f.grossSalary),employerName:Me(f.employerName)}));u.length&&(r.salary=u);const d=Rl(t.salaryDetails)[0]??{};r.hraAmount=Ie(d.hraReceived),r.leaveTravelAllowanceAmount=Ie(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(d.leaveEncashment),r.anyOtherAllowanceAmount=Ie(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return Xr(r)}function eh(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:ah(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:_o(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:_o(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function th(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function rh(s,e){const t=[];for(const r of s){const o=Me(r.employerName),n=Me(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function nh(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),o=Me(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function ih(s,e){return{userId:zt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function oh(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,cryptoSellValue:t??0,cryptoPurchaseAmount:r??0,vdaPurchaseCost:r??0}}function sh(s,e){const t=(o,n,i,a)=>{const l=Me(s[o]),c=Me(s[n]),u=Ie(s[i]),d=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function zt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function _o(s){return s===!0||s===!1?s:void 0}function ah(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Rl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function xo(s,e){return Rl(s).map(t=>Xr(e(t))).filter(t=>t!==void 0)}function Xr(s){if(Array.isArray(s)){const e=s.map(Xr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=Xr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function lh(s){const e=s&&typeof s=="object"?s:{},t={},r=qe(e.employers),o=qe(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(d=>{const f=So(d.salary),g=So(d.perquisites),h=So(d.profitsInLieuOfSalaryType),b=f+g+h,y=uh(d.allowance);return{employerName:Le(d.employerName),employerTan:Le(d.employerTAN),basicSalary:f||void 0,grossSalary:b||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:ch(d,o,r)??Ue(d.totalTdsDeposited)}}));const n=qe(e.houseProperties);n.length&&(t.hpDetails=n.map(d=>{const f=qe(d.loanDetails),g=f.length?f[0]:void 0,h=Ue(d.grossAnnualRentReceived),b=f.length?f.reduce((x,v)=>x+(Ue(v.interest)??0),0):void 0,y=qe(d.tenant),w=qe(d.coOwners),m=y[0],k=w[0];return{typeOfHouseProperty:Le(d.propertyType),loanTakenFrom:Le(g?.loanTakenFrom),lenderName:Le(g?.bankOrInstituteName),loanAccountNumber:Le(g?.loanAccountNo),sanctionDate:Le(g?.loanSanctionDate),totalLoanAmount:Ue(g?.totalLoanAmount),outstandingAmount:Ue(g?.loanOutstandingAmount),homeLoanInterest:b,homeLoanPrinciple:void 0,housePropertyAddress:Le(d.address),housePropertyPincode:Le(d.pinCode),rentalIncome:h,nameOfTenant:Le(m?.name),propertyTax:Ue(d.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Le(k?.name),coOwnerPan:Le(k?.panNumber),coOwnerShare:Ue(k?.share)?.toString()}})),t.us80cAmount=Lt(qe(e.deductionUS80CDetails).map(d=>Ue(d.amount))),t.us80dForSelfAndFamilyAmount=Lt(qe(e.deductionUS80DDetails).map(d=>Ue(d.healthInsuranceAmount)));const i=qe(e.incomes),a=d=>Lt(i.filter(f=>Le(f.incomeType)===d).map(f=>Ue(f.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Lt(qe(e.dividendIncomes).map(d=>Ue(d.income)));const l=e.business;if(l){const d=qe(l.presumptiveIncomes),f=b=>{const y=qe(b.incomes),w=m=>Ue(y.find(k=>Le(k.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Le(b.businessType)?.toUpperCase().includes("PROFESSION")},g=b=>d.find(y=>f(y)===b),h=(b,y)=>{if(!b)return;const w=qe(b.incomes),m=x=>Ue(w.find(v=>Le(v.incomeType)===x)?.receipts),k=m("BANK")||m("ANY_OTHER");t[y.name]=Le(b.businessType),t[y.nature]=Le(b.natureOfBusiness),t[y.bank]=k||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Lt(w.map(x=>Ue(x.presumptiveIncome)))||void 0};h(g(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),h(g(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=qe(e.capitalGain).filter(d=>Le(d.assetType)?.toUpperCase()==="VDA").flatMap(d=>qe(d.assetDetails));c.length&&(t.cryptoSellPrice=Lt(c.map(d=>Ue(d.sellValue))),t.cryptoPurchasePrice=Lt(c.map(d=>Ue(d.purchaseCost)))),t.agricultureIncome=Ue(e.agriculturalDetails?.income),t.aadhaarNumber=Le(e.aadharNumber);const u=qe(e.bankDetails)[0];return u&&(t.bankAccountNumber=Le(u.accountNumber),t.bankIfscCode=Le(u.ifsCode)),Ll(t)}function So(s){return qe(s).reduce((e,t)=>e+(Ue(t.taxableAmount)??0),0)}function ch(s,e,t){if(!e.length)return;const r=Le(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Le(n.deductorTAN)?.trim().toUpperCase()===r)return Ue(n.totalTdsDeposited)}const o=Le(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Le(n.deductorName)?.trim().toLowerCase()===o)return Ue(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ue(e[0].totalTdsDeposited)}function uh(s){const e=qe(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ue(i.exemptAmount)??Ue(i.allowanceAmount);switch(Le(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ue(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Lt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function qe(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ue(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Le(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Ll(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Ll(o):o):e[t]=r);return e}function Eo(){if(typeof window>"u")return null;const s=window,e=s.__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=s.__aikaara_descriptor__??{},r=yh(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=vh(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):kh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:wh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||_h(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function dh(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return lh(Ao(await r.json().catch(()=>({}))))}async function hh(s,e){const t=await s.getToken(),r=s.userId,o={...Zd(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ao(await a.json().catch(()=>({})))}async function fh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function ph(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function mh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function gh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function bh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function sr(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Ao(await n.json().catch(()=>({})))}function yh(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.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 vh(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);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 wh(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function kh(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Ao(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function _h(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class xh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Cl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Xd,data:{}});const t=Eo();if(!(!t||!t.baseUrl))try{const r=await dh(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=Eo();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=rh(n,o);i&&await fh(r,i)}else if(e==="bank-details"){const n=nh(t,o);n&&await ph(r,n)}else if(e==="other-sources")await mh(r,ih(t,o));else if(e==="business-profession"){const n=sh(t,o);n&&await gh(r,n)}else if(e==="crypto-income"){const n=oh(t,o);n&&await bh(r,n)}}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=Eo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await hh(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 Nl 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||Oc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Bo,position:this.getAttribute("position")||this._config.position||Pc,width:Number(this.getAttribute("width"))||this._config.width||Ac,height:Number(this.getAttribute("height"))||this._config.height||Ic,fontFamily:this._config.fontFamily||Cc,borderRadius:this._config.borderRadius??Tc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Do,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||Mc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
8
|
+
`)&&(e=e.replace(dl,"%0A")),e.includes("\r")&&(e=e.replace(hl,"%0D")),e.includes(" ")&&(e=e.replace(fl,"%09")),r.pathname=e,r}var Ja,qr,lo,Hr,Wr,co,zr,uo,Vr,ho,Kr,fo,Gr,po,Yr,mo,St,go,ze,Qa,Xa,Za,el,tl,rl,nl,il,ol,sl,al,Jr,ll,cl,ul,dl,hl,fl,Nd=Ye(()=>{le(),ue(),ce(),Xu(),pd(),Ad(),za(),Ja=Object.freeze(Object.create(null)),qr={},lo=!1,Hr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Wr={},co=!1,zr={},uo=!1,Vr={},ho=!1,Kr={},fo=!1,Gr={},po=!1,Yr={},mo=!1,St={},go=!1,ze=Md(),ze.parse,ze.resolve,ze.resolveObject,ze.format,ze.Url,Qa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,ze.URL=typeof URL<"u"?URL:null,ze.pathToFileURL=Ya,ze.fileURLToPath=Ga,Xa=ze.Url,Za=ze.format,el=ze.resolve,tl=ze.resolveObject,rl=ze.parse,nl=ze.URL,il=92,ol=47,sl=97,al=122,Jr=Qa==="win32",ll=/\//g,cl=/%/g,ul=/\\/g,dl=/\n/g,hl=/\r/g,fl=/\t/g}),jd=pe((s,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")}}),bo=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0}),s.BufferedDuplex=void 0,s.writev=r;var e=Ot(),t=(Fe(),Re($e));function r(n,i){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",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,a){super({objectMode:!0}),this.proxy=i,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,i,a){this.isSocketOpen?this.writeToProxy(n,i,a):this.writeQueue.push({chunk:n,encoding:i,cb:a})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,a){this.proxy.write(n,i)===!1?this.proxy.once("drain",a):a()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:a}=this.writeQueue.shift();this.writeToProxy(n,i,a)}}};s.BufferedDuplex=o}),Qr=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(s,"__esModule",{value:!0}),s.streamBuilder=s.browserStreamBuilder=void 0;var t=(Fe(),Re($e)),r=e(jd()),o=e(pt()),n=Ot(),i=e(Er()),a=bo(),l=(0,o.default)("mqttjs:ws"),c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(w,m){let k=`${w.protocol}://${w.hostname}:${w.port}${w.path}`;return typeof w.transformWsUrl=="function"&&(k=w.transformWsUrl(k,w,m)),k}function d(w){let m=w;return w.port||(w.protocol==="wss"?m.port=443:m.port=80),w.path||(m.path="/"),w.wsOptions||(m.wsOptions={}),!i.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 f(w){let m=d(w);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let k=new URL(document.URL);m.hostname=k.hostname,m.port||(m.port=Number(k.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function g(w,m,k){l("createWebSocket"),l(`protocol: ${k.protocolId} ${k.protocolVersion}`);let x=k.protocolId==="MQIsdp"&&k.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return k.createWebsocket?v=k.createWebsocket(m,[x],k):v=new r.default(m,[x],k.wsOptions),v}function h(w,m){let k=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[k],m):v=new WebSocket(x,[k]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let k=d(m);k.hostname=k.hostname||k.host||"localhost";let x=u(k,w),v=g(w,x,k),E=r.default.createWebSocketStream(v,k.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};s.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let k,x=f(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=h(w,m),I=O(m,U,ae);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",q),S.addEventListener("message",D)):(S.onclose=T,S.onerror=q,S.onmessage=D);function O(Y,V,re){let $=new n.Transform({objectMode:Y.objectMode});return $._write=V,$._flush=re,$}function j(){l("WebSocket onOpen"),k instanceof a.BufferedDuplex&&k.socketReady()}function T(Y){l("WebSocket onClose",Y),k.end(),k.destroy()}function q(Y){l("WebSocket onError",Y);let V=new Error("WebSocket error");V.event=Y,k.destroy(V)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:V}=Y;V instanceof ArrayBuffer?V=t.Buffer.from(V):V instanceof Blob?V=t.Buffer.from(await new Response(V).arrayBuffer()):V=t.Buffer.from(V,"utf8"),I.push(V)}function U(Y,V,re){if(S.bufferedAmount>x){setTimeout(U,v,Y,V,re);return}E&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch($){return re($)}re()}function ae(Y){S.close(),Y()}return k};s.browserStreamBuilder=y}),yo={};Bt(yo,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>pl,isIP:()=>je,isIPv4:()=>je,isIPv6:()=>je});function je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var pl,ml=Ye(()=>{le(),ue(),ce(),pl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),gl=pe((s,e)=>{le(),ue(),ce(),e.exports={}}),bl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(s,"__esModule",{value:!0});var t=e((ml(),Re(yo))),r=e(pt()),o=e(gl()),n=(0,r.default)("mqttjs:tcp"),i=(a,l)=>{if(l.port=l.port||1883,l.hostname=l.hostname||l.host||"localhost",l.socksProxy)return(0,o.default)(l.hostname,l.port,l.socksProxy,{timeout:l.socksTimeout});let{port:c,path:u}=l,d=l.hostname;return n("port %d and host %s",c,d),t.default.createConnection({port:c,host:d,path:u})};s.default=i}),yl={};Bt(yl,{default:()=>vl});var vl,Ud=Ye(()=>{le(),ue(),ce(),vl={}}),wl=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(s,"__esModule",{value:!0});var t=(Ud(),Re(yl)),r=e((ml(),Re(yo))),o=e(pt()),n=e(gl()),i=(0,o.default)("mqttjs:tls");function a(c){let{host:u,port:d,socksProxy:f,...g}=c;if(f!==void 0){let h=(0,n.default)(u,d,f,{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,i("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",f)});function f(g){u.rejectUnauthorized&&c.emit("error",g),d.end()}return d.on("error",f),d};s.default=l}),kl=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i;function a(){let f=new t.Transform;return f._write=(g,h,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},f._flush=g=>{o.close({success(){g()}})},f}function l(f){f.hostname||(f.hostname="localhost"),f.path||(f.path="/"),f.wsOptions||(f.wsOptions={})}function c(f,g){let h=f.protocol==="wxs"?"wss":"ws",b=`${h}://${f.hostname}${f.path}`;return f.port&&f.port!==80&&f.port!==443&&(b=`${h}://${f.hostname}:${f.port}${f.path}`),typeof f.transformWsUrl=="function"&&(b=f.transformWsUrl(b,f,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(f=>{let{data:g}=f;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(f=>{let g=new Error(f.errMsg);i.destroy(g)})}var d=(f,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,f);o=wx.connectSocket({url:b,protocols:[h]}),n=a(),i=new r.BufferedDuplex(g,n,o),i._destroy=(w,m)=>{o.close({success(){m&&m(w)}})};let y=i.destroy;return i.destroy=(w,m)=>(i.destroy=y,setTimeout(()=>{o.close({fail(){i._destroy(w,m)}})},0),i),u(),i};s.default=d}),_l=pe(s=>{le(),ue(),ce(),Object.defineProperty(s,"__esModule",{value:!0});var e=(Fe(),Re($e)),t=Ot(),r=bo(),o,n,i,a=!1;function l(){let g=new t.Transform;return g._write=(h,b,y)=>{o.sendSocketMessage({data:h.buffer,success(){y()},fail(){y(new Error)}})},g._flush=h=>{o.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,o.onSocketOpen(()=>{i.socketReady()}),o.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)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var f=(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 o=h.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(h,n,o),d(),i};s.default=f}),Bd=pe(s=>{le(),ue(),ce();var e=s&&s.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(s,"__esModule",{value:!0}),s.connectAsync=u;var t=e(pt()),r=e((Nd(),Re(Va))),o=e(_i()),n=e(Er());typeof Ne?.nextTick!="function"&&(Ne.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),a=null;function l(d){let f;if(d.auth)if(f=d.auth.match(/^(.+):(.+)$/),f){let[,g,h]=f;d.username=g,d.password=h}else d.username=d.auth}function c(d,f){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!f&&(f=d,d=""),f=f||{},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,f={...y,...f},!f.protocol)throw new Error("Missing protocol");f.protocol=f.protocol.replace(/:$/,"")}if(f.unixSocket=f.unixSocket||f.protocol?.includes("+unix"),f.unixSocket?f.protocol=f.protocol.replace("+unix",""):!f.protocol?.startsWith("ws")&&!f.protocol?.startsWith("wx")&&delete f.path,l(f),f.query&&typeof f.query.clientId=="string"&&(f.clientId=f.query.clientId),n.default||f.unixSocket?f.socksProxy=void 0:f.socksProxy===void 0&&typeof Ne<"u"&&(f.socksProxy=Ne.env.MQTTJS_SOCKS_PROXY),f.cert&&f.key)if(f.protocol){if(["mqtts","wss","wxs","alis"].indexOf(f.protocol)===-1)switch(f.protocol){case"mqtt":f.protocol="mqtts";break;case"ws":f.protocol="wss";break;case"wx":f.protocol="wxs";break;case"ali":f.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${f.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(a||(a={},!n.default&&!f.forceNativeWebSocket?(a.ws=Qr().streamBuilder,a.wss=Qr().streamBuilder,a.mqtt=bl().default,a.tcp=bl().default,a.ssl=wl().default,a.tls=a.ssl,a.mqtts=wl().default):(a.ws=Qr().browserStreamBuilder,a.wss=Qr().browserStreamBuilder,a.wx=kl().default,a.wxs=kl().default,a.ali=_l().default,a.alis=_l().default)),!a[f.protocol]){let b=["mqtts","wss"].indexOf(f.protocol)!==-1;f.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof a[y]=="function")[0]}if(f.clean===!1&&!f.clientId)throw new Error("Missing clientId for unclean clients");f.protocol&&(f.defaultProtocol=f.protocol);function g(b){return f.servers&&((!b._reconnectCount||b._reconnectCount===f.servers.length)&&(b._reconnectCount=0),f.host=f.servers[b._reconnectCount].host,f.port=f.servers[b._reconnectCount].port,f.protocol=f.servers[b._reconnectCount].protocol?f.servers[b._reconnectCount].protocol:f.defaultProtocol,f.hostname=f.host,b._reconnectCount++),i("calling streambuilder for",f.protocol),a[f.protocol](b,f)}let h=new o.default(g,f);return h.on("error",()=>{}),h}function u(d,f,g=!0){return new Promise((h,b)=>{let y=c(d,f),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])})})}s.default=c}),xl=pe(s=>{le(),ue(),ce();var e=s&&s.__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=s&&s.__setModuleDefault||(Object.create?function(g,h){Object.defineProperty(g,"default",{enumerable:!0,value:h})}:function(g,h){g.default=h}),r=s&&s.__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}})(),o=s&&s.__exportStar||function(g,h){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(h,b)&&e(h,g,b)},n=s&&s.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(s,"__esModule",{value:!0}),s.ReasonCodes=s.KeepaliveManager=s.UniqueMessageIdProvider=s.DefaultMessageIdProvider=s.Store=s.MqttClient=s.connectAsync=s.connect=s.Client=void 0;var i=n(_i());s.MqttClient=i.default;var a=n(Ps());s.DefaultMessageIdProvider=a.default;var l=n(Ju());s.UniqueMessageIdProvider=l.default;var c=n(xs());s.Store=c.default;var u=r(Bd());s.connect=u.default,Object.defineProperty(s,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Us());s.KeepaliveManager=d.default,s.Client=i.default,o(_i(),s),o(qt(),s),o(_s(),s);var f=xr();Object.defineProperty(s,"ReasonCodes",{enumerable:!0,get:function(){return f.ReasonCodes}})}),Dd=pe(s=>{le(),ue(),ce();var e=s&&s.__createBinding||(Object.create?function(i,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(i,c,u)}:function(i,a,l,c){c===void 0&&(c=l),i[c]=a[l]}),t=s&&s.__setModuleDefault||(Object.create?function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}:function(i,a){i.default=a}),r=s&&s.__importStar||(function(){var i=function(a){return i=Object.getOwnPropertyNames||function(l){var c=[];for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(c[c.length]=u);return c},i(a)};return function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var c=i(a),u=0;u<c.length;u++)c[u]!=="default"&&e(l,a,c[u]);return t(l,a),l}})(),o=s&&s.__exportStar||function(i,a){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(a,l)&&e(a,i,l)};Object.defineProperty(s,"__esModule",{value:!0});var n=r(xl());s.default=n,o(xl(),s)});const $d=Dd();const Fd={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},qd=300,Hd={templateId:"7",type:"link",isDeepLink:!0},Wd={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Sl{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={...Fd,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??1/0,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0};this.clientId=this.config.clientId??this.freshClientId();const r=this.config.connectTimeoutMs??1e4,o={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!1,resubscribe:!0,reconnectPeriod:0,connectTimeout:r,keepalive:this.config.keepAliveSec??30,protocolVersion:this.config.protocolVersion??4,protocolId:this.config.protocolId??"MQTT"};return this.config.enablePresence!==!1&&(o.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),this.attachLifecycleHandlers(),new Promise((n,i)=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(u),d())},c=(d,f)=>{a||(this.debugLog("CONNECT_FAIL",{reason:d,message:f?.message}),l(()=>i(f??new Error(`tiledesk-transport: ${d}`))))},u=setTimeout(()=>c("connect-timeout"),r+500);this.client=$d.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),a||l(()=>n()),this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const d=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(d),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:d})}}),this.client.on("message",(d,f)=>{this.dispatchInbound(d,f)}),this.client.on("close",()=>{if(this.debugLog("CLOSE",{}),this.notifyStateChange(!1),!a){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",d=>{this.debugLog("ERROR",{message:d.message}),a||c("mqtt-error",d)}),this.client.on("disconnect",d=>{this.debugLog("DISCONNECT",{reasonCode:d?.reasonCode,properties:d?.properties})}),this.client.on("offline",()=>{this.debugLog("OFFLINE",{}),a||c("mqtt-offline")}),this.client.on("packetsend",d=>{(d.cmd==="subscribe"||d.cmd==="unsubscribe"||d.cmd==="pingreq")&&this.debugLog(d.cmd.toUpperCase(),{topic:d.topic,packetId:d.messageId})})})}freshClientId(){const e=Math.random().toString(36).slice(2,8);return`aikaara_${this.config.userId}_${Date.now()}_${e}`}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[o,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[o]=`${n.slice(0,200)}…(${n.length})`:r[o]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const o=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,o)}publishFileMessage(e,t){if(!this.client)return;const r={...Hd,...this.config.fileTemplate??{},...zd(t)},o={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(o),type:"html",attributes:n,metadata:o.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=qd){if(!this.client)return;const o=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(o,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.detachLifecycleHandlers(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed||this.reconnectTimer)return;if(typeof navigator<"u"&&navigator.onLine===!1){this.debugLog("RECONNECT_SKIP_OFFLINE",{attempt:this.reconnectAttempt});return}this.connectedAt>0&&Date.now()-this.connectedAt>=5e3&&(this.reconnectAttempt=0),this.connectedAt=0;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs),t=e*.2*(Math.random()*2-1),r=Math.max(0,Math.round(e+t));this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const o=[...this.subscribedTopics];this.subscribedTopics.clear(),o.forEach(n=>{this.client&&(this.client.subscribe(n,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(n))})}catch{}}},r)}reconnectNow(e){this.disposed||this.isConnected||typeof navigator<"u"&&navigator.onLine===!1||(this.debugLog("RECONNECT_NOW",{reason:e}),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.scheduleReconnect())}attachLifecycleHandlers(){this.lifecycleHandlersAttached||typeof window>"u"||typeof document>"u"||(this.onOnlineHandler=()=>this.reconnectNow("online"),this.onVisibilityHandler=()=>{document.visibilityState==="visible"&&this.reconnectNow("visible")},this.onPageShowHandler=e=>{e.persisted&&this.reconnectNow("pageshow-bfcache")},window.addEventListener("online",this.onOnlineHandler),document.addEventListener("visibilitychange",this.onVisibilityHandler),window.addEventListener("pageshow",this.onPageShowHandler),this.lifecycleHandlersAttached=!0)}detachLifecycleHandlers(){this.lifecycleHandlersAttached&&(typeof window>"u"||typeof document>"u"||(this.onOnlineHandler&&window.removeEventListener("online",this.onOnlineHandler),this.onVisibilityHandler&&document.removeEventListener("visibilitychange",this.onVisibilityHandler),this.onPageShowHandler&&window.removeEventListener("pageshow",this.onPageShowHandler),this.onOnlineHandler=null,this.onVisibilityHandler=null,this.onPageShowHandler=null,this.lifecycleHandlersAttached=!1))}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let o=null;try{o=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!o)return;this.debugLog("RECV",{topic:e,sender:o.sender,type:o.type,contentType:o.metadata?.contentType,templateId:o.metadata?.templateId,messageId:o.message_id,text:typeof o.text=="string"?o.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const c=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof o.status=="number"?o.status:Number(o.status??0),f={conversationId:c,messageId:u,status:d,raw:o};this.statusUpdateHandlers.forEach(g=>g(f)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),a=i?.groups?.conversationId,l={topic:e,conversationId:a,messageId:typeof o.message_id=="string"?o.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(c=>c(o,l))}buildOutgoingEnvelope(e,t){const r={...Wd,...this.config.messageDefaults??{}},o=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:o,senderFullname:o,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(o,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(o,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const a=i[n];return a?a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function zd(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(e[t]=r);return e}function El(s,e){return(s.sender??"").toString()===e}function Al(s,e){const t=(s.sender??"").toString(),r=e.systemSenders??["metadata","system"],o=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(o)?"assistant":r.includes(t)?"system":"agent":"system"}function vo(s){const e={raw:s},t=s.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 s.text=="string"&&s.text.trim().startsWith("{"))try{const o=s.text.replace(/\\(?!["\\/bfnrtu])/g,"\\\\"),n=JSON.parse(o);typeof n.message=="string"&&(e.innerMessage=n.message);const i=n.metadata;i&&typeof i=="object"&&(typeof i.contentType=="string"&&(e.contentType=i.contentType),typeof i.templateId=="string"&&(e.templateId=i.templateId),i.payload!==void 0&&(e.payload=i.payload))}catch{}const r=s.attributes;if(r&&typeof r=="object"){const o=r.attachment;!e.contentType&&typeof r.contentType=="string"&&(e.contentType=r.contentType),!e.contentType&&o&&typeof o.contentType=="string"&&(e.contentType=o.contentType),!e.templateId&&typeof r.templateId=="string"&&(e.templateId=r.templateId),!e.templateId&&o&&typeof o.templateId=="string"&&(e.templateId=o.templateId),e.payload===void 0&&r.payload!==void 0&&(e.payload=r.payload),e.payload===void 0&&o&&o.payload!==void 0&&(e.payload=o.payload),e.payload===void 0&&o&&o.template!==void 0&&(e.payload=o.template)}return e}function Il(s){const e=vo(s);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const o=r[0],n=o.action,i=n&&typeof n.url=="string"?n.url:void 0,a=typeof o.description=="string"?o.description:void 0,l=s.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!a?null:{fileName:a,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function Tl(s,e,t){const r=Al(s,t),o=vo(s),n=Il(s);let i="";o.innerMessage?i=o.innerMessage:typeof s.text=="string"&&(s.text.trim().startsWith("{")?o.contentType!=="300"&&(i=s.text):i=s.text);const a=typeof s.message_id=="string"?s.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof s.timestamp=="number"?new Date(s.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof s.status=="number"?Vd(s.status):"delivered",d={id:a,externalId:a,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:s.sender,sender_fullname:s.sender_fullname??s.senderFullname,app_id:s.app_id,attributes:s.attributes}};return o.contentType&&(d.template={contentType:o.contentType,templateId:o.templateId,payload:o.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:o}}function Vd(s){return s<0?"error":s>=250?"read":s>=150?"delivered":"sent"}class Cl extends mr{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 Fo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new qo,this.conversationManager=new Ko(e.conversationId),this.usesAikaara()&&(this.connection=new $o(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)}),this.connection.on("reconnected",()=>{this.resubscribeAfterReconnect()})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Sl({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const o=r?"connected":"disconnected";this.emit("connection:state",o),this.config.onConnectionStateChange?.(o)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,o)=>this.handleTiledeskMessage(r,o))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),o=this.config.tiledesk?.autoInitiateOnEmpty??!0,n=this.config.tiledesk?.autoInitiateOnUnknown??!1;o&&(r==="empty"||r==="unknown"&&n)&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(l){return this.config.onError?.(l instanceof Error?l:new Error(String(l))),"unknown"}if(!r.length)return"empty";const o=r.map(l=>Tl(l,e,{userId:t})).sort((l,c)=>new Date(l.message.createdAt).getTime()-new Date(c.message.createdAt).getTime()),n=o.map(l=>l.message),i=this.messageStore.messages,a=[...n,...i.filter(l=>!n.some(c=>c.externalId&&c.externalId===l.externalId))];this.messageStore.setMessages(a);for(const{message:l,template:c}of o){if(this.config.onMessage)try{this.config.onMessage(l)}catch(u){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",u)}if(this.config.onTemplateMessage&&c.contentType){const u={messageId:l.id,conversationId:e,role:l.role==="tool"?"system":l.role,contentType:c.contentType,templateId:c.templateId,payload:c.payload,innerMessage:c.innerMessage,raw:c.raw};try{this.config.onTemplateMessage(u)}catch(d){console.warn("[aikaara-chat-sdk] onTemplateMessage threw on history replay",d)}}}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",o),this.config.onMessage?.(o);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const o=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:o.fileName,fileUrl:o.url,cloudFileId:o.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const o=this.conversationManager.conversationId;if(!o)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(o,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=this.conversationManager.conversationId;if(t.conversationId&&r&&t.conversationId!==r)return;const o=t.conversationId??r;if(!o)return;const n=this.config.tiledeskIdentity?.userId??"",{message:i,template:a}=Tl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(El(e,n)){const u=this.messageStore.reconcileOptimistic(i);if(u){this.emit("message:updated",u);return}}const{message:l,deduped:c}=this.messageStore.upsertRemoteMessage(i);if(c)this.emit("message:updated",l);else{this.emit("message:received",l),this.config.onMessage?.(l);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:l.role,hasAttachments:Array.isArray(l.attachments)&&l.attachments.length>0,templateId:l.template?.templateId,messageId:l.id,conversationId:l.conversationId}}))}catch{}}if(a.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:a.contentType,templateId:a.templateId,payload:a.payload,innerMessage:a.innerMessage,raw:e};this.config.onTemplateMessage?.(u)}}handleTiledeskStatusUpdate(e){const t=this.conversationManager.conversationId;t&&e.conversationId!==t||(e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered"))}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}async resubscribeAfterReconnect(){const e=this.conversationManager.conversationId;if(!(!e||!this.connection))try{this.subscription=await this.connection.subscribeToConversation(e),this.subscription.onReceived(t=>{this.handleBroadcast(t)})}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.config.onError?.(t instanceof Error?t:new Error(String(t)))}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",o=e.content||"";o?this.messageStore.updateStreaming(o):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,o=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),o&&(this.emit("stream:end",{messageId:o.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",o),this.config.onMessage?.(o));break}case"message_queued":{const r=this.messageStore.messages.findLast(o=>o.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class Kd extends mr{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const Pl={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 Gd(s){const e=s.lastIndexOf(".");return e<0||e===s.length-1?"":s.slice(e+1).toLowerCase()}function Yd(s,e,t){const r=Gd(s.name||"");if(r&&e&&e[r])return e[r];const o=s.type;return o&&o.trim().length>0?o:r&&Pl[r]?Pl[r]:t}function wo(s,e){return s.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function Jd(s,e){const t=e.split(".");let r=s;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function Ol(s){const e=s.signedUrlPath||"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Yd(t,s.contentTypeMap,s.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},a=s.authHeader?await s.authHeader():void 0,l={accept:"application/json",...s.extraHeaders??{},...a?{authorization:a}:{}};let c=s.signEndpoint.includes("{")?s.signEndpoint:`${s.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=wo(c,i),d=await fetch(u,{method:s.signMethod??"GET",headers:l});if(!d.ok)throw new Error(`Sign request failed: ${d.status}`);const f=await d.json().catch(()=>({})),g=Jd(f,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const h=s.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,s.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(s.registerEndpoint){const w=JSON.parse(wo(JSON.stringify(s.registerBody??{}),i)),m=await fetch(s.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:s.viewerTemplate?wo(s.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function ko(s){return{async upload(e,t){const r=new FormData,o=s.fieldName??"file";r.append(o,e,e.name);const n=typeof s.extraFields=="function"?s.extraFields(t):s.extraFields;if(n)for(const[f,g]of Object.entries(n))r.append(f,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof s.headers=="function"?await s.headers():s.headers??{},a=await fetch(s.endpoint,{method:s.method??"POST",body:r,headers:i,credentials:s.credentials});if(!a.ok)throw new Error(`Upload failed: ${a.status} ${a.statusText}`);const l=await a.json().catch(()=>({}));if(s.parseResponse)return s.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 Qd="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function Ml(s){const e=s.apiBase.replace(/\/$/,""),t=s.pageSize??200,r=s.pathTemplate??Qd;return{async fetchMessages(o,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(o)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),a=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...s.extraHeaders??{}};if(s.getToken){const f=await s.getToken();f&&(l.authorization=f)}const c=await fetch(a,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(s.parseResponse&&u)return s.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 Xd=[{id:"salary-hra",title:"Salary / HRA / Allowances",icon:"💰",dataPath:"salaryDetails[]",repeatable:{maxCount:4,labelTemplate:"Employer {index}"},entryIcon:"🏢",fields:[{id:"employerDetails",type:"group",title:"Employer Details",fields:[{id:"employerName",type:"text",label:"Employer Name",required:!0},{id:"employerTan",type:"text",label:"TAN (Tax Deduction Account Number)",pattern:"^[A-Z]{4}[0-9]{5}[A-Z]$",maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0},{id:"totalTdsDeposited",type:"number",label:"TDS Deducted",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"business44ad",type:"group",title:"Business Income 44AD",collapsible:!0,defaultCollapsed:!0,fields:[{id:"bizName",type:"text",label:"Business / Profession Name"},{id:"bizNature",type:"text",label:"Nature of Work"},{id:"bizReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"bizReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"bizNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]},{id:"profession44ada",type:"group",title:"Professional Income 44ADA",collapsible:!0,defaultCollapsed:!0,fields:[{id:"profName",type:"text",label:"Business / Profession Name"},{id:"profNature",type:"text",label:"Nature of Work"},{id:"profReceiptsBank",type:"number",label:"Gross Receipts (Bank)",currency:"₹",min:0},{id:"profReceiptsCash",type:"number",label:"Gross Receipt (Cash)",currency:"₹",min:0},{id:"profNetProfit",type:"number",label:"Net Profit",currency:"₹",readOnly:!0}]}],submitLabel:"Save"},{id:"other-sources",title:"Income from Other Sources",icon:"💵",fields:[{id:"interestIncome",type:"group",title:"Interest Income",fields:[{id:"savingBankInterest",type:"number",label:"Savings Bank Interest",currency:"₹",min:0},{id:"fdInterest",type:"number",label:"Fixed Deposit Interest",currency:"₹",min:0}]},{id:"otherIncomeGroup",type:"group",title:"Other Income",fields:[{id:"dividend",type:"number",label:"Dividend Income",currency:"₹",min:0},{id:"anyOtherIncome",type:"number",label:"Any Other Income",currency:"₹",min:0},{id:"familyPension",type:"number",label:"Family Pension",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"crypto-income",title:"Crypto Income",icon:"🪙",fields:[{id:"cryptoGroup",type:"group",title:"Virtual Digital Assets",hint:"Gains from crypto / VDAs are taxed at a flat 30%",fields:[{id:"cryptoSellPrice",type:"number",label:"Total Sale Value",currency:"₹",min:0},{id:"cryptoPurchasePrice",type:"number",label:"Total Cost of Acquisition",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"bank-details",title:"Personal / Bank Details",icon:"🏦",fields:[{id:"bankGroup",type:"group",title:"Bank Account (for refund)",fields:[{id:"aadhaarNumber",type:"text",label:"Aadhaar Number",maxLength:12,readOnly:!0},{id:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:"^[A-Z]{4}0[A-Z0-9]{6}$",maxLength:11}]}],submitLabel:"Save"}];function Zd(s,e){const t=s||{},r={userId:zt(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Ie(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Ie(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Ie(t.us80dForParentsAmount),r.hasParentOverSixty=_o(t.hasParentOverSixty),r.preventiveHealthCheckUp=Ie(t.preventiveHealthCheckUp),r.medicalExpenditure=Ie(t.medicalExpenditure),r.savingBankInterest=Ie(t.savingBankInterest),r.fdInterest=Ie(t.fdInterest),r.dividend=Ie(t.dividend),r.anyOtherIncome=Ie(t.anyOtherIncome),r.cryptoSellValue=Ie(t.cryptoSellPrice),r.cryptoPurchaseAmount=Ie(t.cryptoPurchasePrice),r.vdaPurchaseCost=Ie(t.cryptoPurchasePrice);const o=(Ie(t.bizReceiptsBank)??0)+(Ie(t.bizReceiptsCash)??0),n=(Ie(t.profReceiptsBank)??0)+(Ie(t.profReceiptsCash)??0),i=Me(t.bizName)!==void 0||o>0;r.businessName=Me(i?t.bizName:t.profName),r.businessAnnualTurnOver=i?o||void 0:n||void 0,r.agricultureDetails={income:Ie(t.agricultureIncome)},r.exemptIncomeAmount=Ie(t.exemptIncome),r.exemptIncomeNature=Me(t.exemptIncomeNature),Ie(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Me(t.exemptIncomeNature)??"Exempt income",value:String(Ie(t.exemptIncome))}]),r.bankAccountNumber=Me(t.bankAccountNumber),r.bankIfscCode=Me(t.bankIfscCode),(Me(t.bankAccountNumber)||Me(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Me(t.bankAccountNumber),bankIfscCode:Me(t.bankIfscCode)}]);const a={description:Me(t.immovableAssetDescription),flatNo:Me(t.immovableAssetFlatNo),area:Me(t.immovableAssetArea),pinCode:Me(t.immovableAssetPincode),amount:Ie(t.immovableAssetCost)};Object.values(a).some(u=>u!==void 0)&&(r.immovableAsset=[a]);const l=xo(t.hpDetails,eh);l.length&&(r.hpDetails=l);const c=xo(t.salaryDetails,th);if(c.length){r.salaryIncome=c;const u=xo(t.salaryDetails,f=>({grossSalary:Ie(f.grossSalary),employerName:Me(f.employerName)}));u.length&&(r.salary=u);const d=Rl(t.salaryDetails)[0]??{};r.hraAmount=Ie(d.hraReceived),r.leaveTravelAllowanceAmount=Ie(d.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Ie(d.leaveEncashment),r.anyOtherAllowanceAmount=Ie(d.anyOtherAllowance),r.salaryIncomeFlag=!0}return Xr(r)}function eh(s){const e={loanType:"HOME_LOAN",loanTakenFrom:Me(s.loanTakenFrom),bankOrInstituteName:Me(s.lenderName),loanAccountNo:Me(s.loanAccountNumber),loanSanctionDate:ah(s.sanctionDate),totalLoanAmount:Ie(s.totalLoanAmount),interest:Ie(s.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Me(s.typeOfHouseProperty),hasRentalIncome:s.typeOfHouseProperty==="LOP"?!0:_o(s.hasRentalIncome),homeLoanInterest:Ie(s.homeLoanInterest),homeLoanPrinciple:Ie(s.homeLoanPrinciple),housePropertyAddress:Me(s.housePropertyAddress),housePropertyPincode:Me(s.housePropertyPincode),rentalIncome:Ie(s.rentalIncome),nameOfTenant:Me(s.nameOfTenant),propertyTax:Ie(s.propertyTax),hasCoOwnedProperty:_o(s.hasCoOwnedProperty),coOwnerName:Me(s.coOwnerName),coOwnerPan:Me(s.coOwnerPan),coOwnerShare:Me(s.coOwnerShare),loanDetails:t?[e]:void 0}}function th(s){return{grossSalaryIncome:Ie(s.grossSalary),salary:Ie(s.basicSalary),employer:{employerName:Me(s.employerName),employerTan:Me(s.employerTan)},allowance:{hraAmount:Ie(s.hraReceived),leaveTravelAllowanceAmount:Ie(s.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Ie(s.leaveEncashment),anyOtherAllowanceAmount:Ie(s.anyOtherAllowance)}}}function rh(s,e){const t=[];for(const r of s){const o=Me(r.employerName),n=Me(r.employerTan),i=Ie(r.grossSalary),a=Ie(r.basicSalary),l=Ie(r.totalTdsDeposited);o===void 0&&n===void 0&&i===void 0&&a===void 0&&l===void 0||t.push({grossSalary:i??0,basicSalary:a??0,employerName:o??"",tanNumber:n??"",tdsDeducted:l??0})}return t.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,forceUpdate:!0,salary:t}:null}function nh(s,e){const t=Me(s.aadhaarNumber),r=Me(s.bankAccountNumber),o=Me(s.bankIfscCode);return t===void 0&&r===void 0&&o===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,aadhaarNumber:t??"",bankDetails:[{bankAccountNumber:r,bankIfscCode:o}]}}function ih(s,e){return{userId:zt(e.userId),assessmentYear:e.assessmentYear,savingBankInterest:Ie(s.savingBankInterest)??0,fdInterest:Ie(s.fdInterest)??0,dividend:Ie(s.dividend)??0,anyOtherIncome:Ie(s.anyOtherIncome)??0,familyPension:Ie(s.familyPension)??0}}function oh(s,e){const t=Ie(s.cryptoSellPrice),r=Ie(s.cryptoPurchasePrice);return t===void 0&&r===void 0?null:{userId:zt(e.userId),assessmentYear:e.assessmentYear,vdaPurchaseCost:r??0,vdaSellCost:t??0}}function sh(s,e){const t=(o,n,i,a)=>{const l=Me(s[o]),c=Me(s[n]),u=Ie(s[i]),d=Ie(s[a]);return l===void 0&&c===void 0&&u===void 0&&d===void 0?null:{businessType:l??"",businessCode:c??"",cashAmount:d??0,bankAmount:u??0}},r=[t("bizName","bizNature","bizReceiptsBank","bizReceiptsCash"),t("profName","profNature","profReceiptsBank","profReceiptsCash")].filter(o=>o!==null);return r.length?{userId:zt(e.userId),assessmentYear:e.assessmentYear,presumptiveIncome:r}:null}function zt(s){if(s===void 0||s==="")return;const e=Number(s);return Number.isFinite(e)&&String(e)===String(s)?e:s}function Ie(s){if(s==null||s==="")return;const e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:void 0}function Me(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function _o(s){return s===!0||s===!1?s:void 0}function ah(s){const e=Me(s);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function Rl(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function xo(s,e){return Rl(s).map(t=>Xr(e(t))).filter(t=>t!==void 0)}function Xr(s){if(Array.isArray(s)){const e=s.map(Xr).filter(t=>t!==void 0);return e.length?e:void 0}if(s&&typeof s=="object"){const e={};for(const[t,r]of Object.entries(s)){const o=Xr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return s}function lh(s){const e=s&&typeof s=="object"?s:{},t={},r=qe(e.employers),o=qe(e.taxPaid?.onSalary);r.length&&(t.salaryDetails=r.map(d=>{const f=So(d.salary),g=So(d.perquisites),h=So(d.profitsInLieuOfSalaryType),b=f+g+h,y=uh(d.allowance);return{employerName:Le(d.employerName),employerTan:Le(d.employerTAN),basicSalary:f||void 0,grossSalary:b||void 0,hraReceived:y.hra,leaveTravelAllowance:y.lta,leaveEncashment:y.leaveEncashment,anyOtherAllowance:y.other,totalTdsDeposited:ch(d,o,r)??Ue(d.totalTdsDeposited)}}));const n=qe(e.houseProperties);n.length&&(t.hpDetails=n.map(d=>{const f=qe(d.loanDetails),g=f.length?f[0]:void 0,h=Ue(d.grossAnnualRentReceived),b=f.length?f.reduce((x,v)=>x+(Ue(v.interest)??0),0):void 0,y=qe(d.tenant),w=qe(d.coOwners),m=y[0],k=w[0];return{typeOfHouseProperty:Le(d.propertyType),loanTakenFrom:Le(g?.loanTakenFrom),lenderName:Le(g?.bankOrInstituteName),loanAccountNumber:Le(g?.loanAccountNo),sanctionDate:Le(g?.loanSanctionDate),totalLoanAmount:Ue(g?.totalLoanAmount),outstandingAmount:Ue(g?.loanOutstandingAmount),homeLoanInterest:b,homeLoanPrinciple:void 0,housePropertyAddress:Le(d.address),housePropertyPincode:Le(d.pinCode),rentalIncome:h,nameOfTenant:Le(m?.name),propertyTax:Ue(d.propertyTax),hasCoOwnedProperty:w.length>0,coOwnerName:Le(k?.name),coOwnerPan:Le(k?.panNumber),coOwnerShare:Ue(k?.share)?.toString()}})),t.us80cAmount=Lt(qe(e.deductionUS80CDetails).map(d=>Ue(d.amount))),t.us80dForSelfAndFamilyAmount=Lt(qe(e.deductionUS80DDetails).map(d=>Ue(d.healthInsuranceAmount)));const i=qe(e.incomes),a=d=>Lt(i.filter(f=>Le(f.incomeType)===d).map(f=>Ue(f.amount)));t.savingBankInterest=a("SAVING_INTEREST"),t.fdInterest=a("FD_RD_INTEREST"),t.anyOtherIncome=a("ANY_OTHER"),t.familyPension=a("FAMILY_PENSION"),t.dividend=Lt(qe(e.dividendIncomes).map(d=>Ue(d.income)));const l=e.business;if(l){const d=qe(l.presumptiveIncomes),f=b=>{const y=qe(b.incomes),w=m=>Ue(y.find(k=>Le(k.incomeType)===m)?.receipts)??0;return w("ANY_OTHER")>0?!0:w("BANK")>0||w("CASH")>0?!1:!!Le(b.businessType)?.toUpperCase().includes("PROFESSION")},g=b=>d.find(y=>f(y)===b),h=(b,y)=>{if(!b)return;const w=qe(b.incomes),m=x=>Ue(w.find(v=>Le(v.incomeType)===x)?.receipts),k=m("BANK")||m("ANY_OTHER");t[y.name]=Le(b.businessType),t[y.nature]=Le(b.natureOfBusiness),t[y.bank]=k||void 0,t[y.cash]=m("CASH")||void 0,t[y.net]=Lt(w.map(x=>Ue(x.presumptiveIncome)))||void 0};h(g(!1),{name:"bizName",nature:"bizNature",bank:"bizReceiptsBank",cash:"bizReceiptsCash",net:"bizNetProfit"}),h(g(!0),{name:"profName",nature:"profNature",bank:"profReceiptsBank",cash:"profReceiptsCash",net:"profNetProfit"})}const c=qe(e.capitalGain).filter(d=>Le(d.assetType)?.toUpperCase()==="VDA").flatMap(d=>qe(d.assetDetails));c.length&&(t.cryptoSellPrice=Lt(c.map(d=>Ue(d.sellValue))),t.cryptoPurchasePrice=Lt(c.map(d=>Ue(d.purchaseCost)))),t.agricultureIncome=Ue(e.agriculturalDetails?.income),t.aadhaarNumber=Le(e.aadharNumber);const u=qe(e.bankDetails)[0];return u&&(t.bankAccountNumber=Le(u.accountNumber),t.bankIfscCode=Le(u.ifsCode)),Ll(t)}function So(s){return qe(s).reduce((e,t)=>e+(Ue(t.taxableAmount)??0),0)}function ch(s,e,t){if(!e.length)return;const r=Le(s.employerTAN)?.trim().toUpperCase();if(r){for(const n of e)if(Le(n.deductorTAN)?.trim().toUpperCase()===r)return Ue(n.totalTdsDeposited)}const o=Le(s.employerName)?.trim().toLowerCase();if(o){for(const n of e)if(Le(n.deductorName)?.trim().toLowerCase()===o)return Ue(n.totalTdsDeposited)}if(t.length===1&&e.length===1)return Ue(e[0].totalTdsDeposited)}function uh(s){const e=qe(s);if(!e.length)return{};let t,r,o,n;for(const i of e){const a=Ue(i.exemptAmount)??Ue(i.allowanceAmount);switch(Le(i.allowanceType)?.toUpperCase()){case"HRA":case"HOUSE_RENT_ALLOWANCE":t=a;break;case"LTA":case"LEAVE_TRAVEL_ALLOWANCE":r=a;break;case"LEAVE_ENCASHMENT":o=a;break;default:n=(n??0)+(Ue(i.allowanceAmount)??0)}}return{hra:t,lta:r,leaveEncashment:o,other:n}}function Lt(s){let e=0,t=!1;for(const r of s)r!=null&&(e+=r,t=!0);return t?e:void 0}function qe(s){return Array.isArray(s)?s.filter(e=>e&&typeof e=="object"):[]}function Ue(s){if(typeof s=="number"&&Number.isFinite(s))return s;if(typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s)))return Number(s)}function Le(s){if(s==null)return;const e=String(s).trim();return e===""?void 0:e}function Ll(s){const e={};for(const[t,r]of Object.entries(s))r!==void 0&&(Array.isArray(r)?e[t]=r.map(o=>o&&typeof o=="object"?Ll(o):o):e[t]=r);return e}function Eo(){if(typeof window>"u")return null;const s=window,e=s.__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=s.__aikaara_descriptor__??{},r=yh(t);if(!r)return console.warn("[smart-edit] API disabled: could not resolve a TaxBuddy API host from the descriptor (cloud / upload / pan / leader endpoints)."),null;const o=vh(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,a=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):kh(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:a,headers:wh(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||_h(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function dh(s){const e=await s.getToken(),t=s.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${s.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...s.headers}});if(!r.ok){const o=await r.text().catch(()=>"");throw new Error(`[smart-edit] GET /itr/latest-itr → ${r.status} ${o.slice(0,200)}`)}return lh(Ao(await r.json().catch(()=>({}))))}async function hh(s,e){const t=await s.getToken(),r=s.userId,o={...Zd(e,{userId:r,assessmentYear:s.assessmentYear,isRevised:s.isRevised}),sendSummary:!0},n=s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...s.headers};s.txbdyApiKey&&(i["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const a=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${a.status} ${l.slice(0,200)}`)}return Ao(await a.json().catch(()=>({})))}async function fh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/salary`,e)}async function ph(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/bank-aadhaar`,e)}async function mh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function gh(s,e){return sr(s,s.submitUrl||`${s.baseUrl}/itr/v1/automation/data`,e)}async function bh(s,e){return sr(s,`${s.baseUrl}/itr/v1/automation/vda`,e)}async function sr(s,e,t){const o={accept:"application/json","content-type":"application/json",authorization:`Bearer ${await s.getToken()}`,...s.headers};s.txbdyApiKey&&(o["txbdy-api-key"]=s.txbdyApiKey),console.info("[smart-edit] PUT",e,"— body keys:",Object.keys(t).join(", "));const n=await fetch(e,{method:"PUT",headers:o,body:JSON.stringify(t)});if(!n.ok){const i=await n.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${e} → ${n.status} ${i.slice(0,200)}`)}return Ao(await n.json().catch(()=>({})))}function yh(s){const e=[s.cloud?.listEndpoint,s.cloud?.downloadEndpoint,s.upload?.signEndpoint,s.login?.pan?.basicPanEndpoint,s.login?.pan?.panDetailEndpoint,s.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 vh(s){if(!s||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${s}`);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 wh(s){const e={};if(!s)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(s))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function kh(s){if(!s)return;const e=s.userId??s.id??s.ext_uid??s.extUid;return e==null||e===""?void 0:String(e)}function Ao(s){if(s&&typeof s=="object"){const e=s;return e.data&&typeof e.data=="object"?e.data:e}return{}}function _h(){const s=new Date,e=s.getMonth()>=3?s.getFullYear():s.getFullYear()-1;return`${e}-${e+1}`}class xh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new Cl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),e.chatActions!==void 0&&this.header.setActions(e.chatActions),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.header.addEventListener("aikaara-chat-action",(e=>{this.handleChatAction(e.detail)})),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e),requestAnimationFrame(()=>{setTimeout(()=>{this.messageList.showTypingIndicator()},100)})}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e);const t=this.client.config?.tiledeskIdentity?.userId;e.metadata?.sender&&t&&e.metadata.sender!==t&&this.messageList.removeTypingIndicator()}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;if(this.shouldOpenSmartEdit(t.text)){this.openSmartEdit();return}const r=this.client.config.templateActionAttributes??{},o=t.attributes?.action??{},n={...t.attributes,action:{...r,...o}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}async handleChatAction(e){if(e.id==="edit-itr"){this.openSmartEdit();return}console.info("[chat-action]",e.id,e.label)}shouldOpenSmartEdit(e){const t=window.__aikaara_descriptor__?.smartEdit?.openOnMessages;if(!Array.isArray(t)||t.length===0)return!1;const r=n=>n.trim().toLowerCase(),o=r(e);return t.some(n=>typeof n=="string"&&r(n)===o)}async openSmartEdit(){const e=this.ensureSmartEditModal();e.open({schemas:Xd,data:{}});const t=Eo();if(!(!t||!t.baseUrl))try{const r=await dh(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=Eo();if(!r)return;const o={userId:r.userId,assessmentYear:r.assessmentYear};try{if(e==="salary-hra"){const n=Array.isArray(t.salaryDetails)?t.salaryDetails:[],i=rh(n,o);i&&await fh(r,i)}else if(e==="bank-details"){const n=nh(t,o);n&&await ph(r,n)}else if(e==="other-sources")await mh(r,ih(t,o));else if(e==="business-profession"){const n=sh(t,o);n&&await gh(r,n)}else if(e==="crypto-income"){const n=oh(t,o);n&&await bh(r,n)}}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=Eo();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await hh(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 Nl 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||Oc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Bo,position:this.getAttribute("position")||this._config.position||Pc,width:Number(this.getAttribute("width"))||this._config.width||Ac,height:Number(this.getAttribute("height"))||this._config.height||Ic,fontFamily:this._config.fontFamily||Cc,borderRadius:this._config.borderRadius??Tc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||Do,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||Mc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,o){if(typeof document>"u")return;const n=document.documentElement,i=(a,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${a}`,l)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??o),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=o=>typeof o=="number"?`${o}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,o])=>o!==void 0&&o!=="").map(([o,n])=>`--aikaara-${o}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
package/dist/headless.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-BEaYaZMk.cjs");class s extends e.EventEmitter{registration=null;pendingEdits=[];constructor(t){super(),this.setupListeners(t)}registerForm(t){this.registration=t;const i=this.pendingEdits.filter(r=>r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId));if(i.length>0){for(const r of i)t.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId)))}}unregisterForm(t,i){this.registration?.entityType===t&&String(this.registration?.entityId)===String(i)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(t,i,r){this.registration&&this.registration.entityType===t&&String(this.registration.entityId)===String(i)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:t,entityId:i,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:t,entity_id:i,fields:r}),this.emit("edit:pending",{entityType:t,entityId:i,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(t){const i=t instanceof Error?t.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:i}),{success:!1,error:i}}}async requestTest(t){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(t),{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Test failed"}}}setupListeners(t){t.on("action:edit_entity",i=>{this.pushFieldUpdates(i.entity_type,i.entity_id,i.fields)}),t.on("action:save_entity",i=>{this.requestSave()}),t.on("action:test_tool",i=>{this.emit("test:triggered",{toolId:i.tool_id,parameters:i.parameters}),this.requestTest(i.parameters)})}}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.runMethodSelectPreflight=e.runMethodSelectPreflight;exports.FormBridge=s;
|
package/dist/headless.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as s } from "./MountTenant-
|
|
2
|
-
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b, G as w } from "./MountTenant-
|
|
1
|
+
import { E as s } from "./MountTenant-DcEbdQPG.mjs";
|
|
2
|
+
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b, G as w } from "./MountTenant-DcEbdQPG.mjs";
|
|
3
3
|
class a extends s {
|
|
4
4
|
registration = null;
|
|
5
5
|
pendingEdits = [];
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-BEaYaZMk.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,n]of Object.entries(i)){const r=a[o];r!=null&&t.setAttribute(n,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.runMethodSelectPreflight=e.runMethodSelectPreflight;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as o } from "./MountTenant-
|
|
2
|
-
import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as T, h as b, i as f, j as v, k as S, C as y, l as M, m as w, E, M as x, S as B, n as F, T as U, o as D, p as I, q as P, s as j, t as q, u as H, v as R, w as W, x as z, y as G, z as K, B as L, D as O, F as J, G as N } from "./MountTenant-
|
|
1
|
+
import { r as o } from "./MountTenant-DcEbdQPG.mjs";
|
|
2
|
+
import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as T, h as b, i as f, j as v, k as S, C as y, l as M, m as w, E, M as x, S as B, n as F, T as U, o as D, p as I, q as P, s as j, t as q, u as H, v as R, w as W, x as z, y as G, z as K, B as L, D as O, F as J, G as N } from "./MountTenant-DcEbdQPG.mjs";
|
|
3
3
|
import { FormBridge as V } from "./headless.mjs";
|
|
4
4
|
function l(e) {
|
|
5
5
|
o();
|
package/dist/ui.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-BEaYaZMk.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraComparePlans=a.AikaaraComparePlans;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraLinkModal=a.AikaaraLinkModal;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraSchemaForm=a.AikaaraSchemaForm;exports.AikaaraSmartEditModal=a.AikaaraSmartEditModal;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTextInput=a.AikaaraTextInput;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
|
package/dist/ui.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { I as i, a as s, c as e, d as t, e as A, J as k, f as n, K as o, g as m, h as d, L as l, N as g, O as p, P as h, i as C, Q as M, R as b, U as c, V as u, j as S, r as I } from "./MountTenant-
|
|
1
|
+
import { I as i, a as s, c as e, d as t, e as A, J as k, f as n, K as o, g as m, h as d, L as l, N as g, O as p, P as h, i as C, Q as M, R as b, U as c, V as u, j as S, r as I } from "./MountTenant-DcEbdQPG.mjs";
|
|
2
2
|
export {
|
|
3
3
|
i as AikaaraChat,
|
|
4
4
|
s as AikaaraChatBubble,
|