@aikaara/chat-sdk 0.4.4 → 0.4.5

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.
@@ -11686,7 +11686,7 @@ function Lc(u) {
11686
11686
  const p = await u.getToken();
11687
11687
  p && (i.authorization = p);
11688
11688
  }
11689
- const a = await fetch(o, { method: "GET", headers: i, credentials: "include" }), c = await a.json().catch(() => null);
11689
+ const a = await fetch(o, { method: "GET", headers: i }), c = await a.json().catch(() => null);
11690
11690
  if (u.parseResponse && c) return u.parseResponse(c);
11691
11691
  const d = c;
11692
11692
  if (d && Array.isArray(d.result))
@@ -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 xe+I.call(z,","+xe)+`
6
6
  `+ie.prev}function Se(z,ie){var xe=be(z),Ae=[];if(xe){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=se(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],Ke;if(D){Ke={};for(var Ge=0;Ge<Oe.length;Ge++)Ke["$"+Oe[Ge]]=Oe[Ge]}for(var Ue in z)se(z,Ue)&&(xe&&String(Number(Ue))===Ue&&Ue<z.length||D&&Ke["$"+Ue]instanceof Symbol||(k.call(/[^\w$]/,Ue)?Ae.push(ie(Ue,z)+": "+ie(z[Ue],z)):Ae.push(Ue+": "+ie(z[Ue],z))));if(typeof T=="function")for(var Qe=0;Qe<Oe.length;Qe++)ae.call(z,Oe[Qe])&&Ae.push("["+ie(Oe[Qe])+"]: "+ie(z[Oe[Qe]],z));return Ae}return yr}function Nc(){if(ji)return wr;ji=!0;var u=Ut(),e=wc(),t=jc(),s=Yt(),l=u("%WeakMap%",!0),r=u("%Map%",!0),n=e("WeakMap.prototype.get",!0),o=e("WeakMap.prototype.set",!0),i=e("WeakMap.prototype.has",!0),a=e("Map.prototype.get",!0),c=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,S){for(var g=b,_;(_=g.next)!==null;g=_)if(_.key===S)return g.next=_.next,_.next=b.next,b.next=_,_},y=function(b,S){var g=p(b,S);return g&&g.value},f=function(b,S,g){var _=p(b,S);_?_.value=g:b.next={key:S,next:b.next,value:g}},m=function(b,S){return!!p(b,S)};return wr=function(){var b,S,g,_={assert:function(x){if(!_.has(x))throw new s("Side channel does not contain "+t(x))},get:function(x){if(l&&x&&(typeof x=="object"||typeof x=="function")){if(b)return n(b,x)}else if(r){if(S)return a(S,x)}else if(g)return y(g,x)},has:function(x){if(l&&x&&(typeof x=="object"||typeof x=="function")){if(b)return i(b,x)}else if(r){if(S)return d(S,x)}else if(g)return m(g,x);return!1},set:function(x,v){l&&x&&(typeof x=="object"||typeof x=="function")?(b||(b=new l),o(b,x,v)):r?(S||(S=new r),c(S,x,v)):(g||(g={key:{},next:null}),f(g,x,v))}};return _},wr}function Zi(){if(Ni)return _r;Ni=!0;var u=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return _r={default:t.RFC3986,formatters:{RFC1738:function(s){return u.call(s,e,"+")},RFC3986:function(s){return String(s)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},_r}function Pa(){if(Li)return Sr;Li=!0;var u=Zi(),e=Object.prototype.hasOwnProperty,t=Array.isArray,s=(function(){for(var b=[],S=0;S<256;++S)b.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return b})(),l=function(b){for(;b.length>1;){var S=b.pop(),g=S.obj[S.prop];if(t(g)){for(var _=[],x=0;x<g.length;++x)typeof g[x]<"u"&&_.push(g[x]);S.obj[S.prop]=_}}},r=function(b,S){for(var g=S&&S.plainObjects?Object.create(null):{},_=0;_<b.length;++_)typeof b[_]<"u"&&(g[_]=b[_]);return g},n=function b(S,g,_){if(!g)return S;if(typeof g!="object"){if(t(S))S.push(g);else if(S&&typeof S=="object")(_&&(_.plainObjects||_.allowPrototypes)||!e.call(Object.prototype,g))&&(S[g]=!0);else return[S,g];return S}if(!S||typeof S!="object")return[S].concat(g);var x=S;return t(S)&&!t(g)&&(x=r(S,_)),t(S)&&t(g)?(g.forEach(function(v,k){if(e.call(S,k)){var E=S[k];E&&typeof E=="object"&&v&&typeof v=="object"?S[k]=b(E,v,_):S.push(v)}else S[k]=v}),S):Object.keys(g).reduce(function(v,k){var E=g[k];return e.call(v,k)?v[k]=b(v[k],E,_):v[k]=E,v},x)},o=function(b,S){return Object.keys(S).reduce(function(g,_){return g[_]=S[_],g},b)},i=function(b,S,g){var _=b.replace(/\+/g," ");if(g==="iso-8859-1")return _.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(_)}catch{return _}},a=1024,c=function(b,S,g,_,x){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),g==="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 k="",E=0;E<v.length;E+=a){for(var I=v.length>=a?v.slice(E,E+a):v,M=[],C=0;C<I.length;++C){var B=I.charCodeAt(C);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||x===u.RFC1738&&(B===40||B===41)){M[M.length]=I.charAt(C);continue}if(B<128){M[M.length]=s[B];continue}if(B<2048){M[M.length]=s[192|B>>6]+s[128|B&63];continue}if(B<55296||B>=57344){M[M.length]=s[224|B>>12]+s[128|B>>6&63]+s[128|B&63];continue}C+=1,B=65536+((B&1023)<<10|I.charCodeAt(C)&1023),M[M.length]=s[240|B>>18]+s[128|B>>12&63]+s[128|B>>6&63]+s[128|B&63]}k+=M.join("")}return k},d=function(b){for(var S=[{obj:{o:b},prop:"o"}],g=[],_=0;_<S.length;++_)for(var x=S[_],v=x.obj[x.prop],k=Object.keys(v),E=0;E<k.length;++E){var I=k[E],M=v[I];typeof M=="object"&&M!==null&&g.indexOf(M)===-1&&(S.push({obj:v,prop:I}),g.push(M))}return l(S),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,S){return[].concat(b,S)},m=function(b,S){if(t(b)){for(var g=[],_=0;_<b.length;_+=1)g.push(S(b[_]));return g}return S(b)};return Sr={arrayToObject:r,assign:o,combine:f,compact:d,decode:i,encode:c,isBuffer:y,isRegExp:p,maybeMap:m,merge:n},Sr}function Lc(){if(Ui)return Er;Ui=!0;var u=Nc(),e=Pa(),t=Zi(),s=Object.prototype.hasOwnProperty,l={brackets:function(m){return m+"[]"},comma:"comma",indices:function(m,b){return m+"["+b+"]"},repeat:function(m){return m}},r=Array.isArray,n=Array.prototype.push,o=function(m,b){n.apply(m,r(b)?b:[b])},i=Date.prototype.toISOString,a=t.default,c={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:a,formatter:t.formatters[a],indices:!1,serializeDate:function(m){return i.call(m)},skipNulls:!1,strictNullHandling:!1},d=function(m){return typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="symbol"||typeof m=="bigint"},p={},y=function m(b,S,g,_,x,v,k,E,I,M,C,B,T,$,D,L,ae,Q){for(var V=b,re=Q,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(F+=1,typeof P<"u"){if(P===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof M=="function"?V=M(S,V):V instanceof Date?V=T(V):g==="comma"&&r(V)&&(V=e.maybeMap(V,function(R){return R instanceof Date?T(R):R})),V===null){if(v)return I&&!L?I(S,c.encoder,ae,"key",$):S;V=""}if(d(V)||e.isBuffer(V)){if(I){var J=L?S:I(S,c.encoder,ae,"key",$);return[D(J)+"="+D(I(V,c.encoder,ae,"value",$))]}return[D(S)+"="+D(String(V))]}var be=[];if(typeof V>"u")return be;var te;if(g==="comma"&&r(V))L&&I&&(V=e.maybeMap(V,I)),te=[{value:V.length>0?V.join(",")||null:void 0}];else if(r(M))te=M;else{var we=Object.keys(V);te=C?we.sort(C):we}var K=E?S.replace(/\./g,"%2E"):S,N=_&&r(V)&&V.length===1?K+"[]":K;if(x&&r(V)&&V.length===0)return N+"[]";for(var ne=0;ne<te.length;++ne){var H=te[ne],G=typeof H=="object"&&typeof H.value<"u"?H.value:V[H];if(!(k&&G===null)){var Y=B&&E?H.replace(/\./g,"%2E"):H,me=r(V)?typeof g=="function"?g(N,Y):N:N+(B?"."+Y:"["+Y+"]");Q.set(b,F);var se=u();se.set(p,Q),o(be,m(G,me,g,_,x,v,k,E,g==="comma"&&L&&r(V)?null:I,M,C,B,T,$,D,L,ae,se))}}return be},f=function(m){if(!m)return c;if(typeof m.allowEmptyArrays<"u"&&typeof m.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof m.encodeDotInKeys<"u"&&typeof m.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(m.encoder!==null&&typeof m.encoder<"u"&&typeof m.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=m.charset||c.charset;if(typeof m.charset<"u"&&m.charset!=="utf-8"&&m.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var S=t.default;if(typeof m.format<"u"){if(!s.call(t.formatters,m.format))throw new TypeError("Unknown format option provided.");S=m.format}var g=t.formatters[S],_=c.filter;(typeof m.filter=="function"||r(m.filter))&&(_=m.filter);var x;if(m.arrayFormat in l?x=m.arrayFormat:"indices"in m?x=m.indices?"indices":"repeat":x=c.arrayFormat,"commaRoundTrip"in m&&typeof m.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof m.allowDots>"u"?m.encodeDotInKeys===!0?!0:c.allowDots:!!m.allowDots;return{addQueryPrefix:typeof m.addQueryPrefix=="boolean"?m.addQueryPrefix:c.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof m.allowEmptyArrays=="boolean"?!!m.allowEmptyArrays:c.allowEmptyArrays,arrayFormat:x,charset:b,charsetSentinel:typeof m.charsetSentinel=="boolean"?m.charsetSentinel:c.charsetSentinel,commaRoundTrip:m.commaRoundTrip,delimiter:typeof m.delimiter>"u"?c.delimiter:m.delimiter,encode:typeof m.encode=="boolean"?m.encode:c.encode,encodeDotInKeys:typeof m.encodeDotInKeys=="boolean"?m.encodeDotInKeys:c.encodeDotInKeys,encoder:typeof m.encoder=="function"?m.encoder:c.encoder,encodeValuesOnly:typeof m.encodeValuesOnly=="boolean"?m.encodeValuesOnly:c.encodeValuesOnly,filter:_,format:S,formatter:g,serializeDate:typeof m.serializeDate=="function"?m.serializeDate:c.serializeDate,skipNulls:typeof m.skipNulls=="boolean"?m.skipNulls:c.skipNulls,sort:typeof m.sort=="function"?m.sort:null,strictNullHandling:typeof m.strictNullHandling=="boolean"?m.strictNullHandling:c.strictNullHandling}};return Er=function(m,b){var S=m,g=f(b),_,x;typeof g.filter=="function"?(x=g.filter,S=x("",S)):r(g.filter)&&(x=g.filter,_=x);var v=[];if(typeof S!="object"||S===null)return"";var k=l[g.arrayFormat],E=k==="comma"&&g.commaRoundTrip;_||(_=Object.keys(S)),g.sort&&_.sort(g.sort);for(var I=u(),M=0;M<_.length;++M){var C=_[M];g.skipNulls&&S[C]===null||o(v,y(S[C],C,k,E,g.allowEmptyArrays,g.strictNullHandling,g.skipNulls,g.encodeDotInKeys,g.encode?g.encoder:null,g.filter,g.sort,g.allowDots,g.serializeDate,g.format,g.formatter,g.encodeValuesOnly,g.charset,I))}var B=v.join(g.delimiter),T=g.addQueryPrefix===!0?"?":"";return g.charsetSentinel&&(g.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},Er}function Uc(){if(Bi)return kr;Bi=!0;var u=Pa(),e=Object.prototype.hasOwnProperty,t=Array.isArray,s={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:u.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},l=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},r=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},n="utf8=%26%2310003%3B",o="utf8=%E2%9C%93",i=function(p,y){var f={__proto__:null},m=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;m=m.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,S=m.split(y.delimiter,b),g=-1,_,x=y.charset;if(y.charsetSentinel)for(_=0;_<S.length;++_)S[_].indexOf("utf8=")===0&&(S[_]===o?x="utf-8":S[_]===n&&(x="iso-8859-1"),g=_,_=S.length);for(_=0;_<S.length;++_)if(_!==g){var v=S[_],k=v.indexOf("]="),E=k===-1?v.indexOf("="):k+1,I,M;E===-1?(I=y.decoder(v,s.decoder,x,"key"),M=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,E),s.decoder,x,"key"),M=u.maybeMap(r(v.slice(E+1),y),function(B){return y.decoder(B,s.decoder,x,"value")})),M&&y.interpretNumericEntities&&x==="iso-8859-1"&&(M=l(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var C=e.call(f,I);C&&y.duplicates==="combine"?f[I]=u.combine(f[I],M):(!C||y.duplicates==="last")&&(f[I]=M)}return f},a=function(p,y,f,m){for(var b=m?y:r(y,f),S=p.length-1;S>=0;--S){var g,_=p[S];if(_==="[]"&&f.parseArrays)g=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{g=f.plainObjects?Object.create(null):{};var x=_.charAt(0)==="["&&_.charAt(_.length-1)==="]"?_.slice(1,-1):_,v=f.decodeDotInKeys?x.replace(/%2E/g,"."):x,k=parseInt(v,10);!f.parseArrays&&v===""?g={0:b}:!isNaN(k)&&_!==v&&String(k)===v&&k>=0&&f.parseArrays&&k<=f.arrayLimit?(g=[],g[k]=b):v!=="__proto__"&&(g[v]=b)}b=g}return b},c=function(p,y,f,m){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,S=/(\[[^[\]]*])/,g=/(\[[^[\]]*])/g,_=f.depth>0&&S.exec(b),x=_?b.slice(0,_.index):b,v=[];if(x){if(!f.plainObjects&&e.call(Object.prototype,x)&&!f.allowPrototypes)return;v.push(x)}for(var k=0;f.depth>0&&(_=g.exec(b))!==null&&k<f.depth;){if(k+=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("["+b.slice(_.index)+"]")}return a(v,y,f,m)}},d=function(p){if(!p)return s;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 y=typeof p.charset>"u"?s.charset:p.charset,f=typeof p.duplicates>"u"?s.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var m=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:s.allowDots:!!p.allowDots;return{allowDots:m,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:s.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:s.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:s.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:s.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:s.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:s.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:s.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:s.decoder,delimiter:typeof p.delimiter=="string"||u.isRegExp(p.delimiter)?p.delimiter:s.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:s.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:s.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:s.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:s.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:s.strictNullHandling}};return kr=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var m=typeof p=="string"?i(p,f):p,b=f.plainObjects?Object.create(null):{},S=Object.keys(m),g=0;g<S.length;++g){var _=S[g],x=c(_,m[_],f,typeof p=="string");b=u.merge(b,x,f)}return f.allowSparse===!0?b:u.compact(b)},kr}function Bc(){if(Di)return xr;Di=!0;var u=Lc(),e=Uc(),t=Zi();return xr={formats:t,parse:e,stringify:u},xr}function Dc(){if(Fi)return gt;Fi=!0;var u=pt;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,s=/:[0-9]*$/,l=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,r=["<",">",'"',"`"," ","\r",`
7
7
  `," "],n=["{","}","|","\\","^","`"].concat(r),o=["'"].concat(n),i=["%","/","?",";","#"].concat(o),a=["/","?","#"],c=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Bc();function S(v,k,E){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,k,E),I}e.prototype.parse=function(v,k,E){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),M=I!==-1&&I<v.indexOf("#")?"?":"#",C=v.split(M),B=/\\/g;C[0]=C[0].replace(B,"/"),v=C.join(M);var T=v;if(T=T.trim(),!E&&v.split("#").length===1){var $=l.exec(T);if($)return this.path=T,this.href=T,this.pathname=$[1],$[2]?(this.search=$[2],k?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):k&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var L=D.toLowerCase();this.protocol=L,T=T.substr(D.length)}if(E||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&&!m[D])){for(var Q=-1,V=0;V<a.length;V++){var re=T.indexOf(a[V]);re!==-1&&(Q===-1||re<Q)&&(Q=re)}var F,Z;Q===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Q),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Q=-1;for(var V=0;V<i.length;V++){var re=T.indexOf(i[V]);re!==-1&&(Q===-1||re<Q)&&(Q=re)}Q===-1&&(Q=T.length),this.host=T.slice(0,Q),T=T.slice(Q),this.parseHost(),this.hostname=this.hostname||"";var P=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!P)for(var J=this.hostname.split(/\./),V=0,be=J.length;V<be;V++){var te=J[V];if(te&&!te.match(d)){for(var we="",K=0,N=te.length;K<N;K++)te.charCodeAt(K)>127?we+="x":we+=te[K];if(!we.match(d)){var ne=J.slice(0,V),H=J.slice(V+1),G=te.match(p);G&&(ne.push(G[1]),H.unshift(G[2])),H.length&&(T="/"+H.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>c?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=u.toASCII(this.hostname));var Y=this.port?":"+this.port:"",me=this.hostname||"";this.host=me+Y,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[L])for(var V=0,be=o.length;V<be;V++){var se=o[V];if(T.indexOf(se)!==-1){var R=encodeURIComponent(se);R===se&&(R=escape(se)),T=T.split(se).join(R)}}var W=T.indexOf("#");W!==-1&&(this.hash=T.substr(W),T=T.slice(0,W));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),k&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):k&&(this.search="",this.query={}),T&&(this.pathname=T),m[L]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Y=this.pathname||"",fe=this.search||"";this.path=Y+fe}return this.href=this.format(),this};function g(v){return typeof v=="string"&&(v=S(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 k=this.protocol||"",E=this.pathname||"",I=this.hash||"",M=!1,C="";this.host?M=v+this.host:this.hostname&&(M=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(M+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(C=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||C&&"?"+C||"";return k&&k.substr(-1)!==":"&&(k+=":"),this.slashes||(!k||m[k])&&M!==!1?(M="//"+(M||""),E&&E.charAt(0)!=="/"&&(E="/"+E)):M||(M=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),E=E.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),k+M+E+B+I};function _(v,k){return S(v,!1,!0).resolve(k)}e.prototype.resolve=function(v){return this.resolveObject(S(v,!1,!0)).format()};function x(v,k){return v?S(v,!1,!0).resolveObject(k):k}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var k=new e;k.parse(v,!1,!0),v=k}for(var E=new e,I=Object.keys(this),M=0;M<I.length;M++){var C=I[M];E[C]=this[C]}if(E.hash=v.hash,v.href==="")return E.href=E.format(),E;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var $=B[T];$!=="protocol"&&(E[$]=v[$])}return m[E.protocol]&&E.hostname&&!E.pathname&&(E.pathname="/",E.path=E.pathname),E.href=E.format(),E}if(v.protocol&&v.protocol!==E.protocol){if(!m[v.protocol]){for(var D=Object.keys(v),L=0;L<D.length;L++){var ae=D[L];E[ae]=v[ae]}return E.href=E.format(),E}if(E.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),E.pathname=be.join("/")}else E.pathname=v.pathname;if(E.search=v.search,E.query=v.query,E.host=v.host||"",E.auth=v.auth,E.hostname=v.hostname||v.host,E.port=v.port,E.pathname||E.search){var Q=E.pathname||"",V=E.search||"";E.path=Q+V}return E.slashes=E.slashes||v.slashes,E.href=E.format(),E}var re=E.pathname&&E.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||E.host&&v.pathname,P=Z,J=E.pathname&&E.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=E.protocol&&!m[E.protocol];if(te&&(E.hostname="",E.port=null,E.host&&(J[0]===""?J[0]=E.host:J.unshift(E.host)),E.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),F)E.host=v.host||v.host===""?v.host:E.host,E.hostname=v.hostname||v.hostname===""?v.hostname:E.hostname,E.search=v.search,E.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),E.search=v.search,E.query=v.query;else if(v.search!=null){if(te){E.host=J.shift(),E.hostname=E.host;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return E.search=v.search,E.query=v.query,(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.href=E.format(),E}if(!J.length)return E.pathname=null,E.search?E.path="/"+E.search:E.path=null,E.href=E.format(),E;for(var K=J.slice(-1)[0],N=(E.host||v.host||J.length>1)&&(K==="."||K==="..")||K==="",ne=0,H=J.length;H>=0;H--)K=J[H],K==="."?J.splice(H,1):K===".."?(J.splice(H,1),ne++):ne&&(J.splice(H,1),ne--);if(!Z&&!P)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),N&&J.join("/").substr(-1)!=="/"&&J.push("");var G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){E.hostname=G?"":J.length?J.shift():"",E.host=E.hostname;var we=E.host&&E.host.indexOf("@")>0?E.host.split("@"):!1;we&&(E.auth=we.shift(),E.hostname=we.shift(),E.host=E.hostname)}return Z=Z||E.host&&J.length,Z&&!G&&J.unshift(""),J.length>0?E.pathname=J.join("/"):(E.pathname=null,E.path=null),(E.pathname!==null||E.search!==null)&&(E.path=(E.pathname?E.pathname:"")+(E.search?E.search:"")),E.auth=v.auth||E.auth,E.slashes=E.slashes||v.slashes,E.href=E.format(),E},e.prototype.parseHost=function(){var v=this.host,k=s.exec(v);k&&(k=k[0],k!==":"&&(this.port=k.substr(1)),v=v.substr(0,v.length-k.length)),v&&(this.hostname=v)},gt.parse=S,gt.resolve=_,gt.resolveObject=x,gt.format=g,gt.Url=e,gt}function Ma(u){if(typeof u=="string")u=new URL(u);else if(!(u instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(u.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Ir?Fc(u):Wc(u)}function Fc(u){let e=u.hostname,t=u.pathname;for(let s=0;s<t.length;s++)if(t[s]==="%"){let l=t.codePointAt(s+2)||32;if(t[s+1]==="2"&&l===102||t[s+1]==="5"&&l===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(za,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let s=t.codePointAt(1)|32,l=t[2];if(s<qa||s>Ha||l!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Wc(u){if(u.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=u.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let s=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&s===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function Ra(u){let e=Mi.resolve(u),t=u.charCodeAt(u.length-1);(t===$a||Ir&&t===Wa)&&e[e.length-1]!==Mi.sep&&(e+="/");let s=new URL("file://");return e.includes("%")&&(e=e.replace(Va,"%25")),!Ir&&e.includes("\\")&&(e=e.replace(Ka,"%5C")),e.includes(`
8
- `)&&(e=e.replace(Ga,"%0A")),e.includes("\r")&&(e=e.replace(Qa,"%0D")),e.includes(" ")&&(e=e.replace(Ya,"%09")),s.pathname=e,s}var ja,yr,Ri,vr,wr,ji,_r,Ni,Sr,Li,Er,Ui,kr,Bi,xr,Di,gt,Fi,Fe,co,Na,La,Ua,Ba,Da,Fa,Wa,$a,qa,Ha,Ir,za,Va,Ka,Ga,Qa,Ya,$c=He(()=>{le(),ce(),ue(),sc(),_c(),Rc(),Oa(),ja=Object.freeze(Object.create(null)),yr={},Ri=!1,vr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,wr={},ji=!1,_r={},Ni=!1,Sr={},Li=!1,Er={},Ui=!1,kr={},Bi=!1,xr={},Di=!1,gt={},Fi=!1,Fe=Dc(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,co=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=Ra,Fe.fileURLToPath=Ma,Na=Fe.Url,La=Fe.format,Ua=Fe.resolve,Ba=Fe.resolveObject,Da=Fe.parse,Fa=Fe.URL,Wa=92,$a=47,qa=97,Ha=122,Ir=co==="win32",za=/\//g,Va=/%/g,Ka=/\\/g,Ga=/\n/g,Qa=/\r/g,Ya=/\t/g}),qc=pe((u,e)=>{le(),ce(),ue(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),es=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0}),u.BufferedDuplex=void 0,u.writev=s;var e=At(),t=(Le(),Ce(Ne));function s(r,n){let o=new Array(r.length);for(let i=0;i<r.length;i++)typeof r[i].chunk=="string"?o[i]=t.Buffer.from(r[i].chunk,"utf8"):o[i]=r[i].chunk;this._write(t.Buffer.concat(o),"binary",n)}var l=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(r,n,o){super({objectMode:!0}),this.proxy=n,this.socket=o,this.writeQueue=[],r.objectMode||(this._writev=s.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",i=>{!this.destroyed&&this.readable&&this.push(i)})}_read(r){this.proxy.read(r)}_write(r,n,o){this.isSocketOpen?this.writeToProxy(r,n,o):this.writeQueue.push({chunk:r,encoding:n,cb:o})}_final(r){this.writeQueue=[],this.proxy.end(r)}_destroy(r,n){this.writeQueue=[],this.proxy.destroy(),n(r)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(r,n,o){this.proxy.write(r,n)===!1?this.proxy.once("drain",o):o()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:r,encoding:n,cb:o}=this.writeQueue.shift();this.writeToProxy(r,n,o)}}};u.BufferedDuplex=l}),er=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(S){return S&&S.__esModule?S:{default:S}};Object.defineProperty(u,"__esModule",{value:!0}),u.streamBuilder=u.browserStreamBuilder=void 0;var t=(Le(),Ce(Ne)),s=e(qc()),l=e(at()),r=At(),n=e(Rr()),o=es(),i=(0,l.default)("mqttjs:ws"),a=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function c(S,g){let _=`${S.protocol}://${S.hostname}:${S.port}${S.path}`;return typeof S.transformWsUrl=="function"&&(_=S.transformWsUrl(_,S,g)),_}function d(S){let g=S;return S.port||(S.protocol==="wss"?g.port=443:g.port=80),S.path||(g.path="/"),S.wsOptions||(g.wsOptions={}),!n.default&&!S.forceNativeWebSocket&&S.protocol==="wss"&&a.forEach(_=>{Object.prototype.hasOwnProperty.call(S,_)&&!Object.prototype.hasOwnProperty.call(S.wsOptions,_)&&(g.wsOptions[_]=S[_])}),g}function p(S){let g=d(S);if(g.hostname||(g.hostname=g.host),!g.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);g.hostname=_.hostname,g.port||(g.port=Number(_.port))}return g.objectMode===void 0&&(g.objectMode=!(g.binary===!0||g.binary===void 0)),g}function y(S,g,_){i("createWebSocket"),i(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";i(`creating new Websocket for url: ${g} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(g,[x],_):v=new s.default(g,[x],_.wsOptions),v}function f(S,g){let _=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt",x=c(g,S),v;return g.createWebsocket?v=g.createWebsocket(x,[_],g):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var m=(S,g)=>{i("streamBuilder");let _=d(g);_.hostname=_.hostname||_.host||"localhost";let x=c(_,S),v=y(S,x,_),k=s.default.createWebSocketStream(v,_.wsOptions);return k.url=x,v.on("close",()=>{k.destroy()}),k};u.streamBuilder=m;var b=(S,g)=>{i("browserStreamBuilder");let _,x=p(g).browserBufferSize||1024*512,v=g.browserBufferTimeout||1e3,k=!g.objectMode,E=f(S,g),I=C(g,L,ae);g.objectMode||(I._writev=o.writev.bind(I)),I.on("close",()=>{E.close()});let M=typeof E.addEventListener<"u";E.readyState===E.OPEN?(_=I,_.socket=E):(_=new o.BufferedDuplex(g,I,E),M?E.addEventListener("open",B):E.onopen=B),M?(E.addEventListener("close",T),E.addEventListener("error",$),E.addEventListener("message",D)):(E.onclose=T,E.onerror=$,E.onmessage=D);function C(Q,V,re){let F=new r.Transform({objectMode:Q.objectMode});return F._write=V,F._flush=re,F}function B(){i("WebSocket onOpen"),_ instanceof o.BufferedDuplex&&_.socketReady()}function T(Q){i("WebSocket onClose",Q),_.end(),_.destroy()}function $(Q){i("WebSocket onError",Q);let V=new Error("WebSocket error");V.event=Q,_.destroy(V)}async function D(Q){if(!I||!I.readable||!I.writable)return;let{data:V}=Q;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 L(Q,V,re){if(E.bufferedAmount>x){setTimeout(L,v,Q,V,re);return}k&&typeof Q=="string"&&(Q=t.Buffer.from(Q,"utf8"));try{E.send(Q)}catch(F){return re(F)}re()}function ae(Q){E.close(),Q()}return _};u.browserStreamBuilder=b}),ts={};jt(ts,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>Ja,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ja,Xa=He(()=>{le(),ce(),ue(),Ja={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),Za=pe((u,e)=>{le(),ce(),ue(),e.exports={}}),ho=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(u,"__esModule",{value:!0});var t=e((Xa(),Ce(ts))),s=e(at()),l=e(Za()),r=(0,s.default)("mqttjs:tcp"),n=(o,i)=>{if(i.port=i.port||1883,i.hostname=i.hostname||i.host||"localhost",i.socksProxy)return(0,l.default)(i.hostname,i.port,i.socksProxy,{timeout:i.socksTimeout});let{port:a,path:c}=i,d=i.hostname;return r("port %d and host %s",a,d),t.default.createConnection({port:a,host:d,path:c})};u.default=n}),el={};jt(el,{default:()=>tl});var tl,Hc=He(()=>{le(),ce(),ue(),tl={}}),fo=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(u,"__esModule",{value:!0});var t=(Hc(),Ce(el)),s=e((Xa(),Ce(ts))),l=e(at()),r=e(Za()),n=(0,l.default)("mqttjs:tls");function o(a){let{host:c,port:d,socksProxy:p,...y}=a;if(p!==void 0){let f=(0,r.default)(c,d,p,{timeout:a.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(a)}var i=(a,c)=>{c.port=c.port||8883,c.host=c.hostname||c.host||"localhost",s.default.isIP(c.host)===0&&(c.servername=c.host),c.rejectUnauthorized=c.rejectUnauthorized!==!1,delete c.path,n("port %d host %s rejectUnauthorized %b",c.port,c.host,c.rejectUnauthorized);let d=o(c);d.on("secureConnect",()=>{c.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){c.rejectUnauthorized&&a.emit("error",y),d.end()}return d.on("error",p),d};u.default=i}),po=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0});var e=(Le(),Ce(Ne)),t=At(),s=es(),l,r,n;function o(){let p=new t.Transform;return p._write=(y,f,m)=>{l.send({data:y.buffer,success(){m()},fail(b){m(new Error(b))}})},p._flush=y=>{l.close({success(){y()}})},p}function i(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function a(p,y){let f=p.protocol==="wxs"?"wss":"ws",m=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(m=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(m=p.transformWsUrl(m,p,y)),m}function c(){l.onOpen(()=>{n.socketReady()}),l.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),r.push(y)}),l.onClose(()=>{n.emit("close"),n.end(),n.destroy()}),l.onError(p=>{let y=new Error(p.errMsg);n.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";i(y);let m=a(y,p);l=wx.connectSocket({url:m,protocols:[f]}),r=o(),n=new s.BufferedDuplex(y,r,l),n._destroy=(S,g)=>{l.close({success(){g&&g(S)}})};let b=n.destroy;return n.destroy=(S,g)=>(n.destroy=b,setTimeout(()=>{l.close({fail(){n._destroy(S,g)}})},0),n),c(),n};u.default=d}),go=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0});var e=(Le(),Ce(Ne)),t=At(),s=es(),l,r,n,o=!1;function i(){let y=new t.Transform;return y._write=(f,m,b)=>{l.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{l.closeSocket({success(){f()}})},y}function a(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function c(y,f){let m=y.protocol==="alis"?"wss":"ws",b=`${m}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${m}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){o||(o=!0,l.onSocketOpen(()=>{n.socketReady()}),l.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");r.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){r.push(e.Buffer.from(f.result));return}r.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),l.onSocketClose(()=>{n.end(),n.destroy()}),l.onSocketError(y=>{n.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let m=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";a(f);let b=c(f,y);return l=f.my,l.connectSocket({url:b,protocols:m}),r=i(),n=new s.BufferedDuplex(f,r,l),d(),n};u.default=p}),zc=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(u,"__esModule",{value:!0}),u.connectAsync=c;var t=e(at()),s=e(($c(),Ce(Ca))),l=e(Zn()),r=e(Rr());typeof Pe?.nextTick!="function"&&(Pe.nextTick=setImmediate);var n=(0,t.default)("mqttjs"),o=null;function i(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function a(d,p){if(n("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let m=s.default.parse(d,!0),b={};if(m.port!=null&&(b.port=Number(m.port)),b.host=m.hostname,b.query=m.query,b.auth=m.auth,b.protocol=m.protocol,b.path=m.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,i(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),r.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Pe<"u"&&(p.socksProxy=Pe.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(o||(o={},!r.default&&!p.forceNativeWebSocket?(o.ws=er().streamBuilder,o.wss=er().streamBuilder,o.mqtt=ho().default,o.tcp=ho().default,o.ssl=fo().default,o.tls=o.ssl,o.mqtts=fo().default):(o.ws=er().browserStreamBuilder,o.wss=er().browserStreamBuilder,o.wx=po().default,o.wxs=po().default,o.ali=go().default,o.alis=go().default)),!o[p.protocol]){let m=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,S)=>m&&S%2===0?!1:typeof o[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(m){return p.servers&&((!m._reconnectCount||m._reconnectCount===p.servers.length)&&(m._reconnectCount=0),p.host=p.servers[m._reconnectCount].host,p.port=p.servers[m._reconnectCount].port,p.protocol=p.servers[m._reconnectCount].protocol?p.servers[m._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,m._reconnectCount++),n("calling streambuilder for",p.protocol),o[p.protocol](m,p)}let f=new l.default(y,p);return f.on("error",()=>{}),f}function c(d,p,y=!0){return new Promise((f,m)=>{let b=a(d,p),S={connect:_=>{g(),f(b)},end:()=>{g(),f(b)},error:_=>{g(),b.end(),m(_)}};y===!1&&(S.close=()=>{S.error(new Error("Couldn't connect to server"))});function g(){Object.keys(S).forEach(_=>{b.off(_,S[_])})}Object.keys(S).forEach(_=>{b.on(_,S[_])})})}u.default=a}),mo=pe(u=>{le(),ce(),ue();var e=u&&u.__createBinding||(Object.create?function(y,f,m,b){b===void 0&&(b=m);var S=Object.getOwnPropertyDescriptor(f,m);(!S||("get"in S?!f.__esModule:S.writable||S.configurable))&&(S={enumerable:!0,get:function(){return f[m]}}),Object.defineProperty(y,b,S)}:function(y,f,m,b){b===void 0&&(b=m),y[b]=f[m]}),t=u&&u.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),s=u&&u.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(m){var b=[];for(var S in m)Object.prototype.hasOwnProperty.call(m,S)&&(b[b.length]=S);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var m={};if(f!=null)for(var b=y(f),S=0;S<b.length;S++)b[S]!=="default"&&e(m,f,b[S]);return t(m,f),m}})(),l=u&&u.__exportStar||function(y,f){for(var m in y)m!=="default"&&!Object.prototype.hasOwnProperty.call(f,m)&&e(f,y,m)},r=u&&u.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(u,"__esModule",{value:!0}),u.ReasonCodes=u.KeepaliveManager=u.UniqueMessageIdProvider=u.DefaultMessageIdProvider=u.Store=u.MqttClient=u.connectAsync=u.connect=u.Client=void 0;var n=r(Zn());u.MqttClient=n.default;var o=r(ba());u.DefaultMessageIdProvider=o.default;var i=r(nc());u.UniqueMessageIdProvider=i.default;var a=r(ea());u.Store=a.default;var c=s(zc());u.connect=c.default,Object.defineProperty(u,"connectAsync",{enumerable:!0,get:function(){return c.connectAsync}});var d=r(ka());u.KeepaliveManager=d.default,u.Client=n.default,l(Zn(),u),l(Lt(),u),l(Zo(),u);var p=Pr();Object.defineProperty(u,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Vc=pe(u=>{le(),ce(),ue();var e=u&&u.__createBinding||(Object.create?function(n,o,i,a){a===void 0&&(a=i);var c=Object.getOwnPropertyDescriptor(o,i);(!c||("get"in c?!o.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(n,a,c)}:function(n,o,i,a){a===void 0&&(a=i),n[a]=o[i]}),t=u&&u.__setModuleDefault||(Object.create?function(n,o){Object.defineProperty(n,"default",{enumerable:!0,value:o})}:function(n,o){n.default=o}),s=u&&u.__importStar||(function(){var n=function(o){return n=Object.getOwnPropertyNames||function(i){var a=[];for(var c in i)Object.prototype.hasOwnProperty.call(i,c)&&(a[a.length]=c);return a},n(o)};return function(o){if(o&&o.__esModule)return o;var i={};if(o!=null)for(var a=n(o),c=0;c<a.length;c++)a[c]!=="default"&&e(i,o,a[c]);return t(i,o),i}})(),l=u&&u.__exportStar||function(n,o){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&e(o,n,i)};Object.defineProperty(u,"__esModule",{value:!0});var r=s(mo());u.default=r,l(mo(),u)});const Kc=Vc();const Gc={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}/#"},Qc=300,Yc={templateId:"7",type:"link",isDeepLink:!0},Jc={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class rl{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...Gc,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,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},s={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(s.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((l,r)=>{this.client=Kc.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const n=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(n),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:n})}l()}),this.client.on("message",(n,o)=>{this.dispatchInbound(n,o)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",n=>{this.debugLog("ERROR",{message:n.message}),this.reconnectAttempt===0&&r(n)}),this.client.on("packetsend",n=>{(n.cmd==="subscribe"||n.cmd==="unsubscribe"||n.cmd==="pingreq")&&this.debugLog(n.cmd.toUpperCase(),{topic:n.topic,packetId:n.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const s={};for(const[l,r]of Object.entries(t))typeof r=="string"&&r.length>200?s[l]=`${r.slice(0,200)}…(${r.length})`:s[l]=r;console.info(`[tiledesk-mqtt] ${e}`,s)}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,s={}){if(!this.client)return;const l=this.buildOutgoingEnvelope(e,{text:t,type:"text",...s});this.publishEnvelope(e,l)}publishFileMessage(e,t){if(!this.client)return;const s={...Yc,...this.config.fileTemplate??{},...Xc(t)},l={metadata:{contentType:"300",templateId:s.templateId,payload:{...s.headerImgSrc?{headerImgSrc:s.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:s.type??"link",isDeepLink:s.isDeepLink??!0}}]},...t.metadata??{}}},r={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},n=this.buildOutgoingEnvelope(e,{text:JSON.stringify(l),type:"html",attributes:r,metadata:l.metadata});this.publishEnvelope(e,n)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,s=Qc){if(!this.client)return;const l=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(l,JSON.stringify({status:s}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const s=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,s)}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.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)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(s=>{this.client&&(this.client.subscribe(s,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(s))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const s=t.toString();let l=null;try{l=JSON.parse(s)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:s});return}if(!l)return;this.debugLog("RECV",{topic:e,sender:l.sender,type:l.type,contentType:l.metadata?.contentType,templateId:l.metadata?.templateId,messageId:l.message_id,text:typeof l.text=="string"?l.text:void 0});const r=e.match(this.inboundUpdateRegex);if(r){const a=r.groups?.conversationId??"",c=r.groups?.messageId??"",d=typeof l.status=="number"?l.status:Number(l.status??0),p={conversationId:a,messageId:c,status:d,raw:l};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(l,{topic:e,conversationId:a,messageId:c,kind:"update"}));return}const n=e.match(this.inboundRegex),o=n?.groups?.conversationId,i={topic:e,conversationId:o,messageId:typeof l.message_id=="string"?l.message_id:void 0,kind:n?"clientadded":"unknown"};this.messageHandlers.forEach(a=>a(l,i))}buildOutgoingEnvelope(e,t){const s={...Jc,...this.config.messageDefaults??{}},l=this.config.senderFullname??this.config.userName??this.config.userId,r=this.config.recipientFullnameResolver?.(e),n={projectId:this.config.projectId,...s.departmentId?{departmentId:s.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...s.channel?{channel:s.channel}:{},...s.requestChannel?{request_channel:s.requestChannel}:{},...s.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:l,senderFullname:l,recipient:e,...r?{recipient_fullname:r}:{},...s.channelType?{channel_type:s.channelType}:{},...s.medium?{medium:s.medium}:{},...s.platform?{platform:s.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:n}}publishEnvelope(e,t){if(!this.client)return;const s=this.renderOutboundTopic(e);this.client.publish(s,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:s,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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(l,r)=>s[r]??"")}buildTopicRegex(e,t){const s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(l,r)=>{const n={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(r))return`(?<${r}>[^/]+)`;const o=n[r];return o?o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${s}$`)}}function Xc(u){const e={};for(const[t,s]of Object.entries(u))s!==void 0&&(e[t]=s);return e}function nl(u,e){return(u.sender??"").toString()===e}function il(u,e){const t=(u.sender??"").toString(),s=e.systemSenders??["metadata","system"],l=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(l)?"assistant":s.includes(t)?"system":"agent":"system"}function rs(u){const e={raw:u},t=u.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 u.text=="string"&&u.text.trim().startsWith("{"))try{const s=JSON.parse(u.text);typeof s.message=="string"&&(e.innerMessage=s.message);const l=s.metadata;l&&typeof l=="object"&&(!e.contentType&&typeof l.contentType=="string"&&(e.contentType=l.contentType),!e.templateId&&typeof l.templateId=="string"&&(e.templateId=l.templateId),e.payload===void 0&&l.payload!==void 0&&(e.payload=l.payload))}catch{}return e}function sl(u){const e=rs(u);if(e.contentType!=="300")return null;const t=e.payload,s=t&&Array.isArray(t.elements)?t.elements:null;if(!s||s.length===0)return null;const l=s[0],r=l.action,n=r&&typeof r.url=="string"?r.url:void 0,o=typeof l.description=="string"?l.description:void 0,i=u.attributes,a=i&&typeof i.cloudFileId=="string"?i.cloudFileId:void 0;return!n&&!o?null:{fileName:o,fileUrl:n,cloudFileId:a,templateId:e.templateId}}function bo(u,e,t){const s=il(u,t),l=rs(u),r=sl(u);let n="";l.innerMessage?n=l.innerMessage:typeof u.text=="string"&&(u.text.trim().startsWith("{")?l.contentType!=="300"&&(n=u.text):n=u.text);const o=typeof u.message_id=="string"?u.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=typeof u.timestamp=="number"?new Date(u.timestamp).toISOString():new Date().toISOString(),a=s==="assistant"?"assistant":s==="agent"?"agent":s==="system"?"system":"user",c=typeof u.status=="number"?Zc(u.status):"delivered",d={id:o,externalId:o,conversationId:e,role:a,content:n,createdAt:i,status:c,metadata:{sender:u.sender,sender_fullname:u.sender_fullname??u.senderFullname,app_id:u.app_id,attributes:u.attributes}};return l.contentType&&(d.template={contentType:l.contentType,templateId:l.templateId,payload:l.payload}),r?.fileUrl&&(d.attachments=[{fileName:r.fileName??"file",fileUrl:r.fileUrl,cloudFileId:r.cloudFileId}]),{message:d,template:l}}function Zc(u){return u<0?"error":u>=250?"read":u>=150?"delivered":"sent"}class ol extends Wi{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 So(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Eo,this.conversationManager=new ko(e.conversationId),this.usesAikaara()&&(this.connection=new _o(e),this.connection.on("connection:state",s=>{this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)}),this.connection.on("error",s=>{this.emit("error",s),this.config.onError?.(s)})),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 rl({...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(s=>{const l=s?"connected":"disconnected";this.emit("connection:state",l),this.config.onConnectionStateChange?.(l)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((s,l)=>this.handleTiledeskMessage(s,l))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(s=>this.handleTiledeskStatusUpdate(s)))}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 s=await this.hydrateTiledeskHistory(t),l=this.config.tiledesk?.autoInitiateOnEmpty??!0;s==="empty"&&l&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let s;try{s=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(o){return this.config.onError?.(o instanceof Error?o:new Error(String(o))),"unknown"}if(!s.length)return"empty";const l=s.map(o=>bo(o,e,{userId:t}).message).sort((o,i)=>new Date(o.createdAt).getTime()-new Date(i.createdAt).getTime()),r=this.messageStore.messages,n=[...l,...r.filter(o=>!l.some(i=>i.externalId&&i.externalId===o.externalId))];return this.messageStore.setMessages(n),"has-history"}async sendMessage(e,t={}){const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const l=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",l),this.config.onMessage?.(l);const r={};if(t.attributes&&(r.attributes=t.attributes),t.metadata&&(r.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(s,e,r);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(s,e,r),this.usesAikaara()&&this.connection&&this.connection.sendMessage(s,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const l=await this.uploadAdapter.upload(e,{conversationId:s,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const r={fileName:l.fileName,fileUrl:l.url,cloudFileId:l.cloudFileId};this.tiledesk.publishFileMessage(s,r)}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,s){const l=this.conversationManager.conversationId;if(!l)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(l,e,t,s)}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 s=t.conversationId??this.conversationManager.conversationId;if(!s)return;const l=this.config.tiledeskIdentity?.userId??"",{message:r,template:n}=bo(e,s,{userId:l,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&r.role==="assistant")return;if(nl(e,l)){const a=this.messageStore.reconcileOptimistic(r);if(a){this.emit("message:updated",a);return}}const{message:o,deduped:i}=this.messageStore.upsertRemoteMessage(r);if(i?this.emit("message:updated",o):(this.emit("message:received",o),this.config.onMessage?.(o)),n.contentType){const a={messageId:o.id,conversationId:s,role:r.role==="tool"?"system":r.role,contentType:n.contentType,templateId:n.templateId,payload:n.payload,innerMessage:n.innerMessage,raw:e};this.config.onTemplateMessage?.(a)}}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{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const s=e.status;this.emit("status",s),this.config.onStatusChange?.(s),s==="processing"&&this.emit("typing:start",void 0);break}case"error":{const s=new Error(e.message||"Unknown error");this.emit("error",s),this.config.onError?.(s);break}case"message_start":{if(e.role==="assistant"){const s=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:s.id}),this.emit("typing:start",void 0)}break}case"message_update":{const s=e.delta||"",l=e.content||"";l?this.messageStore.updateStreaming(l):s&&this.messageStore.appendToStreaming(s);const r=this.messageStore.streamingContent;this.emit("stream:update",{delta:s,content:r}),this.config.onStreamUpdate?.(s,r);break}case"message_end":{const s=e.usage,l=this.messageStore.finalizeStreaming(s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0);this.emit("typing:stop",void 0),l&&(this.emit("stream:end",{messageId:l.id,usage:s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0}),this.emit("message:received",l),this.config.onMessage?.(l));break}case"message_queued":{const s=this.messageStore.messages.findLast(l=>l.status==="sending");s&&this.messageStore.confirmOptimistic(s.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}}}function Br(u,e){return u.replace(/\{(\w+)\}/g,(t,s)=>e[s]??"")}function eh(u,e){const t=e.split(".");let s=u;for(const l of t)if(s&&typeof s=="object"&&l in s)s=s[l];else return"";return typeof s=="string"?s:""}function al(u){const e=u.signedUrlPath??"data.s3SignedUrl";return{async upload(t,s){const l=t.name||`upload-${Date.now()}`,r={fileName:l,userId:s.userId,requestId:s.conversationId,conversationId:s.conversationId},n=u.authHeader?await u.authHeader():void 0,o={accept:"application/json",...u.extraHeaders??{},...n?{authorization:n}:{}},i=Br(u.signEndpoint.includes("{")?u.signEndpoint:`${u.signEndpoint}?fileName={fileName}`,r),a=await fetch(i,{method:u.signMethod??"GET",headers:o});if(!a.ok)throw new Error(`Sign request failed: ${a.status}`);const c=await a.json().catch(()=>({})),d=eh(c,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=u.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,u.s3HostRewrite):d,y=await fetch(p,{method:"PUT",headers:{"content-type":t.type||"application/octet-stream"},body:t});if(!y.ok){const m=await y.text().catch(()=>"");throw new Error(`S3 PUT failed: ${y.status} ${m.slice(0,200)}`)}if(u.registerEndpoint){const m=JSON.parse(Br(JSON.stringify(u.registerBody??{}),r)),b=await fetch(u.registerEndpoint,{method:"POST",headers:{...o,"content-type":"application/json"},body:JSON.stringify(m)});if(!b.ok){const S=await b.text().catch(()=>"");throw new Error(`Register failed: ${b.status} ${S.slice(0,200)}`)}}return{url:u.viewerTemplate?Br(u.viewerTemplate,r):d.split("?")[0],fileName:l,contentType:t.type,byteSize:t.size,meta:{requestId:s.conversationId}}}}}function ns(u){return{async upload(e,t){const s=new FormData,l=u.fieldName??"file";s.append(l,e,e.name);const r=typeof u.extraFields=="function"?u.extraFields(t):u.extraFields;if(r)for(const[p,y]of Object.entries(r))s.append(p,y);s.append("conversationId",t.conversationId),s.append("userId",t.userId),t.projectId&&s.append("projectId",t.projectId);const n=typeof u.headers=="function"?await u.headers():u.headers??{},o=await fetch(u.endpoint,{method:u.method??"POST",body:s,headers:n,credentials:u.credentials});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const i=await o.json().catch(()=>({}));if(u.parseResponse)return u.parseResponse(i,t);const a=i,c=a.url??a.fileUrl??a.publicUrl,d=a.fileName??a.name??e.name;if(!c)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:c,fileName:d,cloudFileId:typeof a.cloudFileId=="string"?a.cloudFileId:void 0,relativePath:typeof a.path=="string"?a.path:void 0,contentType:typeof a.contentType=="string"?a.contentType:void 0,byteSize:typeof a.byteSize=="number"?a.byteSize:void 0,meta:a}}}}const th="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ll(u){const e=u.apiBase.replace(/\/$/,""),t=u.pageSize??200,s=u.pathTemplate??th;return{async fetchMessages(l,r){const n=s.replace("{userId}",encodeURIComponent(r.userId)).replace("{conversationId}",encodeURIComponent(l)).replace("{appId}",encodeURIComponent(r.appId??"tilechat")).replace("{projectId}",encodeURIComponent(r.projectId??"")).replace("{pageSize}",String(t)),o=n.startsWith("http")?n:`${e}${n.startsWith("/")?n:`/${n}`}`,i={accept:"application/json","content-type":"application/json",...u.extraHeaders??{}};if(u.getToken){const p=await u.getToken();p&&(i.authorization=p)}const a=await fetch(o,{method:"GET",headers:i,credentials:"include"}),c=await a.json().catch(()=>null);if(u.parseResponse&&c)return u.parseResponse(c);const d=c;if(d&&Array.isArray(d.result))return d.result;if(!a.ok)throw new Error(`History fetch failed: ${a.status} ${a.statusText}`);return[]}}}class rh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,s){this.client=new ol(e,{uploadAdapter:s?.uploadAdapter,historyAdapter:s?.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),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.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)}),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)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const s=this.client.config.templateActionAttributes??{},l=t.attributes?.action??{},r={...t.attributes,action:{...s,...l}};this.handleSend(t.text,r)})}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,s){this.client.sendUserEvent(e,t,s)}getClient(){return this.client}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 ul 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,s){t!==s&&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||Bl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||ss,position:this.getAttribute("position")||this._config.position||Ul,width:Number(this.getAttribute("width"))||this._config.width||Rl,height:Number(this.getAttribute("height"))||this._config.height||jl,fontFamily:this._config.fontFamily||Ll,borderRadius:this._config.borderRadius??Nl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||os,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,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Dl,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}}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",s=`
8
+ `)&&(e=e.replace(Ga,"%0A")),e.includes("\r")&&(e=e.replace(Qa,"%0D")),e.includes(" ")&&(e=e.replace(Ya,"%09")),s.pathname=e,s}var ja,yr,Ri,vr,wr,ji,_r,Ni,Sr,Li,Er,Ui,kr,Bi,xr,Di,gt,Fi,Fe,co,Na,La,Ua,Ba,Da,Fa,Wa,$a,qa,Ha,Ir,za,Va,Ka,Ga,Qa,Ya,$c=He(()=>{le(),ce(),ue(),sc(),_c(),Rc(),Oa(),ja=Object.freeze(Object.create(null)),yr={},Ri=!1,vr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,wr={},ji=!1,_r={},Ni=!1,Sr={},Li=!1,Er={},Ui=!1,kr={},Bi=!1,xr={},Di=!1,gt={},Fi=!1,Fe=Dc(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,co=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=Ra,Fe.fileURLToPath=Ma,Na=Fe.Url,La=Fe.format,Ua=Fe.resolve,Ba=Fe.resolveObject,Da=Fe.parse,Fa=Fe.URL,Wa=92,$a=47,qa=97,Ha=122,Ir=co==="win32",za=/\//g,Va=/%/g,Ka=/\\/g,Ga=/\n/g,Qa=/\r/g,Ya=/\t/g}),qc=pe((u,e)=>{le(),ce(),ue(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),es=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0}),u.BufferedDuplex=void 0,u.writev=s;var e=At(),t=(Le(),Ce(Ne));function s(r,n){let o=new Array(r.length);for(let i=0;i<r.length;i++)typeof r[i].chunk=="string"?o[i]=t.Buffer.from(r[i].chunk,"utf8"):o[i]=r[i].chunk;this._write(t.Buffer.concat(o),"binary",n)}var l=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(r,n,o){super({objectMode:!0}),this.proxy=n,this.socket=o,this.writeQueue=[],r.objectMode||(this._writev=s.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",i=>{!this.destroyed&&this.readable&&this.push(i)})}_read(r){this.proxy.read(r)}_write(r,n,o){this.isSocketOpen?this.writeToProxy(r,n,o):this.writeQueue.push({chunk:r,encoding:n,cb:o})}_final(r){this.writeQueue=[],this.proxy.end(r)}_destroy(r,n){this.writeQueue=[],this.proxy.destroy(),n(r)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(r,n,o){this.proxy.write(r,n)===!1?this.proxy.once("drain",o):o()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:r,encoding:n,cb:o}=this.writeQueue.shift();this.writeToProxy(r,n,o)}}};u.BufferedDuplex=l}),er=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(S){return S&&S.__esModule?S:{default:S}};Object.defineProperty(u,"__esModule",{value:!0}),u.streamBuilder=u.browserStreamBuilder=void 0;var t=(Le(),Ce(Ne)),s=e(qc()),l=e(at()),r=At(),n=e(Rr()),o=es(),i=(0,l.default)("mqttjs:ws"),a=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function c(S,g){let _=`${S.protocol}://${S.hostname}:${S.port}${S.path}`;return typeof S.transformWsUrl=="function"&&(_=S.transformWsUrl(_,S,g)),_}function d(S){let g=S;return S.port||(S.protocol==="wss"?g.port=443:g.port=80),S.path||(g.path="/"),S.wsOptions||(g.wsOptions={}),!n.default&&!S.forceNativeWebSocket&&S.protocol==="wss"&&a.forEach(_=>{Object.prototype.hasOwnProperty.call(S,_)&&!Object.prototype.hasOwnProperty.call(S.wsOptions,_)&&(g.wsOptions[_]=S[_])}),g}function p(S){let g=d(S);if(g.hostname||(g.hostname=g.host),!g.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let _=new URL(document.URL);g.hostname=_.hostname,g.port||(g.port=Number(_.port))}return g.objectMode===void 0&&(g.objectMode=!(g.binary===!0||g.binary===void 0)),g}function y(S,g,_){i("createWebSocket"),i(`protocol: ${_.protocolId} ${_.protocolVersion}`);let x=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";i(`creating new Websocket for url: ${g} and protocol: ${x}`);let v;return _.createWebsocket?v=_.createWebsocket(g,[x],_):v=new s.default(g,[x],_.wsOptions),v}function f(S,g){let _=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt",x=c(g,S),v;return g.createWebsocket?v=g.createWebsocket(x,[_],g):v=new WebSocket(x,[_]),v.binaryType="arraybuffer",v}var m=(S,g)=>{i("streamBuilder");let _=d(g);_.hostname=_.hostname||_.host||"localhost";let x=c(_,S),v=y(S,x,_),k=s.default.createWebSocketStream(v,_.wsOptions);return k.url=x,v.on("close",()=>{k.destroy()}),k};u.streamBuilder=m;var b=(S,g)=>{i("browserStreamBuilder");let _,x=p(g).browserBufferSize||1024*512,v=g.browserBufferTimeout||1e3,k=!g.objectMode,E=f(S,g),I=C(g,L,ae);g.objectMode||(I._writev=o.writev.bind(I)),I.on("close",()=>{E.close()});let M=typeof E.addEventListener<"u";E.readyState===E.OPEN?(_=I,_.socket=E):(_=new o.BufferedDuplex(g,I,E),M?E.addEventListener("open",B):E.onopen=B),M?(E.addEventListener("close",T),E.addEventListener("error",$),E.addEventListener("message",D)):(E.onclose=T,E.onerror=$,E.onmessage=D);function C(Q,V,re){let F=new r.Transform({objectMode:Q.objectMode});return F._write=V,F._flush=re,F}function B(){i("WebSocket onOpen"),_ instanceof o.BufferedDuplex&&_.socketReady()}function T(Q){i("WebSocket onClose",Q),_.end(),_.destroy()}function $(Q){i("WebSocket onError",Q);let V=new Error("WebSocket error");V.event=Q,_.destroy(V)}async function D(Q){if(!I||!I.readable||!I.writable)return;let{data:V}=Q;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 L(Q,V,re){if(E.bufferedAmount>x){setTimeout(L,v,Q,V,re);return}k&&typeof Q=="string"&&(Q=t.Buffer.from(Q,"utf8"));try{E.send(Q)}catch(F){return re(F)}re()}function ae(Q){E.close(),Q()}return _};u.browserStreamBuilder=b}),ts={};jt(ts,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>Ja,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var Ja,Xa=He(()=>{le(),ce(),ue(),Ja={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),Za=pe((u,e)=>{le(),ce(),ue(),e.exports={}}),ho=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(u,"__esModule",{value:!0});var t=e((Xa(),Ce(ts))),s=e(at()),l=e(Za()),r=(0,s.default)("mqttjs:tcp"),n=(o,i)=>{if(i.port=i.port||1883,i.hostname=i.hostname||i.host||"localhost",i.socksProxy)return(0,l.default)(i.hostname,i.port,i.socksProxy,{timeout:i.socksTimeout});let{port:a,path:c}=i,d=i.hostname;return r("port %d and host %s",a,d),t.default.createConnection({port:a,host:d,path:c})};u.default=n}),el={};jt(el,{default:()=>tl});var tl,Hc=He(()=>{le(),ce(),ue(),tl={}}),fo=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(u,"__esModule",{value:!0});var t=(Hc(),Ce(el)),s=e((Xa(),Ce(ts))),l=e(at()),r=e(Za()),n=(0,l.default)("mqttjs:tls");function o(a){let{host:c,port:d,socksProxy:p,...y}=a;if(p!==void 0){let f=(0,r.default)(c,d,p,{timeout:a.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(a)}var i=(a,c)=>{c.port=c.port||8883,c.host=c.hostname||c.host||"localhost",s.default.isIP(c.host)===0&&(c.servername=c.host),c.rejectUnauthorized=c.rejectUnauthorized!==!1,delete c.path,n("port %d host %s rejectUnauthorized %b",c.port,c.host,c.rejectUnauthorized);let d=o(c);d.on("secureConnect",()=>{c.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){c.rejectUnauthorized&&a.emit("error",y),d.end()}return d.on("error",p),d};u.default=i}),po=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0});var e=(Le(),Ce(Ne)),t=At(),s=es(),l,r,n;function o(){let p=new t.Transform;return p._write=(y,f,m)=>{l.send({data:y.buffer,success(){m()},fail(b){m(new Error(b))}})},p._flush=y=>{l.close({success(){y()}})},p}function i(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function a(p,y){let f=p.protocol==="wxs"?"wss":"ws",m=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(m=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(m=p.transformWsUrl(m,p,y)),m}function c(){l.onOpen(()=>{n.socketReady()}),l.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),r.push(y)}),l.onClose(()=>{n.emit("close"),n.end(),n.destroy()}),l.onError(p=>{let y=new Error(p.errMsg);n.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";i(y);let m=a(y,p);l=wx.connectSocket({url:m,protocols:[f]}),r=o(),n=new s.BufferedDuplex(y,r,l),n._destroy=(S,g)=>{l.close({success(){g&&g(S)}})};let b=n.destroy;return n.destroy=(S,g)=>(n.destroy=b,setTimeout(()=>{l.close({fail(){n._destroy(S,g)}})},0),n),c(),n};u.default=d}),go=pe(u=>{le(),ce(),ue(),Object.defineProperty(u,"__esModule",{value:!0});var e=(Le(),Ce(Ne)),t=At(),s=es(),l,r,n,o=!1;function i(){let y=new t.Transform;return y._write=(f,m,b)=>{l.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{l.closeSocket({success(){f()}})},y}function a(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function c(y,f){let m=y.protocol==="alis"?"wss":"ws",b=`${m}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${m}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){o||(o=!0,l.onSocketOpen(()=>{n.socketReady()}),l.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");r.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){r.push(e.Buffer.from(f.result));return}r.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),l.onSocketClose(()=>{n.end(),n.destroy()}),l.onSocketError(y=>{n.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let m=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";a(f);let b=c(f,y);return l=f.my,l.connectSocket({url:b,protocols:m}),r=i(),n=new s.BufferedDuplex(f,r,l),d(),n};u.default=p}),zc=pe(u=>{le(),ce(),ue();var e=u&&u.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(u,"__esModule",{value:!0}),u.connectAsync=c;var t=e(at()),s=e(($c(),Ce(Ca))),l=e(Zn()),r=e(Rr());typeof Pe?.nextTick!="function"&&(Pe.nextTick=setImmediate);var n=(0,t.default)("mqttjs"),o=null;function i(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function a(d,p){if(n("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let m=s.default.parse(d,!0),b={};if(m.port!=null&&(b.port=Number(m.port)),b.host=m.hostname,b.query=m.query,b.auth=m.auth,b.protocol=m.protocol,b.path=m.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,i(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),r.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Pe<"u"&&(p.socksProxy=Pe.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(o||(o={},!r.default&&!p.forceNativeWebSocket?(o.ws=er().streamBuilder,o.wss=er().streamBuilder,o.mqtt=ho().default,o.tcp=ho().default,o.ssl=fo().default,o.tls=o.ssl,o.mqtts=fo().default):(o.ws=er().browserStreamBuilder,o.wss=er().browserStreamBuilder,o.wx=po().default,o.wxs=po().default,o.ali=go().default,o.alis=go().default)),!o[p.protocol]){let m=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,S)=>m&&S%2===0?!1:typeof o[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(m){return p.servers&&((!m._reconnectCount||m._reconnectCount===p.servers.length)&&(m._reconnectCount=0),p.host=p.servers[m._reconnectCount].host,p.port=p.servers[m._reconnectCount].port,p.protocol=p.servers[m._reconnectCount].protocol?p.servers[m._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,m._reconnectCount++),n("calling streambuilder for",p.protocol),o[p.protocol](m,p)}let f=new l.default(y,p);return f.on("error",()=>{}),f}function c(d,p,y=!0){return new Promise((f,m)=>{let b=a(d,p),S={connect:_=>{g(),f(b)},end:()=>{g(),f(b)},error:_=>{g(),b.end(),m(_)}};y===!1&&(S.close=()=>{S.error(new Error("Couldn't connect to server"))});function g(){Object.keys(S).forEach(_=>{b.off(_,S[_])})}Object.keys(S).forEach(_=>{b.on(_,S[_])})})}u.default=a}),mo=pe(u=>{le(),ce(),ue();var e=u&&u.__createBinding||(Object.create?function(y,f,m,b){b===void 0&&(b=m);var S=Object.getOwnPropertyDescriptor(f,m);(!S||("get"in S?!f.__esModule:S.writable||S.configurable))&&(S={enumerable:!0,get:function(){return f[m]}}),Object.defineProperty(y,b,S)}:function(y,f,m,b){b===void 0&&(b=m),y[b]=f[m]}),t=u&&u.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),s=u&&u.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(m){var b=[];for(var S in m)Object.prototype.hasOwnProperty.call(m,S)&&(b[b.length]=S);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var m={};if(f!=null)for(var b=y(f),S=0;S<b.length;S++)b[S]!=="default"&&e(m,f,b[S]);return t(m,f),m}})(),l=u&&u.__exportStar||function(y,f){for(var m in y)m!=="default"&&!Object.prototype.hasOwnProperty.call(f,m)&&e(f,y,m)},r=u&&u.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(u,"__esModule",{value:!0}),u.ReasonCodes=u.KeepaliveManager=u.UniqueMessageIdProvider=u.DefaultMessageIdProvider=u.Store=u.MqttClient=u.connectAsync=u.connect=u.Client=void 0;var n=r(Zn());u.MqttClient=n.default;var o=r(ba());u.DefaultMessageIdProvider=o.default;var i=r(nc());u.UniqueMessageIdProvider=i.default;var a=r(ea());u.Store=a.default;var c=s(zc());u.connect=c.default,Object.defineProperty(u,"connectAsync",{enumerable:!0,get:function(){return c.connectAsync}});var d=r(ka());u.KeepaliveManager=d.default,u.Client=n.default,l(Zn(),u),l(Lt(),u),l(Zo(),u);var p=Pr();Object.defineProperty(u,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),Vc=pe(u=>{le(),ce(),ue();var e=u&&u.__createBinding||(Object.create?function(n,o,i,a){a===void 0&&(a=i);var c=Object.getOwnPropertyDescriptor(o,i);(!c||("get"in c?!o.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(n,a,c)}:function(n,o,i,a){a===void 0&&(a=i),n[a]=o[i]}),t=u&&u.__setModuleDefault||(Object.create?function(n,o){Object.defineProperty(n,"default",{enumerable:!0,value:o})}:function(n,o){n.default=o}),s=u&&u.__importStar||(function(){var n=function(o){return n=Object.getOwnPropertyNames||function(i){var a=[];for(var c in i)Object.prototype.hasOwnProperty.call(i,c)&&(a[a.length]=c);return a},n(o)};return function(o){if(o&&o.__esModule)return o;var i={};if(o!=null)for(var a=n(o),c=0;c<a.length;c++)a[c]!=="default"&&e(i,o,a[c]);return t(i,o),i}})(),l=u&&u.__exportStar||function(n,o){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&e(o,n,i)};Object.defineProperty(u,"__esModule",{value:!0});var r=s(mo());u.default=r,l(mo(),u)});const Kc=Vc();const Gc={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}/#"},Qc=300,Yc={templateId:"7",type:"link",isDeepLink:!0},Jc={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class rl{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...Gc,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,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},s={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(s.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((l,r)=>{this.client=Kc.connect(this.config.mqttEndpoint,s),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const n=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(n),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:n})}l()}),this.client.on("message",(n,o)=>{this.dispatchInbound(n,o)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",n=>{this.debugLog("ERROR",{message:n.message}),this.reconnectAttempt===0&&r(n)}),this.client.on("packetsend",n=>{(n.cmd==="subscribe"||n.cmd==="unsubscribe"||n.cmd==="pingreq")&&this.debugLog(n.cmd.toUpperCase(),{topic:n.topic,packetId:n.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const s={};for(const[l,r]of Object.entries(t))typeof r=="string"&&r.length>200?s[l]=`${r.slice(0,200)}…(${r.length})`:s[l]=r;console.info(`[tiledesk-mqtt] ${e}`,s)}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,s={}){if(!this.client)return;const l=this.buildOutgoingEnvelope(e,{text:t,type:"text",...s});this.publishEnvelope(e,l)}publishFileMessage(e,t){if(!this.client)return;const s={...Yc,...this.config.fileTemplate??{},...Xc(t)},l={metadata:{contentType:"300",templateId:s.templateId,payload:{...s.headerImgSrc?{headerImgSrc:s.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:s.type??"link",isDeepLink:s.isDeepLink??!0}}]},...t.metadata??{}}},r={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},n=this.buildOutgoingEnvelope(e,{text:JSON.stringify(l),type:"html",attributes:r,metadata:l.metadata});this.publishEnvelope(e,n)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,s=Qc){if(!this.client)return;const l=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(l,JSON.stringify({status:s}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const s=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,s)}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.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)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(s=>{this.client&&(this.client.subscribe(s,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(s))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const s=t.toString();let l=null;try{l=JSON.parse(s)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:s});return}if(!l)return;this.debugLog("RECV",{topic:e,sender:l.sender,type:l.type,contentType:l.metadata?.contentType,templateId:l.metadata?.templateId,messageId:l.message_id,text:typeof l.text=="string"?l.text:void 0});const r=e.match(this.inboundUpdateRegex);if(r){const a=r.groups?.conversationId??"",c=r.groups?.messageId??"",d=typeof l.status=="number"?l.status:Number(l.status??0),p={conversationId:a,messageId:c,status:d,raw:l};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(l,{topic:e,conversationId:a,messageId:c,kind:"update"}));return}const n=e.match(this.inboundRegex),o=n?.groups?.conversationId,i={topic:e,conversationId:o,messageId:typeof l.message_id=="string"?l.message_id:void 0,kind:n?"clientadded":"unknown"};this.messageHandlers.forEach(a=>a(l,i))}buildOutgoingEnvelope(e,t){const s={...Jc,...this.config.messageDefaults??{}},l=this.config.senderFullname??this.config.userName??this.config.userId,r=this.config.recipientFullnameResolver?.(e),n={projectId:this.config.projectId,...s.departmentId?{departmentId:s.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...s.channel?{channel:s.channel}:{},...s.requestChannel?{request_channel:s.requestChannel}:{},...s.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:l,senderFullname:l,recipient:e,...r?{recipient_fullname:r}:{},...s.channelType?{channel_type:s.channelType}:{},...s.medium?{medium:s.medium}:{},...s.platform?{platform:s.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:n}}publishEnvelope(e,t){if(!this.client)return;const s=this.renderOutboundTopic(e);this.client.publish(s,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:s,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 s={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(l,r)=>s[r]??"")}buildTopicRegex(e,t){const s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(l,r)=>{const n={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(r))return`(?<${r}>[^/]+)`;const o=n[r];return o?o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${s}$`)}}function Xc(u){const e={};for(const[t,s]of Object.entries(u))s!==void 0&&(e[t]=s);return e}function nl(u,e){return(u.sender??"").toString()===e}function il(u,e){const t=(u.sender??"").toString(),s=e.systemSenders??["metadata","system"],l=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(l)?"assistant":s.includes(t)?"system":"agent":"system"}function rs(u){const e={raw:u},t=u.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 u.text=="string"&&u.text.trim().startsWith("{"))try{const s=JSON.parse(u.text);typeof s.message=="string"&&(e.innerMessage=s.message);const l=s.metadata;l&&typeof l=="object"&&(!e.contentType&&typeof l.contentType=="string"&&(e.contentType=l.contentType),!e.templateId&&typeof l.templateId=="string"&&(e.templateId=l.templateId),e.payload===void 0&&l.payload!==void 0&&(e.payload=l.payload))}catch{}return e}function sl(u){const e=rs(u);if(e.contentType!=="300")return null;const t=e.payload,s=t&&Array.isArray(t.elements)?t.elements:null;if(!s||s.length===0)return null;const l=s[0],r=l.action,n=r&&typeof r.url=="string"?r.url:void 0,o=typeof l.description=="string"?l.description:void 0,i=u.attributes,a=i&&typeof i.cloudFileId=="string"?i.cloudFileId:void 0;return!n&&!o?null:{fileName:o,fileUrl:n,cloudFileId:a,templateId:e.templateId}}function bo(u,e,t){const s=il(u,t),l=rs(u),r=sl(u);let n="";l.innerMessage?n=l.innerMessage:typeof u.text=="string"&&(u.text.trim().startsWith("{")?l.contentType!=="300"&&(n=u.text):n=u.text);const o=typeof u.message_id=="string"?u.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,i=typeof u.timestamp=="number"?new Date(u.timestamp).toISOString():new Date().toISOString(),a=s==="assistant"?"assistant":s==="agent"?"agent":s==="system"?"system":"user",c=typeof u.status=="number"?Zc(u.status):"delivered",d={id:o,externalId:o,conversationId:e,role:a,content:n,createdAt:i,status:c,metadata:{sender:u.sender,sender_fullname:u.sender_fullname??u.senderFullname,app_id:u.app_id,attributes:u.attributes}};return l.contentType&&(d.template={contentType:l.contentType,templateId:l.templateId,payload:l.payload}),r?.fileUrl&&(d.attachments=[{fileName:r.fileName??"file",fileUrl:r.fileUrl,cloudFileId:r.cloudFileId}]),{message:d,template:l}}function Zc(u){return u<0?"error":u>=250?"read":u>=150?"delivered":"sent"}class ol extends Wi{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 So(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Eo,this.conversationManager=new ko(e.conversationId),this.usesAikaara()&&(this.connection=new _o(e),this.connection.on("connection:state",s=>{this.emit("connection:state",s),this.config.onConnectionStateChange?.(s)}),this.connection.on("error",s=>{this.emit("error",s),this.config.onError?.(s)})),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 rl({...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(s=>{const l=s?"connected":"disconnected";this.emit("connection:state",l),this.config.onConnectionStateChange?.(l)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((s,l)=>this.handleTiledeskMessage(s,l))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(s=>this.handleTiledeskStatusUpdate(s)))}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 s=await this.hydrateTiledeskHistory(t),l=this.config.tiledesk?.autoInitiateOnEmpty??!0;s==="empty"&&l&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let s;try{s=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(o){return this.config.onError?.(o instanceof Error?o:new Error(String(o))),"unknown"}if(!s.length)return"empty";const l=s.map(o=>bo(o,e,{userId:t}).message).sort((o,i)=>new Date(o.createdAt).getTime()-new Date(i.createdAt).getTime()),r=this.messageStore.messages,n=[...l,...r.filter(o=>!l.some(i=>i.externalId&&i.externalId===o.externalId))];return this.messageStore.setMessages(n),"has-history"}async sendMessage(e,t={}){const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const l=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",l),this.config.onMessage?.(l);const r={};if(t.attributes&&(r.attributes=t.attributes),t.metadata&&(r.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(s,e,r);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(s,e,r),this.usesAikaara()&&this.connection&&this.connection.sendMessage(s,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const l=await this.uploadAdapter.upload(e,{conversationId:s,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const r={fileName:l.fileName,fileUrl:l.url,cloudFileId:l.cloudFileId};this.tiledesk.publishFileMessage(s,r)}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,s){const l=this.conversationManager.conversationId;if(!l)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(l,e,t,s)}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 s=t.conversationId??this.conversationManager.conversationId;if(!s)return;const l=this.config.tiledeskIdentity?.userId??"",{message:r,template:n}=bo(e,s,{userId:l,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&r.role==="assistant")return;if(nl(e,l)){const a=this.messageStore.reconcileOptimistic(r);if(a){this.emit("message:updated",a);return}}const{message:o,deduped:i}=this.messageStore.upsertRemoteMessage(r);if(i?this.emit("message:updated",o):(this.emit("message:received",o),this.config.onMessage?.(o)),n.contentType){const a={messageId:o.id,conversationId:s,role:r.role==="tool"?"system":r.role,contentType:n.contentType,templateId:n.templateId,payload:n.payload,innerMessage:n.innerMessage,raw:e};this.config.onTemplateMessage?.(a)}}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{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const s=e.status;this.emit("status",s),this.config.onStatusChange?.(s),s==="processing"&&this.emit("typing:start",void 0);break}case"error":{const s=new Error(e.message||"Unknown error");this.emit("error",s),this.config.onError?.(s);break}case"message_start":{if(e.role==="assistant"){const s=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:s.id}),this.emit("typing:start",void 0)}break}case"message_update":{const s=e.delta||"",l=e.content||"";l?this.messageStore.updateStreaming(l):s&&this.messageStore.appendToStreaming(s);const r=this.messageStore.streamingContent;this.emit("stream:update",{delta:s,content:r}),this.config.onStreamUpdate?.(s,r);break}case"message_end":{const s=e.usage,l=this.messageStore.finalizeStreaming(s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0);this.emit("typing:stop",void 0),l&&(this.emit("stream:end",{messageId:l.id,usage:s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0}),this.emit("message:received",l),this.config.onMessage?.(l));break}case"message_queued":{const s=this.messageStore.messages.findLast(l=>l.status==="sending");s&&this.messageStore.confirmOptimistic(s.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}}}function Br(u,e){return u.replace(/\{(\w+)\}/g,(t,s)=>e[s]??"")}function eh(u,e){const t=e.split(".");let s=u;for(const l of t)if(s&&typeof s=="object"&&l in s)s=s[l];else return"";return typeof s=="string"?s:""}function al(u){const e=u.signedUrlPath??"data.s3SignedUrl";return{async upload(t,s){const l=t.name||`upload-${Date.now()}`,r={fileName:l,userId:s.userId,requestId:s.conversationId,conversationId:s.conversationId},n=u.authHeader?await u.authHeader():void 0,o={accept:"application/json",...u.extraHeaders??{},...n?{authorization:n}:{}},i=Br(u.signEndpoint.includes("{")?u.signEndpoint:`${u.signEndpoint}?fileName={fileName}`,r),a=await fetch(i,{method:u.signMethod??"GET",headers:o});if(!a.ok)throw new Error(`Sign request failed: ${a.status}`);const c=await a.json().catch(()=>({})),d=eh(c,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=u.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,u.s3HostRewrite):d,y=await fetch(p,{method:"PUT",headers:{"content-type":t.type||"application/octet-stream"},body:t});if(!y.ok){const m=await y.text().catch(()=>"");throw new Error(`S3 PUT failed: ${y.status} ${m.slice(0,200)}`)}if(u.registerEndpoint){const m=JSON.parse(Br(JSON.stringify(u.registerBody??{}),r)),b=await fetch(u.registerEndpoint,{method:"POST",headers:{...o,"content-type":"application/json"},body:JSON.stringify(m)});if(!b.ok){const S=await b.text().catch(()=>"");throw new Error(`Register failed: ${b.status} ${S.slice(0,200)}`)}}return{url:u.viewerTemplate?Br(u.viewerTemplate,r):d.split("?")[0],fileName:l,contentType:t.type,byteSize:t.size,meta:{requestId:s.conversationId}}}}}function ns(u){return{async upload(e,t){const s=new FormData,l=u.fieldName??"file";s.append(l,e,e.name);const r=typeof u.extraFields=="function"?u.extraFields(t):u.extraFields;if(r)for(const[p,y]of Object.entries(r))s.append(p,y);s.append("conversationId",t.conversationId),s.append("userId",t.userId),t.projectId&&s.append("projectId",t.projectId);const n=typeof u.headers=="function"?await u.headers():u.headers??{},o=await fetch(u.endpoint,{method:u.method??"POST",body:s,headers:n,credentials:u.credentials});if(!o.ok)throw new Error(`Upload failed: ${o.status} ${o.statusText}`);const i=await o.json().catch(()=>({}));if(u.parseResponse)return u.parseResponse(i,t);const a=i,c=a.url??a.fileUrl??a.publicUrl,d=a.fileName??a.name??e.name;if(!c)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:c,fileName:d,cloudFileId:typeof a.cloudFileId=="string"?a.cloudFileId:void 0,relativePath:typeof a.path=="string"?a.path:void 0,contentType:typeof a.contentType=="string"?a.contentType:void 0,byteSize:typeof a.byteSize=="number"?a.byteSize:void 0,meta:a}}}}const th="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ll(u){const e=u.apiBase.replace(/\/$/,""),t=u.pageSize??200,s=u.pathTemplate??th;return{async fetchMessages(l,r){const n=s.replace("{userId}",encodeURIComponent(r.userId)).replace("{conversationId}",encodeURIComponent(l)).replace("{appId}",encodeURIComponent(r.appId??"tilechat")).replace("{projectId}",encodeURIComponent(r.projectId??"")).replace("{pageSize}",String(t)),o=n.startsWith("http")?n:`${e}${n.startsWith("/")?n:`/${n}`}`,i={accept:"application/json","content-type":"application/json",...u.extraHeaders??{}};if(u.getToken){const p=await u.getToken();p&&(i.authorization=p)}const a=await fetch(o,{method:"GET",headers:i}),c=await a.json().catch(()=>null);if(u.parseResponse&&c)return u.parseResponse(c);const d=c;if(d&&Array.isArray(d.result))return d.result;if(!a.ok)throw new Error(`History fetch failed: ${a.status} ${a.statusText}`);return[]}}}class rh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,s){this.client=new ol(e,{uploadAdapter:s?.uploadAdapter,historyAdapter:s?.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),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.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)}),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)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const s=this.client.config.templateActionAttributes??{},l=t.attributes?.action??{},r={...t.attributes,action:{...s,...l}};this.handleSend(t.text,r)})}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,s){this.client.sendUserEvent(e,t,s)}getClient(){return this.client}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 ul 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,s){t!==s&&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||Bl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||ss,position:this.getAttribute("position")||this._config.position||Ul,width:Number(this.getAttribute("width"))||this._config.width||Rl,height:Number(this.getAttribute("height"))||this._config.height||jl,fontFamily:this._config.fontFamily||Ll,borderRadius:this._config.borderRadius??Nl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||os,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,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Dl,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}}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",s=`
9
9
  font-family: var(--aikaara-font);
10
10
  position: fixed;
11
11
  z-index: 9999;
package/dist/headless.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./MountTenant-Pm0OS72h.cjs");class s extends i.EventEmitter{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)})}}exports.ActionCableClient=i.ActionCableClient;exports.AikaaraChatClient=i.AikaaraChatClient;exports.ApiClient=i.ApiClient;exports.ChannelSubscription=i.ChannelSubscription;exports.ConnectionManager=i.ConnectionManager;exports.ConversationManager=i.ConversationManager;exports.EventEmitter=i.EventEmitter;exports.MessageStore=i.MessageStore;exports.SessionAuthAdapter=i.SessionAuthAdapter;exports.TiledeskTransport=i.TiledeskTransport;exports.clearPersistedConversationId=i.clearPersistedConversationId;exports.createFetchUploadAdapter=i.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=i.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=i.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=i.extractTiledeskFileEnvelope;exports.inferTiledeskRole=i.inferTiledeskRole;exports.isTiledeskSelfEcho=i.isTiledeskSelfEcho;exports.mountFromSlug=i.mountFromSlug;exports.mountTenantWidget=i.mount;exports.parseTiledeskTemplate=i.parseTiledeskTemplate;exports.FormBridge=s;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./MountTenant-C_HFZNbx.cjs");class s extends i.EventEmitter{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)})}}exports.ActionCableClient=i.ActionCableClient;exports.AikaaraChatClient=i.AikaaraChatClient;exports.ApiClient=i.ApiClient;exports.ChannelSubscription=i.ChannelSubscription;exports.ConnectionManager=i.ConnectionManager;exports.ConversationManager=i.ConversationManager;exports.EventEmitter=i.EventEmitter;exports.MessageStore=i.MessageStore;exports.SessionAuthAdapter=i.SessionAuthAdapter;exports.TiledeskTransport=i.TiledeskTransport;exports.clearPersistedConversationId=i.clearPersistedConversationId;exports.createFetchUploadAdapter=i.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=i.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=i.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=i.extractTiledeskFileEnvelope;exports.inferTiledeskRole=i.inferTiledeskRole;exports.isTiledeskSelfEcho=i.isTiledeskSelfEcho;exports.mountFromSlug=i.mountFromSlug;exports.mountTenantWidget=i.mount;exports.parseTiledeskTemplate=i.parseTiledeskTemplate;exports.FormBridge=s;
package/dist/headless.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { E as s } from "./MountTenant-CUfrArN1.mjs";
2
- import { A as p, b as g, k as l, C as h, l as y, m as c, M as u, S as m, T as f, n as T, o as S, p as _, q as v, s as E, t as C, u as F, v as A, w as k, x as I } from "./MountTenant-CUfrArN1.mjs";
1
+ import { E as s } from "./MountTenant-CZa8dgKD.mjs";
2
+ import { A as p, b as g, k as l, C as h, l as y, m as c, M as u, S as m, T as f, n as T, o as S, p as _, q as v, s as E, t as C, u as F, v as A, w as k, x as I } from "./MountTenant-CZa8dgKD.mjs";
3
3
  class a extends s {
4
4
  registration = null;
5
5
  pendingEdits = [];
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-Pm0OS72h.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[n,o]of Object.entries(i)){const r=a[n];r!=null&&t.setAttribute(o,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-C_HFZNbx.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[n,o]of Object.entries(i)){const r=a[n];r!=null&&t.setAttribute(o,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { r as o } from "./MountTenant-CUfrArN1.mjs";
2
- import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as b, h as f, i as T, j as v, k as S, C as w, l as y, m as M, E, M as x, S as B, T as F, n as U, o as I, p as j, q, s as H, t as P, u as W, v as K, w as L, x as O } from "./MountTenant-CUfrArN1.mjs";
1
+ import { r as o } from "./MountTenant-CZa8dgKD.mjs";
2
+ import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as b, h as f, i as T, j as v, k as S, C as w, l as y, m as M, E, M as x, S as B, T as F, n as U, o as I, p as j, q, s as H, t as P, u as W, v as K, w as L, x as O } from "./MountTenant-CZa8dgKD.mjs";
3
3
  import { FormBridge as z } from "./headless.mjs";
4
4
  function l(e) {
5
5
  o();
package/dist/ui.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-Pm0OS72h.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-C_HFZNbx.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
package/dist/ui.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { y as i, a as s, c as e, d as t, e as A, f as k, g as n, h as o, z as g, B as d, i as h, D as l, F as m, G as p, j as C, r as b } from "./MountTenant-CUfrArN1.mjs";
1
+ import { y as i, a as s, c as e, d as t, e as A, f as k, g as n, h as o, z as g, B as d, i as h, D as l, F as m, G as p, j as C, r as b } from "./MountTenant-CZa8dgKD.mjs";
2
2
  export {
3
3
  i as AikaaraChat,
4
4
  s as AikaaraChatBubble,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikaara/chat-sdk",
3
- "version": "0.4.4",
3
+ "version": "0.4.5",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",