@aikaara/chat-sdk 1.4.13 → 1.4.15

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.
@@ -11640,56 +11640,59 @@ class dh extends qs {
11640
11640
  // --- Tiledesk inbound handling -------------------------------------------
11641
11641
  handleTiledeskMessage(e, t) {
11642
11642
  if (t.kind === "update") return;
11643
- const r = t.conversationId ?? this.conversationManager.conversationId;
11644
- if (!r) return;
11645
- const o = this.config.tiledeskIdentity?.userId ?? "", { message: n, template: i } = Rs(e, r, {
11646
- userId: o,
11643
+ const r = this.conversationManager.conversationId;
11644
+ if (t.conversationId && r && t.conversationId !== r) return;
11645
+ const o = t.conversationId ?? r;
11646
+ if (!o) return;
11647
+ const n = this.config.tiledeskIdentity?.userId ?? "", { message: i, template: s } = Rs(e, o, {
11648
+ userId: n,
11647
11649
  systemSenders: this.config.tiledesk?.messageDefaults?.attributes?.systemSenders
11648
11650
  });
11649
- if (this.mode === "dual" && n.role === "assistant") return;
11650
- if (lh(e, o)) {
11651
- const c = this.messageStore.reconcileOptimistic(n);
11652
- if (c) {
11653
- this.emit("message:updated", c);
11651
+ if (this.mode === "dual" && i.role === "assistant") return;
11652
+ if (lh(e, n)) {
11653
+ const u = this.messageStore.reconcileOptimistic(i);
11654
+ if (u) {
11655
+ this.emit("message:updated", u);
11654
11656
  return;
11655
11657
  }
11656
11658
  }
11657
- const { message: s, deduped: a } = this.messageStore.upsertRemoteMessage(n);
11658
- if (a)
11659
- this.emit("message:updated", s);
11659
+ const { message: a, deduped: c } = this.messageStore.upsertRemoteMessage(i);
11660
+ if (c)
11661
+ this.emit("message:updated", a);
11660
11662
  else {
11661
- this.emit("message:received", s), this.config.onMessage?.(s);
11663
+ this.emit("message:received", a), this.config.onMessage?.(a);
11662
11664
  try {
11663
11665
  typeof window < "u" && window.dispatchEvent(
11664
11666
  new CustomEvent("aikaara:message", {
11665
11667
  detail: {
11666
- role: s.role,
11667
- hasAttachments: Array.isArray(s.attachments) && s.attachments.length > 0,
11668
- templateId: s.template?.templateId,
11669
- messageId: s.id,
11670
- conversationId: s.conversationId
11668
+ role: a.role,
11669
+ hasAttachments: Array.isArray(a.attachments) && a.attachments.length > 0,
11670
+ templateId: a.template?.templateId,
11671
+ messageId: a.id,
11672
+ conversationId: a.conversationId
11671
11673
  }
11672
11674
  })
11673
11675
  );
11674
11676
  } catch {
11675
11677
  }
11676
11678
  }
11677
- if (i.contentType) {
11678
- const c = {
11679
- messageId: s.id,
11680
- conversationId: r,
11681
- role: n.role === "tool" ? "system" : n.role,
11682
- contentType: i.contentType,
11683
- templateId: i.templateId,
11684
- payload: i.payload,
11685
- innerMessage: i.innerMessage,
11679
+ if (s.contentType) {
11680
+ const u = {
11681
+ messageId: a.id,
11682
+ conversationId: o,
11683
+ role: i.role === "tool" ? "system" : i.role,
11684
+ contentType: s.contentType,
11685
+ templateId: s.templateId,
11686
+ payload: s.payload,
11687
+ innerMessage: s.innerMessage,
11686
11688
  raw: e
11687
11689
  };
11688
- this.config.onTemplateMessage?.(c);
11690
+ this.config.onTemplateMessage?.(u);
11689
11691
  }
11690
11692
  }
11691
11693
  handleTiledeskStatusUpdate(e) {
11692
- e.status >= 250 ? this.messageStore.updateMessageStatus(e.messageId, "read") : e.status >= 150 && this.messageStore.updateMessageStatus(e.messageId, "delivered");
11694
+ const t = this.conversationManager.conversationId;
11695
+ t && e.conversationId !== t || (e.status >= 250 ? this.messageStore.updateMessageStatus(e.messageId, "read") : e.status >= 150 && this.messageStore.updateMessageStatus(e.messageId, "delivered"));
11693
11696
  }
11694
11697
  /**
11695
11698
  * Parse structured action results from tool execution output.
@@ -14578,7 +14581,7 @@ class vd extends HTMLElement {
14578
14581
  */
14579
14582
  mountLinkButton(e) {
14580
14583
  const t = this.renderGen;
14581
- import("./AikaaraLinkButton-BkmyI7Dk.mjs").then(({ registerAikaaraLinkButton: r, AikaaraLinkButton: o }) => {
14584
+ import("./AikaaraLinkButton-rE4Aoe2C.mjs").then(({ registerAikaaraLinkButton: r, AikaaraLinkButton: o }) => {
14582
14585
  if (t !== this.renderGen) return;
14583
14586
  r();
14584
14587
  const n = document.createElement("aikaara-link-button");
@@ -14906,7 +14909,7 @@ class Ed extends HTMLElement {
14906
14909
  const e = {}, t = this.closest("aikaara-template-renderer") ?? this.parentElement;
14907
14910
  return t && t.querySelectorAll("aikaara-option-list").forEach((r) => {
14908
14911
  const o = r.getValues?.();
14909
- o?.name && (e[o.name] = o.values);
14912
+ o?.name && (e[o.name] = o.type === "radio" ? o.values[0] ?? "" : o.values);
14910
14913
  }), e;
14911
14914
  }
14912
14915
  handleClick() {
@@ -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 Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Pe=typeof T=="function"?T(z):[],et;if(D){et={};for(var tt=0;tt<Pe.length;tt++)et["$"+Pe[tt]]=Pe[tt]}for(var He in z)oe(z,He)&&(Ee&&String(Number(He))===He&&He<z.length||D&&et["$"+He]instanceof Symbol||(E.call(/[^\w$]/,He)?Ae.push(ie(He,z)+": "+ie(z[He],z)):Ae.push(He+": "+ie(z[He],z))));if(typeof T=="function")for(var rt=0;rt<Pe.length;rt++)ae.call(z,Pe[rt])&&Ae.push("["+ie(Pe[rt])+"]: "+ie(z[Pe[rt]],z));return Ae}return Rr}function vh(){if(to)return jr;to=!0;var a=Dt(),e=ih(),t=yh(),r=Xt(),o=a("%WeakMap%",!0),n=a("%Map%",!0),i=e("WeakMap.prototype.get",!0),s=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=_,_},g=function(y,w){var m=p(y,w);return m&&m.value},f=function(y,w,m){var _=p(y,w);_?_.value=m:y.next={key:w,next:y.next,value:m}},b=function(y,w){return!!p(y,w)};return 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 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 h(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),s(y,x,v)):n?(w||(w=new n),u(w,x,v)):(m||(m={key:{},next:null}),f(m,x,v))}};return _},jr}function Zi(){if(ro)return Nr;ro=!0;var a=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Nr={default:t.RFC3986,formatters:{RFC1738:function(r){return a.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Nr}function Na(){if(no)return Ur;no=!0;var a=Zi(),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)},s=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,P=[],O=0;O<I.length;++O){var N=I.charCodeAt(O);if(N===45||N===46||N===95||N===126||N>=48&&N<=57||N>=65&&N<=90||N>=97&&N<=122||x===a.RFC1738&&(N===40||N===41)){P[P.length]=I.charAt(O);continue}if(N<128){P[P.length]=r[N];continue}if(N<2048){P[P.length]=r[192|N>>6]+r[128|N&63];continue}if(N<55296||N>=57344){P[P.length]=r[224|N>>12]+r[128|N>>6&63]+r[128|N&63];continue}O+=1,N=65536+((N&1023)<<10|I.charCodeAt(O)&1023),P[P.length]=r[240|N>>18]+r[128|N>>12&63]+r[128|N>>6&63]+r[128|N&63]}E+=P.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],P=v[I];typeof P=="object"&&P!==null&&m.indexOf(P)===-1&&(w.push({obj:v,prop:I}),m.push(P))}return o(w),y},p=function(y){return Object.prototype.toString.call(y)==="[object RegExp]"},g=function(y){return!y||typeof y!="object"?!1:!!(y.constructor&&y.constructor.isBuffer&&y.constructor.isBuffer(y))},f=function(y,w){return[].concat(y,w)},b=function(y,w){if(t(y)){for(var m=[],_=0;_<y.length;_+=1)m.push(w(y[_]));return m}return w(y)};return Ur={arrayToObject:n,assign:s,combine:f,compact:h,decode:l,encode:u,isBuffer:g,isRegExp:p,maybeMap:b,merge:i},Ur}function wh(){if(io)return Br;io=!0;var a=vh(),e=Na(),t=Zi(),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,s=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},h=function(b){return typeof b=="string"||typeof b=="number"||typeof b=="boolean"||typeof b=="symbol"||typeof b=="bigint"},p={},g=function b(y,w,m,_,x,v,E,S,I,P,O,N,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 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(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(P))te=P;else{var we=Object.keys(V);te=O?we.sort(O):we}var G=S?w.replace(/\./g,"%2E"):w,j=_&&n(V)&&V.length===1?G+"[]":G;if(x&&n(V)&&V.length===0)return j+"[]";for(var ne=0;ne<te.length;++ne){var W=te[ne],K=typeof W=="object"&&typeof W.value<"u"?W.value:V[W];if(!(E&&K===null)){var J=N&&S?W.replace(/\./g,"%2E"):W,ge=n(V)?typeof m=="function"?m(j,J):j:j+(N?"."+J:"["+J+"]");Y.set(y,F);var oe=a();oe.set(p,Y),s(be,b(K,ge,m,_,x,v,E,S,m==="comma"&&U&&n(V)?null:I,P,O,N,T,q,D,U,ae,oe))}}return be},f=function(b){if(!b)return u;if(typeof b.allowEmptyArrays<"u"&&typeof b.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof b.encodeDotInKeys<"u"&&typeof b.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(b.encoder!==null&&typeof b.encoder<"u"&&typeof b.encoder!="function")throw new TypeError("Encoder has to be a function.");var y=b.charset||u.charset;if(typeof b.charset<"u"&&b.charset!=="utf-8"&&b.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var w=t.default;if(typeof b.format<"u"){if(!r.call(t.formatters,b.format))throw new TypeError("Unknown format option provided.");w=b.format}var m=t.formatters[w],_=u.filter;(typeof b.filter=="function"||n(b.filter))&&(_=b.filter);var x;if(b.arrayFormat in o?x=b.arrayFormat:"indices"in b?x=b.indices?"indices":"repeat":x=u.arrayFormat,"commaRoundTrip"in b&&typeof b.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof b.allowDots>"u"?b.encodeDotInKeys===!0?!0:u.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:x,charset:y,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:u.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?u.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:u.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:u.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:u.encodeValuesOnly,filter:_,format:w,formatter:m,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:u.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:u.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:u.strictNullHandling}};return Br=function(b,y){var w=b,m=f(y),_,x;typeof m.filter=="function"?(x=m.filter,w=x("",w)):n(m.filter)&&(x=m.filter,_=x);var v=[];if(typeof w!="object"||w===null)return"";var E=o[m.arrayFormat],S=E==="comma"&&m.commaRoundTrip;_||(_=Object.keys(w)),m.sort&&_.sort(m.sort);for(var I=a(),P=0;P<_.length;++P){var O=_[P];m.skipNulls&&w[O]===null||s(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 N=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&"),N.length>0?T+N:""},Br}function _h(){if(oo)return Dr;oo=!0;var a=Na(),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:a.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},o=function(p){return p.replace(/&#(\d+);/g,function(g,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,g){return p&&typeof p=="string"&&g.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",l=function(p,g){var f={__proto__:null},b=g.ignoreQueryPrefix?p.replace(/^\?/,""):p;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var y=g.parameterLimit===1/0?void 0:g.parameterLimit,w=b.split(g.delimiter,y),m=-1,_,x=g.charset;if(g.charsetSentinel)for(_=0;_<w.length;++_)w[_].indexOf("utf8=")===0&&(w[_]===s?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,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=a.maybeMap(n(v.slice(S+1),g),function(N){return g.decoder(N,r.decoder,x,"value")})),P&&g.interpretNumericEntities&&x==="iso-8859-1"&&(P=o(P)),v.indexOf("[]=")>-1&&(P=t(P)?[P]:P);var O=e.call(f,I);O&&g.duplicates==="combine"?f[I]=a.combine(f[I],P):(!O||g.duplicates==="last")&&(f[I]=P)}return f},c=function(p,g,f,b){for(var y=b?g:n(g,f),w=p.length-1;w>=0;--w){var m,_=p[w];if(_==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(y===""||f.strictNullHandling&&y===null)?[]:[].concat(y);else{m=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,E=parseInt(v,10);!f.parseArrays&&v===""?m={0:y}:!isNaN(E)&&_!==v&&String(E)===v&&E>=0&&f.parseArrays&&E<=f.arrayLimit?(m=[],m[E]=y):v!=="__proto__"&&(m[v]=y)}y=m}return y},u=function(p,g,f,b){if(p){var y=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,w=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,_=f.depth>0&&w.exec(y),x=_?y.slice(0,_.index):y,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var E=0;f.depth>0&&(_=m.exec(y))!==null&&E<f.depth;){if(E+=1,!f.plainObjects&&e.call(Object.prototype,_[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(_[1])}if(_){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+y.slice(_.index)+"]")}return c(v,g,f,b)}},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 g=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:b,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:g,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||a.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Dr=function(p,g){var f=h(g);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var b=typeof p=="string"?l(p,f):p,y=f.plainObjects?Object.create(null):{},w=Object.keys(b),m=0;m<w.length;++m){var _=w[m],x=u(_,b[_],f,typeof p=="string");y=a.merge(y,x,f)}return f.allowSparse===!0?y:a.compact(y)},Dr}function kh(){if(so)return Fr;so=!0;var a=wh(),e=_h(),t=Zi();return Fr={formats:t,parse:e,stringify:a},Fr}function xh(){if(ao)return _t;ao=!0;var a=vt;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),s=["'"].concat(i),l=["%","/","?",";","#"].concat(s),c=["/","?","#"],u=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},b={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=kh();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),N=/\\/g;O[0]=O[0].replace(N,"/"),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&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[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 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="",G=0,j=te.length;G<j;G++)te.charCodeAt(G)>127?we+="x":we+=te[G];if(!we.match(h)){var ne=Q.slice(0,V),W=Q.slice(V+1),K=te.match(p);K&&(ne.push(K[1]),W.unshift(K[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=a.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=s.length;V<be;V++){var oe=s[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),b[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||"",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 N=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),N&&N.charAt(0)!=="?"&&(N="?"+N),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),N=N.replace("#","%23"),E+P+S+N+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),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 N=Object.keys(v),T=0;T<N.length;T++){var q=N[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&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),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&&!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]==="")),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 G=Q.slice(-1)[0],j=(S.host||v.host||Q.length>1)&&(G==="."||G==="..")||G==="",ne=0,W=Q.length;W>=0;W--)G=Q[W],G==="."?Q.splice(W,1):G===".."?(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(""),j&&Q.join("/").substr(-1)!=="/"&&Q.push("");var K=Q[0]===""||Q[0]&&Q[0].charAt(0)==="/";if(te){S.hostname=K?"":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&&!K&&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)},_t.parse=w,_t.resolve=_,_t.resolveObject=x,_t.format=m,_t.Url=e,_t}function Ua(a){if(typeof a=="string")a=new URL(a);else if(!(a instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(a.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return $r?Sh(a):Eh(a)}function Sh(a){let e=a.hostname,t=a.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(Qa,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,o=t[2];if(r<Ya||r>Ja||o!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Eh(a){if(a.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=a.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 Ba(a){let e=Xi.resolve(a),t=a.charCodeAt(a.length-1);(t===Ka||$r&&t===Ga)&&e[e.length-1]!==Xi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Xa,"%25")),!$r&&e.includes("\\")&&(e=e.replace(Za,"%5C")),e.includes(`
8
- `)&&(e=e.replace(el,"%0A")),e.includes("\r")&&(e=e.replace(tl,"%0D")),e.includes(" ")&&(e=e.replace(rl,"%09")),r.pathname=e,r}var Da,Rr,eo,Lr,jr,to,Nr,ro,Ur,no,Br,io,Dr,oo,Fr,so,_t,ao,qe,Fa,$a,qa,Ha,Wa,za,Va,Ga,Ka,Ya,Ja,$r,Qa,Xa,Za,el,tl,rl,Ah=Ve(()=>{le(),ue(),ce(),Hu(),oh(),bh(),La(),Da=Object.freeze(Object.create(null)),Rr={},eo=!1,Lr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,_t={},ao=!1,qe=xh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Fa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=Ba,qe.fileURLToPath=Ua,$a=qe.Url,qa=qe.format,Ha=qe.resolve,Wa=qe.resolveObject,za=qe.parse,Va=qe.URL,Ga=92,Ka=47,Ya=97,Ja=122,$r=Fa==="win32",Qa=/\//g,Xa=/%/g,Za=/\\/g,el=/\n/g,tl=/\r/g,rl=/\t/g}),Ih=pe((a,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")}}),lo=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.BufferedDuplex=void 0,a.writev=r;var e=It(),t=(De(),Me(Be));function r(n,i){let s=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?s[l]=t.Buffer.from(n[l].chunk,"utf8"):s[l]=n[l].chunk;this._write(t.Buffer.concat(s),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,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,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_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,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};a.BufferedDuplex=o}),qr=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(a,"__esModule",{value:!0}),a.streamBuilder=a.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(Ih()),o=e(ht()),n=It(),i=e(gr()),s=lo(),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 g(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};a.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),I=O(m,U,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new s.BufferedDuplex(m,I,S),P?S.addEventListener("open",N):S.onopen=N),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 F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function N(){l("WebSocket onOpen"),_ instanceof s.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 _};a.browserStreamBuilder=y}),co={};Lt(co,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>nl,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 nl,il=Ve(()=>{le(),ue(),ce(),nl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),ol=pe((a,e)=>{le(),ue(),ce(),e.exports={}}),sl=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(a,"__esModule",{value:!0});var t=e((il(),Me(co))),r=e(ht()),o=e(ol()),n=(0,r.default)("mqttjs:tcp"),i=(s,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})};a.default=i}),al={};Lt(al,{default:()=>ll});var ll,Th=Ve(()=>{le(),ue(),ce(),ll={}}),cl=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(a,"__esModule",{value:!0});var t=(Th(),Me(al)),r=e((il(),Me(co))),o=e(ht()),n=e(ol()),i=(0,o.default)("mqttjs:tls");function s(c){let{host:u,port:h,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=s(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),h.end()}return h.on("error",p),h};a.default=l}),ul=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=lo(),o,n,i;function s(){let p=new t.Transform;return p._write=(g,f,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{o.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",b=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let g=new Error(p.errMsg);i.destroy(g)})}var h=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);o=wx.connectSocket({url:b,protocols:[f]}),n=s(),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};a.default=h}),hl=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=lo(),o,n,i,s=!1;function l(){let g=new t.Transform;return g._write=(f,b,y)=>{o.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},g._flush=f=>{o.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,f)),y}function h(){s||(s=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let b=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,g);return o=f.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(f,n,o),h(),i};a.default=p}),Ch=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(a,"__esModule",{value:!0}),a.connectAsync=u;var t=e(ht()),r=e((Ah(),Me(ja))),o=e(pi()),n=e(gr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;h.username=g,h.password=f}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 b=r.default.parse(h,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=qr().streamBuilder,s.wss=qr().streamBuilder,s.mqtt=sl().default,s.tcp=sl().default,s.ssl=cl().default,s.tls=s.ssl,s.mqtts=cl().default):(s.ws=qr().browserStreamBuilder,s.wss=qr().browserStreamBuilder,s.wx=ul().default,s.wxs=ul().default,s.ali=hl().default,s.alis=hl().default)),!s[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof s[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](b,p)}let f=new o.default(g,p);return f.on("error",()=>{}),f}function u(h,p,g=!0){return new Promise((f,b)=>{let y=c(h,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),b(_)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}a.default=c}),dl=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(g,f,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(f,b);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[b]}}),Object.defineProperty(g,y,w)}:function(g,f,b,y){y===void 0&&(y=b),g[y]=f[b]}),t=a&&a.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=a&&a.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(f)};return function(f){if(f&&f.__esModule)return f;var b={};if(f!=null)for(var y=g(f),w=0;w<y.length;w++)y[w]!=="default"&&e(b,f,y[w]);return t(b,f),b}})(),o=a&&a.__exportStar||function(g,f){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(f,b)&&e(f,g,b)},n=a&&a.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(a,"__esModule",{value:!0}),a.ReasonCodes=a.KeepaliveManager=a.UniqueMessageIdProvider=a.DefaultMessageIdProvider=a.Store=a.MqttClient=a.connectAsync=a.connect=a.Client=void 0;var i=n(pi());a.MqttClient=i.default;var s=n(vs());a.DefaultMessageIdProvider=s.default;var l=n($u());a.UniqueMessageIdProvider=l.default;var c=n(ds());a.Store=c.default;var u=r(Ch());a.connect=u.default,Object.defineProperty(a,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(As());a.KeepaliveManager=h.default,a.Client=i.default,o(pi(),a),o(Bt(),a),o(hs(),a);var p=pr();Object.defineProperty(a,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Ph=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(i,s,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(s,l);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[l]}}),Object.defineProperty(i,c,u)}:function(i,s,l,c){c===void 0&&(c=l),i[c]=s[l]}),t=a&&a.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=a&&a.__importStar||(function(){var i=function(s){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(s)};return function(s){if(s&&s.__esModule)return s;var l={};if(s!=null)for(var c=i(s),u=0;u<c.length;u++)c[u]!=="default"&&e(l,s,c[u]);return t(l,s),l}})(),o=a&&a.__exportStar||function(i,s){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(s,l)&&e(s,i,l)};Object.defineProperty(a,"__esModule",{value:!0});var n=r(dl());a.default=n,o(dl(),a)});const Oh=Ph();const Mh={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}/#"},Rh=300,Lh={templateId:"7",type:"link",isDeepLink:!0},jh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class fl{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={...Mh,...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 s=!1;const l=h=>{s||(s=!0,clearTimeout(u),h())},c=(h,p)=>{s||(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=Oh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),s||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),!s){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),s||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",{}),s||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={...Lh,...this.config.fileTemplate??{},...Nh(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=Rh){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(g=>g(p)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,l={topic:e,conversationId:s,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={...jh,...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 s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Nh(a){const e={};for(const[t,r]of Object.entries(a))r!==void 0&&(e[t]=r);return e}function pl(a,e){return(a.sender??"").toString()===e}function ml(a,e){const t=(a.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 uo(a){const e={raw:a},t=a.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 a.text=="string"&&a.text.trim().startsWith("{"))try{const o=JSON.parse(a.text);typeof o.message=="string"&&(e.innerMessage=o.message);const n=o.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=a.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 gl(a){const e=uo(a);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,s=typeof o.description=="string"?o.description:void 0,l=a.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function bl(a,e,t){const r=ml(a,t),o=uo(a),n=gl(a);let i="";o.innerMessage?i=o.innerMessage:typeof a.text=="string"&&(a.text.trim().startsWith("{")?o.contentType!=="300"&&(i=a.text):i=a.text);const s=typeof a.message_id=="string"?a.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof a.timestamp=="number"?new Date(a.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof a.status=="number"?Uh(a.status):"delivered",h={id:s,externalId:s,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:a.sender,sender_fullname:a.sender_fullname??a.senderFullname,app_id:a.app_id,attributes:a.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 Uh(a){return a<0?"error":a>=250?"read":a>=150?"delivered":"sent"}class yl extends sr{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 Po(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Oo,this.conversationManager=new No(e.conversationId),this.usesAikaara()&&(this.connection=new Co(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 fl({...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(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const o=r.map(s=>bl(s,e,{userId:t}).message).sort((s,l)=>new Date(s.createdAt).getTime()-new Date(l.createdAt).getTime()),n=this.messageStore.messages,i=[...o,...n.filter(s=>!o.some(l=>l.externalId&&l.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of o)try{this.config.onMessage(s)}catch(l){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",l)}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=t.conversationId??this.conversationManager.conversationId;if(!r)return;const o=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=bl(e,r,{userId:o,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(pl(e,o)){const c=this.messageStore.reconcileOptimistic(n);if(c){this.emit("message:updated",c);return}}const{message:s,deduped:l}=this.messageStore.upsertRemoteMessage(n);if(l)this.emit("message:updated",s);else{this.emit("message:received",s),this.config.onMessage?.(s);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("aikaara:message",{detail:{role:s.role,hasAttachments:Array.isArray(s.attachments)&&s.attachments.length>0,templateId:s.template?.templateId,messageId:s.id,conversationId:s.conversationId}}))}catch{}}if(i.contentType){const c={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(c)}}handleTiledeskStatusUpdate(e){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 Bh extends sr{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 vl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Dh(a){const e=a.lastIndexOf(".");return e<0||e===a.length-1?"":a.slice(e+1).toLowerCase()}function Fh(a,e,t){const r=Dh(a.name||"");if(r&&e&&e[r])return e[r];const o=a.type;return o&&o.trim().length>0?o:r&&vl[r]?vl[r]:t}function ho(a,e){return a.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function $h(a,e){const t=e.split(".");let r=a;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function wl(a){const e=a.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Fh(t,a.contentTypeMap,a.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},s=a.authHeader?await a.authHeader():void 0,l={accept:"application/json",...a.extraHeaders??{},...s?{authorization:s}:{}};let c=a.signEndpoint.includes("{")?a.signEndpoint:`${a.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=ho(c,i),h=await fetch(u,{method:a.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),g=$h(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=a.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,a.s3HostRewrite):g,b=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(a.registerEndpoint){const w=JSON.parse(ho(JSON.stringify(a.registerBody??{}),i)),m=await fetch(a.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:a.viewerTemplate?ho(a.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function fo(a){return{async upload(e,t){const r=new FormData,o=a.fieldName??"file";r.append(o,e,e.name);const n=typeof a.extraFields=="function"?a.extraFields(t):a.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof a.headers=="function"?await a.headers():a.headers??{},s=await fetch(a.endpoint,{method:a.method??"POST",body:r,headers:i,credentials:a.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const l=await s.json().catch(()=>({}));if(a.parseResponse)return a.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 qh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function _l(a){const e=a.apiBase.replace(/\/$/,""),t=a.pageSize??200,r=a.pathTemplate??qh;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)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...a.extraHeaders??{}};if(a.getToken){const p=await a.getToken();p&&(l.authorization=p)}const c=await fetch(s,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(a.parseResponse&&u)return a.parseResponse(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 Hh="^[A-Z]{5}[0-9]{4}[A-Z]$",Wh="^[A-Z]{4}[0-9]{5}[A-Z]$",zh="^[A-Z]{4}0[A-Z0-9]{6}$",kl="^[0-9]{6}$",Vh=[{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)",required:!0,pattern:Wh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],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}]}],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:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:kl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Hh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",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:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:zh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:kl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function Gh(a,e){const t=a||{},r={userId:Jh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Oe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Oe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Oe(t.us80dForParentsAmount),r.hasParentOverSixty=po(t.hasParentOverSixty),r.preventiveHealthCheckUp=Oe(t.preventiveHealthCheckUp),r.medicalExpenditure=Oe(t.medicalExpenditure),r.savingBankInterest=Oe(t.savingBankInterest),r.fdInterest=Oe(t.fdInterest),r.dividend=Oe(t.dividend),r.anyOtherIncome=Oe(t.anyOtherIncome),r.cryptoSellValue=Oe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Oe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Oe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Oe(t.grossReceipts),r.businessNetProfit=Oe(t.netProfit),r.agricultureDetails={income:Oe(t.agricultureIncome)},r.exemptIncomeAmount=Oe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Oe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Oe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const o={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Oe(t.immovableAssetCost)};Object.values(o).some(s=>s!==void 0)&&(r.immovableAsset=[o]);const n=mo(t.hpDetails,Kh);n.length&&(r.hpDetails=n);const i=mo(t.salaryDetails,Yh);if(i.length){r.salaryIncome=i;const s=mo(t.salaryDetails,c=>({grossSalary:Oe(c.grossSalary),employerName:Re(c.employerName)}));s.length&&(r.salary=s);const l=xl(t.salaryDetails)[0]??{};r.hraAmount=Oe(l.hraReceived),r.leaveTravelAllowanceAmount=Oe(l.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Oe(l.leaveEncashment),r.anyOtherAllowanceAmount=Oe(l.anyOtherAllowance),r.salaryIncomeFlag=!0}return Hr(r)}function Kh(a){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(a.loanTakenFrom),bankOrInstituteName:Re(a.lenderName),loanAccountNo:Re(a.loanAccountNumber),loanSanctionDate:Qh(a.sanctionDate),totalLoanAmount:Oe(a.totalLoanAmount),interest:Oe(a.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Re(a.typeOfHouseProperty),hasRentalIncome:a.typeOfHouseProperty==="LOP"?!0:po(a.hasRentalIncome),homeLoanInterest:Oe(a.homeLoanInterest),homeLoanPrinciple:Oe(a.homeLoanPrinciple),housePropertyAddress:Re(a.housePropertyAddress),housePropertyPincode:Re(a.housePropertyPincode),rentalIncome:Oe(a.rentalIncome),nameOfTenant:Re(a.nameOfTenant),propertyTax:Oe(a.propertyTax),hasCoOwnedProperty:po(a.hasCoOwnedProperty),coOwnerName:Re(a.coOwnerName),coOwnerPan:Re(a.coOwnerPan),coOwnerShare:Re(a.coOwnerShare),loanDetails:t?[e]:void 0}}function Yh(a){return{grossSalaryIncome:Oe(a.grossSalary),salary:Oe(a.basicSalary),employer:{employerName:Re(a.employerName),employerTan:Re(a.employerTan)},allowance:{hraAmount:Oe(a.hraReceived),leaveTravelAllowanceAmount:Oe(a.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Oe(a.leaveEncashment),anyOtherAllowanceAmount:Oe(a.anyOtherAllowance)}}}function Jh(a){if(a===void 0||a==="")return;const e=Number(a);return Number.isFinite(e)&&String(e)===String(a)?e:a}function Oe(a){if(a==null||a==="")return;const e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:void 0}function Re(a){if(a==null)return;const e=String(a).trim();return e===""?void 0:e}function po(a){return a===!0||a===!1?a:void 0}function Qh(a){const e=Re(a);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function xl(a){return Array.isArray(a)?a.filter(e=>e&&typeof e=="object"):[]}function mo(a,e){return xl(a).map(t=>Hr(e(t))).filter(t=>t!==void 0)}function Hr(a){if(Array.isArray(a)){const e=a.map(Hr).filter(t=>t!==void 0);return e.length?e:void 0}if(a&&typeof a=="object"){const e={};for(const[t,r]of Object.entries(a)){const o=Hr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return a}function Sl(){if(typeof window>"u")return null;const a=window,e=a.__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=a.__aikaara_descriptor__??{},r=ed(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=td(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,s=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):nd(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:s,headers:rd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||id(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Xh(a){const e=await a.getToken(),t=a.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${a.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...a.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 El(await r.json().catch(()=>({})))}async function Zh(a,e){const t=await a.getToken(),r=a.userId,o=Gh(e,{userId:r,assessmentYear:a.assessmentYear,isRevised:a.isRevised}),n=a.submitUrl||`${a.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...a.headers};a.txbdyApiKey&&(i["txbdy-api-key"]=a.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const s=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!s.ok){const l=await s.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${s.status} ${l.slice(0,200)}`)}return El(await s.json().catch(()=>({})))}function ed(a){const e=[a.cloud?.listEndpoint,a.cloud?.downloadEndpoint,a.upload?.signEndpoint,a.login?.pan?.basicPanEndpoint,a.login?.pan?.panDetailEndpoint,a.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 td(a){if(!a||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${a}`);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 rd(a){const e={};if(!a)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(a))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function nd(a){if(!a)return;const e=a.userId??a.id??a.ext_uid??a.extUid;return e==null||e===""?void 0:String(e)}function El(a){if(a&&typeof a=="object"){const e=a;return e.data&&typeof e.data=="object"?e.data:e}return{}}function id(){const a=new Date,e=a.getMonth()>=3?a.getFullYear():a.getFullYear()-1;return`${e}-${e+1}`}class od{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new yl(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:Vh,data:{}});const t=Sl();if(!(!t||!t.baseUrl))try{const r=await Xh(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-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Sl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Zh(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 Al 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||kc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Io,position:this.getAttribute("position")||this._config.position||_c,width:Number(this.getAttribute("width"))||this._config.width||bc,height:Number(this.getAttribute("height"))||this._config.height||yc,fontFamily:this._config.fontFamily||wc,borderRadius:this._config.borderRadius??vc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||To,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||xc,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=(s,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${s}`,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(el,"%0A")),e.includes("\r")&&(e=e.replace(tl,"%0D")),e.includes(" ")&&(e=e.replace(rl,"%09")),r.pathname=e,r}var Da,Rr,eo,Lr,jr,to,Nr,ro,Ur,no,Br,io,Dr,oo,Fr,so,_t,ao,qe,Fa,$a,qa,Ha,Wa,za,Va,Ga,Ka,Ya,Ja,$r,Qa,Xa,Za,el,tl,rl,Ah=Ve(()=>{le(),ue(),ce(),Hu(),oh(),bh(),La(),Da=Object.freeze(Object.create(null)),Rr={},eo=!1,Lr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,jr={},to=!1,Nr={},ro=!1,Ur={},no=!1,Br={},io=!1,Dr={},oo=!1,Fr={},so=!1,_t={},ao=!1,qe=xh(),qe.parse,qe.resolve,qe.resolveObject,qe.format,qe.Url,Fa=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,qe.URL=typeof URL<"u"?URL:null,qe.pathToFileURL=Ba,qe.fileURLToPath=Ua,$a=qe.Url,qa=qe.format,Ha=qe.resolve,Wa=qe.resolveObject,za=qe.parse,Va=qe.URL,Ga=92,Ka=47,Ya=97,Ja=122,$r=Fa==="win32",Qa=/\//g,Xa=/%/g,Za=/\\/g,el=/\n/g,tl=/\r/g,rl=/\t/g}),Ih=pe((a,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")}}),lo=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0}),a.BufferedDuplex=void 0,a.writev=r;var e=It(),t=(De(),Me(Be));function r(n,i){let s=new Array(n.length);for(let l=0;l<n.length;l++)typeof n[l].chunk=="string"?s[l]=t.Buffer.from(n[l].chunk,"utf8"):s[l]=n[l].chunk;this._write(t.Buffer.concat(s),"binary",i)}var o=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,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,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_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,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};a.BufferedDuplex=o}),qr=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(w){return w&&w.__esModule?w:{default:w}};Object.defineProperty(a,"__esModule",{value:!0}),a.streamBuilder=a.browserStreamBuilder=void 0;var t=(De(),Me(Be)),r=e(Ih()),o=e(ht()),n=It(),i=e(gr()),s=lo(),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 g(w,m,_){l("createWebSocket"),l(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";l(`creating new Websocket for url: ${m} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(m,[x],_):v=new r.default(m,[x],_.wsOptions),v}function f(w,m){let _=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",x=u(m,w),v;return m.createWebsocket?v=m.createWebsocket(x,[_],m):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var b=(w,m)=>{l("streamBuilder");let _=h(m);_.hostname=_.hostname||_.host||"localhost";let x=u(_,w),v=g(w,x,_),E=r.default.createWebSocketStream(v,_.wsOptions);return E.url=x,v.on("close",()=>{E.destroy()}),E};a.streamBuilder=b;var y=(w,m)=>{l("browserStreamBuilder");let _,x=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,E=!m.objectMode,S=f(w,m),I=O(m,U,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let P=typeof S.addEventListener<"u";S.readyState===S.OPEN?(_=I,_.socket=S):(_=new s.BufferedDuplex(m,I,S),P?S.addEventListener("open",N):S.onopen=N),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 F=new n.Transform({objectMode:Y.objectMode});return F._write=V,F._flush=re,F}function N(){l("WebSocket onOpen"),_ instanceof s.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 _};a.browserStreamBuilder=y}),co={};Lt(co,{Server:()=>je,Socket:()=>je,Stream:()=>je,_createServerHandle:()=>je,_normalizeArgs:()=>je,_setSimultaneousAccepts:()=>je,connect:()=>je,createConnection:()=>je,createServer:()=>je,default:()=>nl,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 nl,il=Ve(()=>{le(),ue(),ce(),nl={_createServerHandle:je,_normalizeArgs:je,_setSimultaneousAccepts:je,connect:je,createConnection:je,createServer:je,isIP:je,isIPv4:je,isIPv6:je,Server:je,Socket:je,Stream:je}}),ol=pe((a,e)=>{le(),ue(),ce(),e.exports={}}),sl=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(a,"__esModule",{value:!0});var t=e((il(),Me(co))),r=e(ht()),o=e(ol()),n=(0,r.default)("mqttjs:tcp"),i=(s,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})};a.default=i}),al={};Lt(al,{default:()=>ll});var ll,Th=Ve(()=>{le(),ue(),ce(),ll={}}),cl=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(a,"__esModule",{value:!0});var t=(Th(),Me(al)),r=e((il(),Me(co))),o=e(ht()),n=e(ol()),i=(0,o.default)("mqttjs:tls");function s(c){let{host:u,port:h,socksProxy:p,...g}=c;if(p!==void 0){let f=(0,n.default)(u,h,p,{timeout:c.socksTimeout});return(0,t.connect)({...g,socket:f})}return(0,t.connect)(c)}var l=(c,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let h=s(u);h.on("secureConnect",()=>{u.rejectUnauthorized&&!h.authorized?h.emit("error",new Error("TLS not authorized")):h.removeListener("error",p)});function p(g){u.rejectUnauthorized&&c.emit("error",g),h.end()}return h.on("error",p),h};a.default=l}),ul=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=lo(),o,n,i;function s(){let p=new t.Transform;return p._write=(g,f,b)=>{o.send({data:g.buffer,success(){b()},fail(y){b(new Error(y))}})},p._flush=g=>{o.close({success(){g()}})},p}function l(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function c(p,g){let f=p.protocol==="wxs"?"wss":"ws",b=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(b=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(b=p.transformWsUrl(b,p,g)),b}function u(){o.onOpen(()=>{i.socketReady()}),o.onMessage(p=>{let{data:g}=p;g instanceof ArrayBuffer?g=e.Buffer.from(g):g=e.Buffer.from(g,"utf8"),n.push(g)}),o.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),o.onError(p=>{let g=new Error(p.errMsg);i.destroy(g)})}var h=(p,g)=>{if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");let f=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";l(g);let b=c(g,p);o=wx.connectSocket({url:b,protocols:[f]}),n=s(),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};a.default=h}),hl=pe(a=>{le(),ue(),ce(),Object.defineProperty(a,"__esModule",{value:!0});var e=(De(),Me(Be)),t=It(),r=lo(),o,n,i,s=!1;function l(){let g=new t.Transform;return g._write=(f,b,y)=>{o.sendSocketMessage({data:f.buffer,success(){y()},fail(){y(new Error)}})},g._flush=f=>{o.closeSocket({success(){f()}})},g}function c(g){g.hostname||(g.hostname="localhost"),g.path||(g.path="/"),g.wsOptions||(g.wsOptions={})}function u(g,f){let b=g.protocol==="alis"?"wss":"ws",y=`${b}://${g.hostname}${g.path}`;return g.port&&g.port!==80&&g.port!==443&&(y=`${b}://${g.hostname}:${g.port}${g.path}`),typeof g.transformWsUrl=="function"&&(y=g.transformWsUrl(y,g,f)),y}function h(){s||(s=!0,o.onSocketOpen(()=>{i.socketReady()}),o.onSocketMessage(g=>{if(typeof g.data=="string"){let f=e.Buffer.from(g.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(g.data)}}),o.onSocketClose(()=>{i.end(),i.destroy()}),o.onSocketError(g=>{i.destroy(g)}))}var p=(g,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let b=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";c(f);let y=u(f,g);return o=f.my,o.connectSocket({url:y,protocols:b}),n=l(),i=new r.BufferedDuplex(f,n,o),h(),i};a.default=p}),Ch=pe(a=>{le(),ue(),ce();var e=a&&a.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(a,"__esModule",{value:!0}),a.connectAsync=u;var t=e(ht()),r=e((Ah(),Me(ja))),o=e(pi()),n=e(gr());typeof Le?.nextTick!="function"&&(Le.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function l(h){let p;if(h.auth)if(p=h.auth.match(/^(.+):(.+)$/),p){let[,g,f]=p;h.username=g,h.password=f}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 b=r.default.parse(h,!0),y={};if(b.port!=null&&(y.port=Number(b.port)),y.host=b.hostname,y.query=b.query,y.auth=b.auth,y.protocol=b.protocol,y.path=b.path,p={...y,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,l(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Le<"u"&&(p.socksProxy=Le.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=qr().streamBuilder,s.wss=qr().streamBuilder,s.mqtt=sl().default,s.tcp=sl().default,s.ssl=cl().default,s.tls=s.ssl,s.mqtts=cl().default):(s.ws=qr().browserStreamBuilder,s.wss=qr().browserStreamBuilder,s.wx=ul().default,s.wxs=ul().default,s.ali=hl().default,s.alis=hl().default)),!s[p.protocol]){let b=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((y,w)=>b&&w%2===0?!1:typeof s[y]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function g(b){return p.servers&&((!b._reconnectCount||b._reconnectCount===p.servers.length)&&(b._reconnectCount=0),p.host=p.servers[b._reconnectCount].host,p.port=p.servers[b._reconnectCount].port,p.protocol=p.servers[b._reconnectCount].protocol?p.servers[b._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,b._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](b,p)}let f=new o.default(g,p);return f.on("error",()=>{}),f}function u(h,p,g=!0){return new Promise((f,b)=>{let y=c(h,p),w={connect:_=>{m(),f(y)},end:()=>{m(),f(y)},error:_=>{m(),y.end(),b(_)}};g===!1&&(w.close=()=>{w.error(new Error("Couldn't connect to server"))});function m(){Object.keys(w).forEach(_=>{y.off(_,w[_])})}Object.keys(w).forEach(_=>{y.on(_,w[_])})})}a.default=c}),dl=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(g,f,b,y){y===void 0&&(y=b);var w=Object.getOwnPropertyDescriptor(f,b);(!w||("get"in w?!f.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return f[b]}}),Object.defineProperty(g,y,w)}:function(g,f,b,y){y===void 0&&(y=b),g[y]=f[b]}),t=a&&a.__setModuleDefault||(Object.create?function(g,f){Object.defineProperty(g,"default",{enumerable:!0,value:f})}:function(g,f){g.default=f}),r=a&&a.__importStar||(function(){var g=function(f){return g=Object.getOwnPropertyNames||function(b){var y=[];for(var w in b)Object.prototype.hasOwnProperty.call(b,w)&&(y[y.length]=w);return y},g(f)};return function(f){if(f&&f.__esModule)return f;var b={};if(f!=null)for(var y=g(f),w=0;w<y.length;w++)y[w]!=="default"&&e(b,f,y[w]);return t(b,f),b}})(),o=a&&a.__exportStar||function(g,f){for(var b in g)b!=="default"&&!Object.prototype.hasOwnProperty.call(f,b)&&e(f,g,b)},n=a&&a.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(a,"__esModule",{value:!0}),a.ReasonCodes=a.KeepaliveManager=a.UniqueMessageIdProvider=a.DefaultMessageIdProvider=a.Store=a.MqttClient=a.connectAsync=a.connect=a.Client=void 0;var i=n(pi());a.MqttClient=i.default;var s=n(vs());a.DefaultMessageIdProvider=s.default;var l=n($u());a.UniqueMessageIdProvider=l.default;var c=n(ds());a.Store=c.default;var u=r(Ch());a.connect=u.default,Object.defineProperty(a,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var h=n(As());a.KeepaliveManager=h.default,a.Client=i.default,o(pi(),a),o(Bt(),a),o(hs(),a);var p=pr();Object.defineProperty(a,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Ph=pe(a=>{le(),ue(),ce();var e=a&&a.__createBinding||(Object.create?function(i,s,l,c){c===void 0&&(c=l);var u=Object.getOwnPropertyDescriptor(s,l);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[l]}}),Object.defineProperty(i,c,u)}:function(i,s,l,c){c===void 0&&(c=l),i[c]=s[l]}),t=a&&a.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=a&&a.__importStar||(function(){var i=function(s){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(s)};return function(s){if(s&&s.__esModule)return s;var l={};if(s!=null)for(var c=i(s),u=0;u<c.length;u++)c[u]!=="default"&&e(l,s,c[u]);return t(l,s),l}})(),o=a&&a.__exportStar||function(i,s){for(var l in i)l!=="default"&&!Object.prototype.hasOwnProperty.call(s,l)&&e(s,i,l)};Object.defineProperty(a,"__esModule",{value:!0});var n=r(dl());a.default=n,o(dl(),a)});const Oh=Ph();const Mh={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}/#"},Rh=300,Lh={templateId:"7",type:"link",isDeepLink:!0},jh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class fl{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={...Mh,...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 s=!1;const l=h=>{s||(s=!0,clearTimeout(u),h())},c=(h,p)=>{s||(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=Oh.connect(this.config.mqttEndpoint,o),this.client.on("connect",()=>{if(this.connectedAt=Date.now(),s||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),!s){c("socket-closed-pre-connack");return}this.disposed||this.scheduleReconnect()}),this.client.on("error",h=>{this.debugLog("ERROR",{message:h.message}),s||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",{}),s||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={...Lh,...this.config.fileTemplate??{},...Nh(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=Rh){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(g=>g(p)),this.messageHandlers.forEach(g=>g(o,{topic:e,conversationId:c,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,l={topic:e,conversationId:s,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={...jh,...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 s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function Nh(a){const e={};for(const[t,r]of Object.entries(a))r!==void 0&&(e[t]=r);return e}function pl(a,e){return(a.sender??"").toString()===e}function ml(a,e){const t=(a.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 uo(a){const e={raw:a},t=a.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 a.text=="string"&&a.text.trim().startsWith("{"))try{const o=JSON.parse(a.text);typeof o.message=="string"&&(e.innerMessage=o.message);const n=o.metadata;n&&typeof n=="object"&&(!e.contentType&&typeof n.contentType=="string"&&(e.contentType=n.contentType),!e.templateId&&typeof n.templateId=="string"&&(e.templateId=n.templateId),e.payload===void 0&&n.payload!==void 0&&(e.payload=n.payload))}catch{}const r=a.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 gl(a){const e=uo(a);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,s=typeof o.description=="string"?o.description:void 0,l=a.attributes,c=l&&typeof l.cloudFileId=="string"?l.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:c,templateId:e.templateId}}function bl(a,e,t){const r=ml(a,t),o=uo(a),n=gl(a);let i="";o.innerMessage?i=o.innerMessage:typeof a.text=="string"&&(a.text.trim().startsWith("{")?o.contentType!=="300"&&(i=a.text):i=a.text);const s=typeof a.message_id=="string"?a.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,l=typeof a.timestamp=="number"?new Date(a.timestamp).toISOString():new Date().toISOString(),c=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof a.status=="number"?Uh(a.status):"delivered",h={id:s,externalId:s,conversationId:e,role:c,content:i,createdAt:l,status:u,metadata:{sender:a.sender,sender_fullname:a.sender_fullname??a.senderFullname,app_id:a.app_id,attributes:a.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 Uh(a){return a<0?"error":a>=250?"read":a>=150?"delivered":"sent"}class yl extends sr{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 Po(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Oo,this.conversationManager=new No(e.conversationId),this.usesAikaara()&&(this.connection=new Co(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 fl({...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(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const o=r.map(s=>bl(s,e,{userId:t}).message).sort((s,l)=>new Date(s.createdAt).getTime()-new Date(l.createdAt).getTime()),n=this.messageStore.messages,i=[...o,...n.filter(s=>!o.some(l=>l.externalId&&l.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of o)try{this.config.onMessage(s)}catch(l){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",l)}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:s}=bl(e,o,{userId:n,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&i.role==="assistant")return;if(pl(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(s.contentType){const u={messageId:l.id,conversationId:o,role:i.role==="tool"?"system":i.role,contentType:s.contentType,templateId:s.templateId,payload:s.payload,innerMessage:s.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 Bh extends sr{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 vl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function Dh(a){const e=a.lastIndexOf(".");return e<0||e===a.length-1?"":a.slice(e+1).toLowerCase()}function Fh(a,e,t){const r=Dh(a.name||"");if(r&&e&&e[r])return e[r];const o=a.type;return o&&o.trim().length>0?o:r&&vl[r]?vl[r]:t}function ho(a,e){return a.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function $h(a,e){const t=e.split(".");let r=a;for(const o of t)if(r&&typeof r=="object"&&o in r)r=r[o];else return"";return typeof r=="string"?r:""}function wl(a){const e=a.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const o=t.name||`upload-${Date.now()}`,n=Fh(t,a.contentTypeMap,a.contentTypeFallback??"application/octet-stream"),i={fileName:o,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId,contentType:n},s=a.authHeader?await a.authHeader():void 0,l={accept:"application/json",...a.extraHeaders??{},...s?{authorization:s}:{}};let c=a.signEndpoint.includes("{")?a.signEndpoint:`${a.signEndpoint}?fileName={fileName}`;if(!c.includes("{contentType}")){const w=c.includes("?")?"&":"?";c=`${c}${w}contentType={contentType}`}const u=ho(c,i),h=await fetch(u,{method:a.signMethod??"GET",headers:l});if(!h.ok)throw new Error(`Sign request failed: ${h.status}`);const p=await h.json().catch(()=>({})),g=$h(p,e);if(!g)throw new Error(`Sign response missing path "${e}"`);const f=a.s3HostRewrite?g.replace(/^https:\/\/[^/]+/i,a.s3HostRewrite):g,b=await fetch(f,{method:"PUT",headers:{"content-type":n},body:t});if(!b.ok){const w=await b.text().catch(()=>"");throw new Error(`S3 PUT failed: ${b.status} ${w.slice(0,200)}`)}if(a.registerEndpoint){const w=JSON.parse(ho(JSON.stringify(a.registerBody??{}),i)),m=await fetch(a.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:a.viewerTemplate?ho(a.viewerTemplate,i):g.split("?")[0],fileName:o,contentType:n,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function fo(a){return{async upload(e,t){const r=new FormData,o=a.fieldName??"file";r.append(o,e,e.name);const n=typeof a.extraFields=="function"?a.extraFields(t):a.extraFields;if(n)for(const[p,g]of Object.entries(n))r.append(p,g);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof a.headers=="function"?await a.headers():a.headers??{},s=await fetch(a.endpoint,{method:a.method??"POST",body:r,headers:i,credentials:a.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const l=await s.json().catch(()=>({}));if(a.parseResponse)return a.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 qh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function _l(a){const e=a.apiBase.replace(/\/$/,""),t=a.pageSize??200,r=a.pathTemplate??qh;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)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,l={accept:"application/json","content-type":"application/json",...a.extraHeaders??{}};if(a.getToken){const p=await a.getToken();p&&(l.authorization=p)}const c=await fetch(s,{method:"GET",headers:l}),u=await c.json().catch(()=>null);if(a.parseResponse&&u)return a.parseResponse(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 Hh="^[A-Z]{5}[0-9]{4}[A-Z]$",Wh="^[A-Z]{4}[0-9]{5}[A-Z]$",zh="^[A-Z]{4}0[A-Z0-9]{6}$",kl="^[0-9]{6}$",Vh=[{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)",required:!0,pattern:Wh,maxLength:10}]},{id:"salaryComponents",type:"group",title:"Salary Components",fields:[{id:"basicSalary",type:"number",label:"Basic Salary",currency:"₹",required:!0,min:0},{id:"hraReceived",type:"number",label:"HRA Received",currency:"₹",min:0},{id:"leaveTravelAllowance",type:"number",label:"Leave Travel Allowance",currency:"₹",min:0},{id:"anyOtherAllowance",type:"number",label:"Other Allowances",currency:"₹",min:0},{id:"leaveEncashment",type:"number",label:"Leave Encashment",currency:"₹",min:0},{id:"grossSalary",type:"number",label:"Gross Salary (Total)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"business-profession",title:"Business / Profession",icon:"💼",fields:[{id:"businessGroup",type:"group",title:"Business Details",fields:[{id:"businessName",type:"text",label:"Business / Profession Name"},{id:"businessNatureOfWork",type:"text",label:"Nature of Work"},{id:"grossReceipts",type:"number",label:"Gross Receipts / Turnover",currency:"₹",min:0},{id:"netProfit",type:"number",label:"Net Profit",currency:"₹"}]}],submitLabel:"Save"},{id:"capital-gains",title:"Capital Gains",icon:"📈",fields:[{id:"equityGains",type:"group",title:"Equity & Mutual Funds",fields:[{id:"shortTermEquityGain",type:"number",label:"Short-Term Capital Gain",currency:"₹"},{id:"longTermEquityGain",type:"number",label:"Long-Term Capital Gain",currency:"₹"}]},{id:"propertyGains",type:"group",title:"Land & Building",fields:[{id:"landBuildingTermType",type:"radio",label:"Holding Period",options:[{value:"short",label:"Short-Term"},{value:"long",label:"Long-Term"}]},{id:"landBuildingPurchaseValue",type:"number",label:"Purchase Value",currency:"₹"},{id:"landBuildingSellValue",type:"number",label:"Sale Value",currency:"₹"}]}],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}]}],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:"agricultural-income",title:"Agricultural Income",icon:"🌾",fields:[{id:"agricultureIncome",type:"number",label:"Total Agricultural Income",currency:"₹",min:0},{id:"agricultureIncomeGt5Lakh",type:"yes-no",label:"Is agricultural income above ₹5,00,000?"}],submitLabel:"Save"},{id:"exempt-income",title:"Other Exempt Income",icon:"🧾",fields:[{id:"exemptIncome",type:"number",label:"Total Exempt Income",currency:"₹",min:0},{id:"exemptIncomeNature",type:"text",label:"Nature of Exempt Income",placeholder:"e.g. PPF interest, gratuity"}],submitLabel:"Save"},{id:"house-property",title:"House Property",icon:"🏠",dataPath:"hpDetails[]",repeatable:{maxCount:2,labelTemplate:"Property {index}"},entryIcon:"🏠",fields:[{id:"typeOfHouseProperty",type:"radio",label:"Property Type",required:!0,options:[{value:"SOP",label:"Self-Occupied"},{value:"LOP",label:"Let-Out"}]},{id:"homeLoanDetails",type:"group",title:"Home Loan Details",hint:"Interest deduction capped at ₹2,00,000",fields:[{id:"loanTakenFrom",type:"text",label:"Loan Taken From",required:!0},{id:"lenderName",type:"text",label:"Lender Name",required:!0},{id:"loanAccountNumber",type:"text",label:"Loan Account Number",required:!0},{id:"sanctionDate",type:"date",label:"Sanction Date",format:"DD/MM/YYYY",required:!0},{id:"totalLoanAmount",type:"number",label:"Total Loan Amount",currency:"₹",min:0},{id:"homeLoanInterest",type:"number",label:"Home Loan Interest",currency:"₹",min:0,max:2e5},{id:"homeLoanPrinciple",type:"number",label:"Home Loan Principal",currency:"₹",min:0}]},{id:"addressDetails",type:"group",title:"Property Address",fields:[{id:"housePropertyAddress",type:"text",label:"Address"},{id:"housePropertyPincode",type:"text",label:"Pincode",maxLength:6,pattern:kl}]},{id:"rentalDetails",type:"group",title:"Rental Income Details",showWhen:{field:"typeOfHouseProperty",equals:"LOP"},fields:[{id:"rentalIncome",type:"number",label:"Annual Rental Income",currency:"₹",required:!0,min:0},{id:"nameOfTenant",type:"text",label:"Tenant Name",required:!0},{id:"propertyTax",type:"number",label:"Municipal / Property Tax Paid",currency:"₹",min:0}]},{id:"hasCoOwnedProperty",type:"yes-no",label:"Is this property co-owned?"},{id:"coOwnerGroup",type:"group",title:"Co-Owner Details",showWhen:{field:"hasCoOwnedProperty",equals:!0},fields:[{id:"coOwnerName",type:"text",label:"Co-Owner Name",required:!0},{id:"coOwnerPan",type:"text",label:"Co-Owner PAN",required:!0,pattern:Hh,maxLength:10},{id:"coOwnerShare",type:"text",label:"Co-Owner Share (%)",placeholder:"e.g. 50",maxLength:5}]}],submitLabel:"Save"},{id:"deductions",title:"Deductions",icon:"📋",fields:[{id:"section80c",type:"group",title:"Section 80C",hint:"Maximum deduction allowed: ₹1,50,000",fields:[{id:"us80cAmount",type:"number",label:"80C Investment Amount",currency:"₹",min:0,max:15e4}]},{id:"section80d",type:"group",title:"Section 80D — Health Insurance",fields:[{id:"us80dForSelfAndFamilyAmount",type:"number",label:"Premium for Self / Spouse / Children",currency:"₹",min:0,max:25e3},{id:"us80dForParentsAmount",type:"number",label:"Premium for Parents",currency:"₹",min:0,max:5e4},{id:"hasParentOverSixty",type:"yes-no",label:"Are your parents senior citizens (60+)?"},{id:"preventiveHealthCheckUp",type:"number",label:"Preventive Health Check-up",currency:"₹",min:0},{id:"medicalExpenditure",type:"number",label:"Medical Expenditure (senior citizen)",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"tax-paid-tds",title:"Tax Paid / TDS",icon:"🧮",fields:[{id:"tdsGroup",type:"group",title:"Tax Deducted at Source",fields:[{id:"tdsOnSalary",type:"number",label:"TDS on Salary",currency:"₹",min:0},{id:"tdsOtherThanSalary",type:"number",label:"TDS (other than salary)",currency:"₹",min:0}]},{id:"advanceTaxGroup",type:"group",title:"Advance / Self-Assessment Tax",fields:[{id:"selfAssessmentOrAdvanceTax",type:"number",label:"Advance / Self-Assessment Tax Paid",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:"bankAccountNumber",type:"text",label:"Bank Account Number",required:!0},{id:"bankIfscCode",type:"text",label:"IFSC Code",required:!0,pattern:zh,maxLength:11}]},{id:"immovableGroup",type:"group",title:"Immovable Assets",hint:"Required if total income exceeds ₹50,00,000",fields:[{id:"immovableAssetDescription",type:"text",label:"Description"},{id:"immovableAssetFlatNo",type:"text",label:"Flat / House No."},{id:"immovableAssetArea",type:"text",label:"Area / Locality"},{id:"immovableAssetPincode",type:"text",label:"Pincode",maxLength:6,pattern:kl},{id:"immovableAssetCost",type:"number",label:"Cost of Asset",currency:"₹",min:0}]}],submitLabel:"Save"},{id:"have-a-question",title:"I only have a question",icon:"❓",fields:[{id:"question",type:"textarea",label:"What would you like to ask?",placeholder:"Type your question for the TaxBuddy expert…",required:!0,rows:5,maxLength:1e3}],submitLabel:"Send Question"}];function Gh(a,e){const t=a||{},r={userId:Jh(e.userId),assessmentYear:e.assessmentYear,isRevised:e.isRevised||"N"};r.us80cAmount=Oe(t.us80cAmount),r.us80dForSelfAndFamilyAmount=Oe(t.us80dForSelfAndFamilyAmount),r.us80dForParentsAmount=Oe(t.us80dForParentsAmount),r.hasParentOverSixty=po(t.hasParentOverSixty),r.preventiveHealthCheckUp=Oe(t.preventiveHealthCheckUp),r.medicalExpenditure=Oe(t.medicalExpenditure),r.savingBankInterest=Oe(t.savingBankInterest),r.fdInterest=Oe(t.fdInterest),r.dividend=Oe(t.dividend),r.anyOtherIncome=Oe(t.anyOtherIncome),r.cryptoSellValue=Oe(t.cryptoSellPrice),r.cryptoPurchaseAmount=Oe(t.cryptoPurchasePrice),r.vdaPurchaseCost=Oe(t.cryptoPurchasePrice),r.businessName=Re(t.businessName),r.businessAnnualTurnOver=Oe(t.grossReceipts),r.businessNetProfit=Oe(t.netProfit),r.agricultureDetails={income:Oe(t.agricultureIncome)},r.exemptIncomeAmount=Oe(t.exemptIncome),r.exemptIncomeNature=Re(t.exemptIncomeNature),Oe(t.exemptIncome)!==void 0&&(r.exemptIncomes=[{name:Re(t.exemptIncomeNature)??"Exempt income",value:String(Oe(t.exemptIncome))}]),r.bankAccountNumber=Re(t.bankAccountNumber),r.bankIfscCode=Re(t.bankIfscCode),(Re(t.bankAccountNumber)||Re(t.bankIfscCode))&&(r.bankDetails=[{bankAccountNumber:Re(t.bankAccountNumber),bankIfscCode:Re(t.bankIfscCode)}]);const o={description:Re(t.immovableAssetDescription),flatNo:Re(t.immovableAssetFlatNo),area:Re(t.immovableAssetArea),pinCode:Re(t.immovableAssetPincode),amount:Oe(t.immovableAssetCost)};Object.values(o).some(s=>s!==void 0)&&(r.immovableAsset=[o]);const n=mo(t.hpDetails,Kh);n.length&&(r.hpDetails=n);const i=mo(t.salaryDetails,Yh);if(i.length){r.salaryIncome=i;const s=mo(t.salaryDetails,c=>({grossSalary:Oe(c.grossSalary),employerName:Re(c.employerName)}));s.length&&(r.salary=s);const l=xl(t.salaryDetails)[0]??{};r.hraAmount=Oe(l.hraReceived),r.leaveTravelAllowanceAmount=Oe(l.leaveTravelAllowance),r.leaveEncashmentAllowanceAmount=Oe(l.leaveEncashment),r.anyOtherAllowanceAmount=Oe(l.anyOtherAllowance),r.salaryIncomeFlag=!0}return Hr(r)}function Kh(a){const e={loanType:"HOME_LOAN",loanTakenFrom:Re(a.loanTakenFrom),bankOrInstituteName:Re(a.lenderName),loanAccountNo:Re(a.loanAccountNumber),loanSanctionDate:Qh(a.sanctionDate),totalLoanAmount:Oe(a.totalLoanAmount),interest:Oe(a.homeLoanInterest)},t=Object.entries(e).some(([r,o])=>r!=="loanType"&&o!==void 0);return{typeOfHouseProperty:Re(a.typeOfHouseProperty),hasRentalIncome:a.typeOfHouseProperty==="LOP"?!0:po(a.hasRentalIncome),homeLoanInterest:Oe(a.homeLoanInterest),homeLoanPrinciple:Oe(a.homeLoanPrinciple),housePropertyAddress:Re(a.housePropertyAddress),housePropertyPincode:Re(a.housePropertyPincode),rentalIncome:Oe(a.rentalIncome),nameOfTenant:Re(a.nameOfTenant),propertyTax:Oe(a.propertyTax),hasCoOwnedProperty:po(a.hasCoOwnedProperty),coOwnerName:Re(a.coOwnerName),coOwnerPan:Re(a.coOwnerPan),coOwnerShare:Re(a.coOwnerShare),loanDetails:t?[e]:void 0}}function Yh(a){return{grossSalaryIncome:Oe(a.grossSalary),salary:Oe(a.basicSalary),employer:{employerName:Re(a.employerName),employerTan:Re(a.employerTan)},allowance:{hraAmount:Oe(a.hraReceived),leaveTravelAllowanceAmount:Oe(a.leaveTravelAllowance),leaveEncashmentAllowanceAmount:Oe(a.leaveEncashment),anyOtherAllowanceAmount:Oe(a.anyOtherAllowance)}}}function Jh(a){if(a===void 0||a==="")return;const e=Number(a);return Number.isFinite(e)&&String(e)===String(a)?e:a}function Oe(a){if(a==null||a==="")return;const e=typeof a=="number"?a:Number(a);return Number.isFinite(e)?e:void 0}function Re(a){if(a==null)return;const e=String(a).trim();return e===""?void 0:e}function po(a){return a===!0||a===!1?a:void 0}function Qh(a){const e=Re(a);if(e)return e.includes("T")?e:/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e}function xl(a){return Array.isArray(a)?a.filter(e=>e&&typeof e=="object"):[]}function mo(a,e){return xl(a).map(t=>Hr(e(t))).filter(t=>t!==void 0)}function Hr(a){if(Array.isArray(a)){const e=a.map(Hr).filter(t=>t!==void 0);return e.length?e:void 0}if(a&&typeof a=="object"){const e={};for(const[t,r]of Object.entries(a)){const o=Hr(r);o!==void 0&&(e[t]=o)}return Object.keys(e).length?e:void 0}return a}function Sl(){if(typeof window>"u")return null;const a=window,e=a.__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=a.__aikaara_descriptor__??{},r=ed(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=td(e.slug),n=typeof o?.tenantJwt=="string"?o.tenantJwt:"",i=e.getChatJwt,s=async()=>n||await i(),l=(o&&o.userId!=null&&o.userId!==""?String(o.userId):nd(e.identity))||void 0;return console.info("[smart-edit] API config — base:",r,"· userId:",l??"(none)"),{baseUrl:r,getToken:s,headers:rd(t.auth?.headers),assessmentYear:t.itr?.assessmentYear||id(),isRevised:"N",userId:l,submitUrl:t.itr?.automationSubmitUrl||void 0}}async function Xh(a){const e=await a.getToken(),t=a.userId;if(!t)throw new Error("[smart-edit] no userId for GET /itr/latest-itr (aikaara_sso identity missing)");const r=await fetch(`${a.baseUrl}/itr/latest-itr?userId=${encodeURIComponent(t)}`,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`,...a.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 El(await r.json().catch(()=>({})))}async function Zh(a,e){const t=await a.getToken(),r=a.userId,o=Gh(e,{userId:r,assessmentYear:a.assessmentYear,isRevised:a.isRevised}),n=a.submitUrl||`${a.baseUrl}/itr/v1/automation/data`,i={accept:"application/json","content-type":"application/json",authorization:`Bearer ${t}`,...a.headers};a.txbdyApiKey&&(i["txbdy-api-key"]=a.txbdyApiKey),console.info("[smart-edit] PUT",n,"— DTO keys:",Object.keys(o).join(", "));const s=await fetch(n,{method:"PUT",headers:i,body:JSON.stringify(o)});if(!s.ok){const l=await s.text().catch(()=>"");throw new Error(`[smart-edit] PUT ${n} → ${s.status} ${l.slice(0,200)}`)}return El(await s.json().catch(()=>({})))}function ed(a){const e=[a.cloud?.listEndpoint,a.cloud?.downloadEndpoint,a.upload?.signEndpoint,a.login?.pan?.basicPanEndpoint,a.login?.pan?.panDetailEndpoint,a.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 td(a){if(!a||typeof localStorage>"u")return null;try{const e=localStorage.getItem(`aikaara_sso:${a}`);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 rd(a){const e={};if(!a)return e;const t=/^(authorization|content-type|accept)$/i;for(const[r,o]of Object.entries(a))!t.test(r)&&typeof o=="string"&&(e[r]=o);return e}function nd(a){if(!a)return;const e=a.userId??a.id??a.ext_uid??a.extUid;return e==null||e===""?void 0:String(e)}function El(a){if(a&&typeof a=="object"){const e=a;return e.data&&typeof e.data=="object"?e.data:e}return{}}function id(){const a=new Date,e=a.getMonth()>=3?a.getFullYear():a.getFullYear()-1;return`${e}-${e+1}`}class od{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;smartEditModal=null;constructor(e,t,r){this.client=new yl(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:Vh,data:{}});const t=Sl();if(!(!t||!t.baseUrl))try{const r=await Xh(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-recalculate",(t=>{const r=t.detail;this.handleSmartEditSave(r.record)})),this.smartEditModal=e,e}async handleSmartEditSave(e){console.info("[smart-edit] Save & Recalculate — persisting record");const t=Sl();if(!t){console.warn("[smart-edit] save skipped — no API config (see the warning above for why)");return}try{await Zh(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 Al 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||kc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||Io,position:this.getAttribute("position")||this._config.position||_c,width:Number(this.getAttribute("width"))||this._config.width||bc,height:Number(this.getAttribute("height"))||this._config.height||yc,fontFamily:this._config.fontFamily||wc,borderRadius:this._config.borderRadius??vc,placeholder:this.getAttribute("placeholder")||this._config.placeholder||To,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||xc,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=(s,l)=>{l!==void 0&&l!==""&&n.style.setProperty(`--aikaara-${s}`,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;
@@ -921,7 +921,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
921
921
  ${Pt(i.label)}
922
922
  </button>`).join("")}
923
923
  </div>
924
- `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Pt(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function yo(a){return String(a).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Id extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const o=r.getValues?.();o?.name&&(e[o.name]=o.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
924
+ `,this.preSelectedDisabled||this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Pt(a){return String(a).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function yo(a){return String(a).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Id extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const o=r.getValues?.();o?.name&&(e[o.name]=o.type==="radio"?o.values[0]??"":o.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
925
925
  <style>
926
926
  :host { display: block; margin: 12px 0 4px; }
927
927
  button {