@talkjs/web-components 0.3.5 → 0.3.6

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.
Files changed (3) hide show
  1. package/default.cjs +2 -2
  2. package/default.js +58 -50
  3. package/package.json +1 -1
package/default.cjs CHANGED
@@ -1347,7 +1347,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1347
1347
  dominant-baseline="middle"
1348
1348
  >${r}</text>
1349
1349
  </svg>
1350
- `.replace(/\s+/g," ");return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`}function DR(){var s;const t=Qe(),e=ae(),n=on(),r=(s=J(()=>e.state$.isUserConnected.child(e.state$.currentConversationId.get())))!=null?s:{},i=J(e.state$.userPermissions),o=J(e.searchQuery$);return f(t.ChatHeader,{common:n,isUserConnected:r,permissions:i,searchQuery:o})}function TR(){const t=Qe(),e=on();return f(t.MessageListHeader,{common:e})}function RR(){const t=Qe(),e=on();return f(t.MessageListFooter,{common:e})}function IR(){const t=Qe(),e=on();return f(t.NoConversationSelected,{common:e})}function HA({containerRef:t}){const[e,n]=ee(null),[r,i]=ee(null),[o,s]=ee(!1);z(()=>{const d=t.current;let h=null;const p=m=>{if(m.pointerType!=="mouse")return;h&&(clearTimeout(h),h=null);const _=m.target.closest("[t-tooltip-text]");_&&(h=setTimeout(()=>{h=null,n(_),s(!1)},500))};return d==null||d.addEventListener("pointerover",p),()=>{d==null||d.removeEventListener("pointerover",p)}},[t]),z(()=>{const d=t.current;let h,p=!1;function m(A){p=!1,A.pointerType!=="mouse"&&(h=setTimeout(()=>{const g=A.target.closest("[t-tooltip-text]");g&&(p=!0,n(g),s(!0))},300))}function _(){clearTimeout(h)}function E(A){p&&(A.stopPropagation(),A.preventDefault())}return d.addEventListener("pointerdown",m),d.addEventListener("pointerup",_),d.addEventListener("pointerleave",_),d.addEventListener("click",E,!0),d.addEventListener("contextmenu",E,!0),()=>{d.removeEventListener("pointerdown",m),d.removeEventListener("pointerup",_),d.removeEventListener("pointerleave",_),d.removeEventListener("click",E,!0),d.removeEventListener("contextmenu",E,!0)}},[t]);const{refs:a,floatingStyles:l}=hA({placement:"top",middleware:[pA(),o&&(u=10,{...fT(u),options:[u,c]})],whileElementsMounted:uA});var u,c;return z(()=>{if(e){a.setReference(e);const d=()=>{const m=e.getAttribute("t-tooltip-text");m===null?p():i(m.trim())},h=new MutationObserver(d);h.observe(e,{attributes:!0}),d();const p=()=>{o?setTimeout(()=>n(null),1e3):n(null)};return e.addEventListener("pointerleave",p),()=>{e.removeEventListener("pointerleave",p),h.disconnect(),a.setReference(null),i(null)}}},[e,o,a]),r?f("div",{className:"t-tooltip",role:"tooltip",style:l,ref:a.setFloating,children:r}):null}function yR({appId:t,chatHeaderVisible:e,messageFieldVisible:n}){const r=ho(),i=(function(){const E=ae(),A=ct(()=>{const O=E.errors$.get(),D=E.authTokenState$.get(),I=E.state$.loadingConversationId.get(),R=E.state$.currentConversationId.get();return O.serverError?"server-error":O.wrongAppId?"wrong-app-id":D==="loading"||D==="idle"?"loading-token":D==="invalid"?"invalid-token":D==="expired"?"expired-token":D==="valid"?O.unknownUser?"unknown-user":I&&E.state$.unknownConversations.child(I).get()?"loading-conv-failed":E.canRenderUi(I)||R!==I&&E.canRenderUi(R)?"loaded":"loading-data":void re.unreachable()}),g=ct({type:"loading"});Yi(O=>{const D=A.get(),I=E.state$.currentConversationId.get(),R=E.extUserId$.get(),y=E.appId$.get();function v(T){g.set({type:"loading"});const C=setTimeout(()=>{g.set(T)},5e3);return()=>clearTimeout(C)}switch(D){case"invalid-token":g.set({type:"auth-failed"});break;case"expired-token":g.set({type:"expired-token"});break;case"wrong-app-id":g.set({type:"wrong-app-id",appId:y});break;case"server-error":g.set({type:"server-error"});break;case"loading-data":case"loading-token":g.set({type:"loading"});break;case"loaded":g.set({type:"loaded",conversationId:I,userId:R});break;case"loading-conv-failed":O.onCleanup=v({type:"inaccessible-conversation",userId:R,conversationId:I});break;case"unknown-user":O.onCleanup=v({type:"unknown-user",userId:R});break;default:re.never(D)}});const S=ct({type:"loading"});return Yi(O=>{if(g.type.get()==="loading"){S.set({type:"invisible-loading"});const D=setTimeout(()=>{S.set({type:"loading"})},1e3);O.onCleanup=()=>{clearTimeout(D)}}else S.set(g.get())}),J(S)})(),o=nE();z(()=>{r.uploadFile=o.startFileUpload,o.onClose=()=>{r.focus()}},[r,o]);const[s,a]=ee(!1),l=ae(),u=J(()=>!!l.app$.get()&&l.state$.userPermissions.canShareFile.get()),c=J(()=>o.uploads$.get().length>0),d=u&&!c;z(()=>{i.type==="loaded"?l.renderedConversationId$.set(i.conversationId):l.renderedConversationId$.set(void 0)},[i,l]);const h=q(E=>{o.startFileUpload([...E.dataTransfer.files]),E.preventDefault(),a(!1)},[o]),p=q(E=>{E.preventDefault(),E.dataTransfer.types.includes("Files")&&a(!0)},[]),m=q(E=>{E.preventDefault(),a(!1)},[]),_=X(null);return mu(),i.type==="invisible-loading"?f(ie,{}):i.type==="loading"?f(kA,{}):i.type==="inaccessible-conversation"?f(mR,{}):i.type==="unknown-user"||i.type==="auth-failed"||i.type==="wrong-app-id"||i.type==="server-error"||i.type==="unexpected-error"?f(la,{appId:t,chatboxState:i}):i.type=="expired-token"?f(MA,{}):i.type==="loaded"?i.conversationId===null?f(IR,{}):f("div",{className:"t-chatbox-content",onDragOver:d?p:void 0,onDragLeave:d?m:void 0,onDrop:d?h:void 0,"t-menu-boundary":"root",ref:_,children:[e&&f(DR,{}),f(TR,{}),f(hR,{conversationId:i.conversationId}),f(RR,{}),n&&f(LA,{attachFile:o.startFileUpload,shareLocation:o.startLocationUpload}),c&&f(ER,{}),s&&f(PA,{className:"t-drop-overlay",children:f(B,{type:"attachment"})}),f(HA,{containerRef:_})]}):f(ie,{})}const CR=()=>!0;async function bu(t,e,{initialDelay:n,maxDelay:r,log:i,shouldRetry:o=CR}){return e().catch(async s=>{if(i&&i(`[TalkJS] Retries left: ${t}. Error: ${JSON.stringify(s)}.`),t===0||!await o(s))throw s;const a=1e3*n*1.2,l=Math.min(1e3*r,a),u=l*(1-(c=.05)+2*Math.random()*c);var c,d;return(d=u,d<=0?Promise.resolve():new Promise(h=>setTimeout(h,d))).then(()=>bu(t-1,e,{initialDelay:u/1e3,maxDelay:r,log:i,shouldRetry:o}))})}function Ec(){const t={},e=new Promise(function(n,r){t.resolve=n,t.reject=r});return t.promise=e,t}const zo=new Uint8Array(31);function UA(){if(globalThis.crypto!==void 0)crypto.getRandomValues(zo);else for(let e=0;e<zo.length;e++)zo[e]=Math.floor(256*Math.random());let t=0;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^zo[t++]&15>>+e/4).toString(16))}class NR{constructor(e,n,r,i,o,s,a,l){this.store=e,this.talkSession=n,this.editorInternals=r,this.onSendMessage=i,this.onDeleteMessage=o,this.onMessageAction=s,this.onFocusMessage=a,this.onBackButtonClick=l,this.loadMoreUntil=async u=>{const c=this.store.state$.currentConversationId.peek(),d=this.store.state$.messages.child(c).loadedAll;let h;do{const p=this.store.messageSubscriptions[c];p&&!d.peek()&&await p.loadMore(30),h=u()}while(!d.peek()&&!h);return h}}setScrollableDiv(e){this.scrollable=e}toggleSearchBox(e){if(this.store.state$.userPermissions.canSearch.peek())if(e!==void 0)this.store.chatSearchState$.set(e?"visible":"hidden");else{const n=this.store.chatSearchState$.peek();this.store.chatSearchState$.set(n==="hidden"?"visible":"hidden")}else Te.error("In-conversation message search is only available to customers on Growth plan and above.")}async deleteMessage(e){const n=this.store.state$.currentConversation.peek();if(!n||n.access==="Read")return;const r=n.id,i=this.store.state$.messages.child(r).lookup.child(e).peek(),o=this.talkSession.conversation(r).message(e),[s]=await Promise.all([i!=null?i:o.get(),o.delete()]);if(s){const a={currentUser:this.store.currentUser$.peek(),conversation:this.store.state$.currentConversation.peek(),message:i};this.onDeleteMessage(a)}}setEditing(e){const n=this.store.state$.currentConversation.peek();n&&n.access!=="Read"&&this.store.state$.editingMessageId.set(e)}async editMessage(e,n){const r=this.store.state$.currentConversation.peek();if(!r||r.access==="Read")return;const i=r.id;await this.talkSession.conversation(i).message(e).edit(n)}setReferencedMessage(e){const n=this.store.state$.currentConversation.peek();n&&n.access!=="Read"&&(this.store.state$.referencedMessageId.set(e),setTimeout(()=>this.editorInternals.focus({skipProseMirrorStuff:!0}),100))}async focusMessage(e,n=!0){var a;if(e==null)return this.store.focusedMessage$.set(null),null;if(await js(()=>this.store.state$.loadingConversationId.get()===this.store.renderedConversationId$.get()),this.store.state$.currentConversationId.peek()===null)return Te.error("Cannot focus message because current conversation is `null`."),null;const r=()=>{const l=this.store.state$.currentConversationId.peek();return this.store.state$.messages.child(l).lookup.child(e).peek()||null};let i=r();if(i||(i=await this.loadMoreUntil(r)),!i)return Te.error(`Message with id: \`${e}\` could not be found in this conversation`),i;const o=(a=this.scrollable)==null?void 0:a.current;re.defined(o);const s=o.querySelector(`[t-message-id="${e}"]`);return s?this.scrollToAndHighlight(s,i,n):Te.error(`Could not find HTMLElement with attribute: t-message-id="${e}"`),i}async jumpToHighlight(e){if(!this.store.state$.userPermissions.canSearch.peek())return Te.error("In-conversation message search is only available to customers on Growth plan and above."),null;if(this.store.highlightedStrings$.peek().length===0||this.store.chatSearchState$.peek()==="searching")return null;let n=this.findHighlight(e);return n||e!=="up"||(this.store.chatSearchState$.set("searching"),n=await this.loadMoreUntil(()=>this.findHighlight("up"))),n}findHighlight(e){var u;const n=(u=this.scrollable)==null?void 0:u.current;re.defined(n);const r=[],i=Array.from(n.querySelectorAll("[t-message-id]")),o=this.store.state$.currentConversationId.peek(),s=this.store.state$.messages.child(o).state.peek();if(i.length===0&&s.length!==0)return Te.error("Could not find HTMLElements with the attribute: t-message-id. This attribute is required for In-Conversation search to work."),null;let a;if(Array.from(n.getElementsByClassName("t-highlighted-text")).forEach(c=>{const d=i.findIndex(m=>m.contains(c));if(d===-1)return;const h=i.splice(d,1)[0],p=h.getAttribute("t-message-id");r.push([p,h])}),e==="up"){const c=n.getBoundingClientRect().top;a=r.find(([d,h])=>h.getBoundingClientRect().top-c<-5)}else{const c=.05*n.getBoundingClientRect().height,d=n.getBoundingClientRect().bottom;for(let h=r.length-1;h>=0;h--){const p=r[h],[m,_]=p;if(d-_.getBoundingClientRect().top<=c){a=p;break}}}const l=this.store.chatSearchState$;if(a){const[c,d]=a,h=this.store.state$.messages.child(o).lookup.child(c).peek();return this.scrollToAndHighlight(d,h),l.set("visible"),h}return r.length===0?l.set("noResults"):l.set("noMoreResults"),null}scrollToAndHighlight(e,n,r=!0){const i=this.scrollable.current.getBoundingClientRect(),o=e.getBoundingClientRect();let s="start";Math.sign(i.top-o.top)===-1&&o.height<i.height&&(s="end"),e instanceof HTMLElement&&(e.style.scrollSnapAlign=s),e.scrollIntoView({behavior:"instant"}),e instanceof HTMLElement&&(e.style.scrollSnapAlign="none"),this.store.focusedMessage$.set(n),r&&this.onFocusMessage({message:n})}setHighlightedStrings(e){this.store.state$.userPermissions.canSearch.peek()?this.store.highlightedStrings$.set(e):Te.error("In-conversation message search and by extension highlighting of strings are only available to customers on Growth plan and above.")}setSearchQuery(e){this.store.setSearchQuery(e)}async sendMessage(e){const n=this.store.state$.currentConversationId.peek();if(!n)return;const r=await(async function(s,a){var _,E,A,g,S;const l=s.state$.currentConversationId.peek(),u=s.state$.messages.child(l),c=typeof a.referencedMessage=="string"?u.lookup.child(a.referencedMessage).peek():await((E=(_=a.referencedMessage)==null?void 0:_.get())!=null?E:null),d=c&&{...c,type:"UserMessage",sender:c.sender,referencedMessageId:(g=(A=c.referencedMessage)==null?void 0:A.id)!=null?g:null};d&&delete d.referencedMessage;const h="content"in a?[Df(s,a.content[0])]:[bR(a.text)],p="text"in a?a.text:yA(a.content.map(O=>Df(s,O)),{}),m=Math.max(Date.now(),vf+1);return vf=m,{id:"ephemeral-"+UA(),type:"UserMessage",sender:s.currentUser$.peek(),createdAt:m,editedAt:null,custom:(S=a.custom)!=null?S:{},origin:"web",referencedMessage:d,reactions:[],content:h,plaintext:p}})(this.store,e);this.store.state$.ephemeralMessages.child(n).child(r.id).set(r);const i=Ec();this.store.readyForNewMessagesPromise=i.promise;const o=await this.talkSession.conversation(n).send(e);this.store.state$.ephemeralMessageIdMapping.child(n).child(o.id).set(r.id),i.resolve(),this.onSendMessage({message:await o.get(),currentUser:this.store.currentUser$.peek(),conversation:this.store.state$.currentConversation.peek()})}sendFileMessage(e){const n={type:"file",fileToken:e.fileToken};return this.sendMessage({content:[n],custom:e.custom})}async uploadVoice(e,n){return await this.talkSession.uploadVoice(e,n)}sendLocationMessage(e){const n={type:"location",latitude:e.location.latitude,longitude:e.location.longitude};return this.sendMessage({content:[n],custom:e.custom})}markAsTyping(){const e=this.store.state$.currentConversationId.peek();e&&this.talkSession.conversation(e).markAsTyping()}async toggleReaction(e,n,r){typeof n!="string"&&(n=n.emoji);const i=this.store.state$.currentConversationId.peek();if(!i)return;const o=this.store.state$.messages.child(i).lookup.child(e).peek().reactions.find(a=>a.emoji===n),s=this._getReactionRef(e,n);o!=null&&o.currentUserReacted&&r!==!0?await s.remove():r!==!1&&await s.add()}async addReaction(e,n){this.store.state$.currentConversationId.peek()&&await this._getReactionRef(e,n).add()}triggerMessageAction(e,n,r){const i=this.store.state$.currentConversation.peek();i&&(typeof e=="string"&&(e=this.store.state$.messages.child(i.id).lookup.child(e).peek()),this.onMessageAction({action:n,params:r,message:e,conversation:i}))}clickBackButton(){const e=this.store.currentUser$.peek();re.defined(e),this.onBackButtonClick({currentUser:e})}storeDraft(e){const n=this.store.state$.currentConversationId.peek(),r=this.store.currentUser$.peek(),i=this.store.appId$.peek();n&&r&&i&&M0(n,r.id,i,e)}_getReactionRef(e,n){const r=this.store.state$.currentConversationId.peek();return this.talkSession.conversation(r).message(e).reaction(n)}}let vf=0;const bR=t=>({type:"text",children:P_(t)});function Df(t,e){switch(e.type){case"text":case"location":return e;case"file":return(function(n,r){const i=n.fileUploads[r.fileToken];return re.defined(i),{type:"file",subtype:i.type==="file"?void 0:i.type,...i.metadata,size:i.file.size,filename:i.file.name,fileToken:r.fileToken,url:i.temporaryBlobUrl}})(t,e)}}class El extends Error{constructor(e,n){const r=(function(i){if(typeof i=="string")return i;if(Array.isArray(i))return i.join(`
1350
+ `.replace(/\s+/g," ");return`data:image/svg+xml;utf8,${encodeURIComponent(i)}`}function DR(){var s;const t=Qe(),e=ae(),n=on(),r=(s=J(()=>e.state$.isUserConnected.child(e.state$.currentConversationId.get())))!=null?s:{},i=J(e.state$.userPermissions),o=J(e.searchQuery$);return f(t.ChatHeader,{common:n,isUserConnected:r,permissions:i,searchQuery:o})}function TR(){const t=Qe(),e=on();return f(t.MessageListHeader,{common:e})}function RR(){const t=Qe(),e=on();return f(t.MessageListFooter,{common:e})}function IR(){const t=Qe(),e=on();return f(t.NoConversationSelected,{common:e})}function HA({containerRef:t}){const[e,n]=ee(null),[r,i]=ee(null),[o,s]=ee(!1);z(()=>{const d=t.current;let h=null;const p=m=>{if(m.pointerType!=="mouse")return;h&&(clearTimeout(h),h=null);const _=m.target.closest("[t-tooltip-text]");_&&(h=setTimeout(()=>{h=null,n(_),s(!1)},500))};return d==null||d.addEventListener("pointerover",p),()=>{d==null||d.removeEventListener("pointerover",p)}},[t]),z(()=>{const d=t.current;let h,p=!1;function m(A){p=!1,A.pointerType!=="mouse"&&(h=setTimeout(()=>{const g=A.target.closest("[t-tooltip-text]");g&&(p=!0,n(g),s(!0))},300))}function _(){clearTimeout(h)}function E(A){p&&(A.stopPropagation(),A.preventDefault())}return d.addEventListener("pointerdown",m),d.addEventListener("pointerup",_),d.addEventListener("pointerleave",_),d.addEventListener("click",E,!0),d.addEventListener("contextmenu",E,!0),()=>{d.removeEventListener("pointerdown",m),d.removeEventListener("pointerup",_),d.removeEventListener("pointerleave",_),d.removeEventListener("click",E,!0),d.removeEventListener("contextmenu",E,!0)}},[t]);const{refs:a,floatingStyles:l}=hA({placement:"top",middleware:[pA(),o&&(u=10,{...fT(u),options:[u,c]})],whileElementsMounted:uA});var u,c;return z(()=>{if(e){a.setReference(e);const d=()=>{const m=e.getAttribute("t-tooltip-text");m===null?p():i(m.trim())},h=new MutationObserver(d);h.observe(e,{attributes:!0}),d();const p=()=>{o?setTimeout(()=>n(null),1e3):n(null)};return e.addEventListener("pointerleave",p),()=>{e.removeEventListener("pointerleave",p),h.disconnect(),a.setReference(null),i(null)}}},[e,o,a]),r?f("div",{className:"t-tooltip",role:"tooltip",style:l,ref:a.setFloating,children:r}):null}function yR({appId:t,chatHeaderVisible:e,messageFieldVisible:n}){const r=ho(),i=(function(){const A=ae(),g=ct(()=>{const D=A.errors$.get(),I=A.authTokenState$.get(),R=A.state$.loadingConversationId.get(),y=A.state$.currentConversationId.get();return D.serverError?"server-error":D.wrongAppId?"wrong-app-id":I==="loading"||I==="idle"?"loading-token":I==="invalid"?"invalid-token":I==="expired"?"expired-token":I==="valid"?D.unknownUser?"unknown-user":R&&A.state$.unknownConversations.child(R).get()?"loading-conv-failed":A.canRenderUi(R)||y!==R&&A.canRenderUi(y)?"loaded":"loading-data":void re.unreachable()}),S=ct({type:"loading"});Yi(D=>{const I=g.get(),R=A.state$.currentConversationId.get(),y=A.extUserId$.get(),v=A.appId$.get();function T(C){S.set({type:"loading"});const N=setTimeout(()=>{S.set(C)},5e3);return()=>clearTimeout(N)}switch(I){case"invalid-token":S.set({type:"auth-failed"});break;case"expired-token":S.set({type:"expired-token"});break;case"wrong-app-id":S.set({type:"wrong-app-id",appId:v});break;case"server-error":S.set({type:"server-error"});break;case"loading-data":case"loading-token":S.set({type:"loading"});break;case"loaded":S.set({type:"loaded",conversationId:R,userId:y});break;case"loading-conv-failed":D.onCleanup=T({type:"inaccessible-conversation",userId:y,conversationId:R});break;case"unknown-user":D.onCleanup=T({type:"unknown-user",userId:y});break;default:re.never(I)}});const O=ct({type:"loading"});return Yi(D=>{if(S.type.get()==="loading"){O.set({type:"invisible-loading"});const I=setTimeout(()=>{O.set({type:"loading"})},1e3);D.onCleanup=()=>{clearTimeout(I)}}else O.set(S.get())}),J(O)})(),o=nE(),s=X(null);z(()=>{const A=s.current;return o.setInputElement(A),A==null||A.addEventListener("change",o.onInputChange),A==null||A.addEventListener("cancel",o.onInputCancel),()=>{o.setInputElement(null),A==null||A.removeEventListener("change",o.onInputChange),A==null||A.removeEventListener("cancel",o.onInputCancel)}}),z(()=>{r.uploadFile=o.startFileUpload,o.onClose=()=>{r.focus()}},[r,o]);const[a,l]=ee(!1),u=ae(),c=J(()=>!!u.app$.get()&&u.state$.userPermissions.canShareFile.get()),d=J(()=>o.uploads$.get().length>0),h=c&&!d;z(()=>{i.type==="loaded"?u.renderedConversationId$.set(i.conversationId):u.renderedConversationId$.set(void 0)},[i,u]);const p=q(A=>{o.startFileUpload([...A.dataTransfer.files]),A.preventDefault(),l(!1)},[o]),m=q(A=>{A.preventDefault(),A.dataTransfer.types.includes("Files")&&l(!0)},[]),_=q(A=>{A.preventDefault(),l(!1)},[]),E=X(null);return mu(),i.type==="invisible-loading"?f(ie,{}):i.type==="loading"?f(kA,{}):i.type==="inaccessible-conversation"?f(mR,{}):i.type==="unknown-user"||i.type==="auth-failed"||i.type==="wrong-app-id"||i.type==="server-error"||i.type==="unexpected-error"?f(la,{appId:t,chatboxState:i}):i.type=="expired-token"?f(MA,{}):i.type==="loaded"?i.conversationId===null?f(IR,{}):f("div",{className:"t-chatbox-content",onDragOver:h?m:void 0,onDragLeave:h?_:void 0,onDrop:h?p:void 0,"t-menu-boundary":"root",ref:E,children:[e&&f(DR,{}),f(TR,{}),f(hR,{conversationId:i.conversationId}),f(RR,{}),n&&f(LA,{attachFile:o.startFileUpload,shareLocation:o.startLocationUpload}),d&&f(ER,{}),a&&f(PA,{className:"t-drop-overlay",children:f(B,{type:"attachment"})}),f("input",{ref:s,type:"file",multiple:!0,style:{display:"none"}}),f(HA,{containerRef:E})]}):f(ie,{})}const CR=()=>!0;async function bu(t,e,{initialDelay:n,maxDelay:r,log:i,shouldRetry:o=CR}){return e().catch(async s=>{if(i&&i(`[TalkJS] Retries left: ${t}. Error: ${JSON.stringify(s)}.`),t===0||!await o(s))throw s;const a=1e3*n*1.2,l=Math.min(1e3*r,a),u=l*(1-(c=.05)+2*Math.random()*c);var c,d;return(d=u,d<=0?Promise.resolve():new Promise(h=>setTimeout(h,d))).then(()=>bu(t-1,e,{initialDelay:u/1e3,maxDelay:r,log:i,shouldRetry:o}))})}function Ec(){const t={},e=new Promise(function(n,r){t.resolve=n,t.reject=r});return t.promise=e,t}const zo=new Uint8Array(31);function UA(){if(globalThis.crypto!==void 0)crypto.getRandomValues(zo);else for(let e=0;e<zo.length;e++)zo[e]=Math.floor(256*Math.random());let t=0;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^zo[t++]&15>>+e/4).toString(16))}class NR{constructor(e,n,r,i,o,s,a,l){this.store=e,this.talkSession=n,this.editorInternals=r,this.onSendMessage=i,this.onDeleteMessage=o,this.onMessageAction=s,this.onFocusMessage=a,this.onBackButtonClick=l,this.loadMoreUntil=async u=>{const c=this.store.state$.currentConversationId.peek(),d=this.store.state$.messages.child(c).loadedAll;let h;do{const p=this.store.messageSubscriptions[c];p&&!d.peek()&&await p.loadMore(30),h=u()}while(!d.peek()&&!h);return h}}setScrollableDiv(e){this.scrollable=e}toggleSearchBox(e){if(this.store.state$.userPermissions.canSearch.peek())if(e!==void 0)this.store.chatSearchState$.set(e?"visible":"hidden");else{const n=this.store.chatSearchState$.peek();this.store.chatSearchState$.set(n==="hidden"?"visible":"hidden")}else Te.error("In-conversation message search is only available to customers on Growth plan and above.")}async deleteMessage(e){const n=this.store.state$.currentConversation.peek();if(!n||n.access==="Read")return;const r=n.id,i=this.store.state$.messages.child(r).lookup.child(e).peek(),o=this.talkSession.conversation(r).message(e),[s]=await Promise.all([i!=null?i:o.get(),o.delete()]);if(s){const a={currentUser:this.store.currentUser$.peek(),conversation:this.store.state$.currentConversation.peek(),message:i};this.onDeleteMessage(a)}}setEditing(e){const n=this.store.state$.currentConversation.peek();n&&n.access!=="Read"&&this.store.state$.editingMessageId.set(e)}async editMessage(e,n){const r=this.store.state$.currentConversation.peek();if(!r||r.access==="Read")return;const i=r.id;await this.talkSession.conversation(i).message(e).edit(n)}setReferencedMessage(e){const n=this.store.state$.currentConversation.peek();n&&n.access!=="Read"&&(this.store.state$.referencedMessageId.set(e),setTimeout(()=>this.editorInternals.focus({skipProseMirrorStuff:!0}),100))}async focusMessage(e,n=!0){var a;if(e==null)return this.store.focusedMessage$.set(null),null;if(await js(()=>this.store.state$.loadingConversationId.get()===this.store.renderedConversationId$.get()),this.store.state$.currentConversationId.peek()===null)return Te.error("Cannot focus message because current conversation is `null`."),null;const r=()=>{const l=this.store.state$.currentConversationId.peek();return this.store.state$.messages.child(l).lookup.child(e).peek()||null};let i=r();if(i||(i=await this.loadMoreUntil(r)),!i)return Te.error(`Message with id: \`${e}\` could not be found in this conversation`),i;const o=(a=this.scrollable)==null?void 0:a.current;re.defined(o);const s=o.querySelector(`[t-message-id="${e}"]`);return s?this.scrollToAndHighlight(s,i,n):Te.error(`Could not find HTMLElement with attribute: t-message-id="${e}"`),i}async jumpToHighlight(e){if(!this.store.state$.userPermissions.canSearch.peek())return Te.error("In-conversation message search is only available to customers on Growth plan and above."),null;if(this.store.highlightedStrings$.peek().length===0||this.store.chatSearchState$.peek()==="searching")return null;let n=this.findHighlight(e);return n||e!=="up"||(this.store.chatSearchState$.set("searching"),n=await this.loadMoreUntil(()=>this.findHighlight("up"))),n}findHighlight(e){var u;const n=(u=this.scrollable)==null?void 0:u.current;re.defined(n);const r=[],i=Array.from(n.querySelectorAll("[t-message-id]")),o=this.store.state$.currentConversationId.peek(),s=this.store.state$.messages.child(o).state.peek();if(i.length===0&&s.length!==0)return Te.error("Could not find HTMLElements with the attribute: t-message-id. This attribute is required for In-Conversation search to work."),null;let a;if(Array.from(n.getElementsByClassName("t-highlighted-text")).forEach(c=>{const d=i.findIndex(m=>m.contains(c));if(d===-1)return;const h=i.splice(d,1)[0],p=h.getAttribute("t-message-id");r.push([p,h])}),e==="up"){const c=n.getBoundingClientRect().top;a=r.find(([d,h])=>h.getBoundingClientRect().top-c<-5)}else{const c=.05*n.getBoundingClientRect().height,d=n.getBoundingClientRect().bottom;for(let h=r.length-1;h>=0;h--){const p=r[h],[m,_]=p;if(d-_.getBoundingClientRect().top<=c){a=p;break}}}const l=this.store.chatSearchState$;if(a){const[c,d]=a,h=this.store.state$.messages.child(o).lookup.child(c).peek();return this.scrollToAndHighlight(d,h),l.set("visible"),h}return r.length===0?l.set("noResults"):l.set("noMoreResults"),null}scrollToAndHighlight(e,n,r=!0){const i=this.scrollable.current.getBoundingClientRect(),o=e.getBoundingClientRect();let s="start";Math.sign(i.top-o.top)===-1&&o.height<i.height&&(s="end"),e instanceof HTMLElement&&(e.style.scrollSnapAlign=s),e.scrollIntoView({behavior:"instant"}),e instanceof HTMLElement&&(e.style.scrollSnapAlign="none"),this.store.focusedMessage$.set(n),r&&this.onFocusMessage({message:n})}setHighlightedStrings(e){this.store.state$.userPermissions.canSearch.peek()?this.store.highlightedStrings$.set(e):Te.error("In-conversation message search and by extension highlighting of strings are only available to customers on Growth plan and above.")}setSearchQuery(e){this.store.setSearchQuery(e)}async sendMessage(e){const n=this.store.state$.currentConversationId.peek();if(!n)return;const r=await(async function(s,a){var _,E,A,g,S;const l=s.state$.currentConversationId.peek(),u=s.state$.messages.child(l),c=typeof a.referencedMessage=="string"?u.lookup.child(a.referencedMessage).peek():await((E=(_=a.referencedMessage)==null?void 0:_.get())!=null?E:null),d=c&&{...c,type:"UserMessage",sender:c.sender,referencedMessageId:(g=(A=c.referencedMessage)==null?void 0:A.id)!=null?g:null};d&&delete d.referencedMessage;const h="content"in a?[Df(s,a.content[0])]:[bR(a.text)],p="text"in a?a.text:yA(a.content.map(O=>Df(s,O)),{}),m=Math.max(Date.now(),vf+1);return vf=m,{id:"ephemeral-"+UA(),type:"UserMessage",sender:s.currentUser$.peek(),createdAt:m,editedAt:null,custom:(S=a.custom)!=null?S:{},origin:"web",referencedMessage:d,reactions:[],content:h,plaintext:p}})(this.store,e);this.store.state$.ephemeralMessages.child(n).child(r.id).set(r);const i=Ec();this.store.readyForNewMessagesPromise=i.promise;const o=await this.talkSession.conversation(n).send(e);this.store.state$.ephemeralMessageIdMapping.child(n).child(o.id).set(r.id),i.resolve(),this.onSendMessage({message:await o.get(),currentUser:this.store.currentUser$.peek(),conversation:this.store.state$.currentConversation.peek()})}sendFileMessage(e){const n={type:"file",fileToken:e.fileToken};return this.sendMessage({content:[n],custom:e.custom})}async uploadVoice(e,n){return await this.talkSession.uploadVoice(e,n)}sendLocationMessage(e){const n={type:"location",latitude:e.location.latitude,longitude:e.location.longitude};return this.sendMessage({content:[n],custom:e.custom})}markAsTyping(){const e=this.store.state$.currentConversationId.peek();e&&this.talkSession.conversation(e).markAsTyping()}async toggleReaction(e,n,r){typeof n!="string"&&(n=n.emoji);const i=this.store.state$.currentConversationId.peek();if(!i)return;const o=this.store.state$.messages.child(i).lookup.child(e).peek().reactions.find(a=>a.emoji===n),s=this._getReactionRef(e,n);o!=null&&o.currentUserReacted&&r!==!0?await s.remove():r!==!1&&await s.add()}async addReaction(e,n){this.store.state$.currentConversationId.peek()&&await this._getReactionRef(e,n).add()}triggerMessageAction(e,n,r){const i=this.store.state$.currentConversation.peek();i&&(typeof e=="string"&&(e=this.store.state$.messages.child(i.id).lookup.child(e).peek()),this.onMessageAction({action:n,params:r,message:e,conversation:i}))}clickBackButton(){const e=this.store.currentUser$.peek();re.defined(e),this.onBackButtonClick({currentUser:e})}storeDraft(e){const n=this.store.state$.currentConversationId.peek(),r=this.store.currentUser$.peek(),i=this.store.appId$.peek();n&&r&&i&&M0(n,r.id,i,e)}_getReactionRef(e,n){const r=this.store.state$.currentConversationId.peek();return this.talkSession.conversation(r).message(e).reaction(n)}}let vf=0;const bR=t=>({type:"text",children:P_(t)});function Df(t,e){switch(e.type){case"text":case"location":return e;case"file":return(function(n,r){const i=n.fileUploads[r.fileToken];return re.defined(i),{type:"file",subtype:i.type==="file"?void 0:i.type,...i.metadata,size:i.file.size,filename:i.file.name,fileToken:r.fileToken,url:i.temporaryBlobUrl}})(t,e)}}class El extends Error{constructor(e,n){const r=(function(i){if(typeof i=="string")return i;if(Array.isArray(i))return i.join(`
1351
1351
  `);try{return JSON.stringify(i)}catch(o){return String(i)}})(e);super(r),this.userMessage=n!=null?n:r,Object.setPrototypeOf&&Object.setPrototypeOf(this,new.target.prototype)}}const oo=console;class wR{constructor(e,n,r,i){this.apiUrls=e,this.appId=n,this.sessionId=r,this.authProvider=i,this._lastPutPromise=Promise.resolve()}async get(e,n={}){const r=this.endpointUrl(e,n),i=await Oi(()=>this.fetchWithReauth(r),{retries:11});return await this.handleResponse(i,r)}async queuedPut(e,n){await this._lastPutPromise;const r=Oi(()=>this._doPut(e,n));return this._lastPutPromise=r,r}put(e,n,r){const i=()=>this._doPut(e,n);return r?Tf(i,r):Oi(i,{retries:5})}post(e,n,r){const i=()=>this._doPost(e,n);return r?Tf(i,r):Oi(i,{retries:5})}delete(e,n={}){return Oi(()=>this._doDelete(e,n),{retries:11})}endpointUrl(e,n={}){const r=new URL(this.apiUrls.internalHttpApiUrl);r.pathname+=`/${this.appId}/${e}`,r.searchParams.set("sessionId",this.sessionId);for(const[i,o]of Object.entries(n))r.searchParams.set(i,o);return r}async _doPut(e,n){const r=this.endpointUrl(e),i=await this.fetchWithReauth(r,{method:"PUT",body:JSON.stringify(n)});return await this.handleResponse(i,r)}async _doPost(e,n){const r=this.endpointUrl(e),i=await this.fetchWithReauth(r,{method:"POST",body:JSON.stringify(n)});return await this.handleResponse(i,r)}async _doDelete(e,n){const r=this.endpointUrl(e,n),i=await this.fetchWithReauth(r,{method:"DELETE"});return await this.handleResponse(i,r)}async handleResponse(e,n){if(e.status>=300){if(e.status===404)throw kl.error(`[${this.appId}][BackendRestClient] Couldn't find resource.`),new El("Could not find app.",`Could not find given appId: "${this.appId}". You can find your appId on https://talkjs.com/dashboard.`);if(e.status===401){const r=await this.authProvider.getToken();throw kl.error(`[${this.appId}][BackendRestClient] Couldn't authenticate ${n} with token ${r}.`),new El("User not authenticated.","Could not authenticate user. Check if your signature is calculated correctly.")}if(e.status>=300&&e.status<500){const{error:r}=await e.json();throw new El(r)}{const r=await e.text();throw new Error(`Got non-success response (${r}) from the server for url: ${n}.`)}}return await e.json()}async fetchWithReauth(e,n){function r(s){const a={Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${s}`};return fetch(e,{...n,headers:a})}const i=await this.authProvider.getToken(),o=await r(i);return o.status!==401?o:(oo.error(`401 error from ${n==null?void 0:n.method} ${e}, ${i}`),this.authProvider.refreshToken(),r(await this.authProvider.getToken()))}}function BA(t){return!t.userMessage}function Oi(t,{retries:e=30}={}){return bu(e,t,{shouldRetry:BA,log:oo.warn.bind(oo),maxDelay:30,initialDelay:.2})}async function Tf(t,e){try{return await t()}catch(r){if(!BA(r))throw r}let n=!1;return e.then(()=>{n=!0}),bu(1e3,t,{initialDelay:.2,maxDelay:30,shouldRetry:()=>!n,log:oo.warn.bind(oo)})}var Rf,_l={exports:{}},LR=(Rf||(Rf=1,(function(t,e){var n="__lodash_hash_undefined__",r=9007199254740991,i="[object Arguments]",o="[object Function]",s="[object Object]",a=/^\[object .+?Constructor\]$/,l=/^(?:0|[1-9]\d*)$/,u={};u["[object Float32Array]"]=u["[object Float64Array]"]=u["[object Int8Array]"]=u["[object Int16Array]"]=u["[object Int32Array]"]=u["[object Uint8Array]"]=u["[object Uint8ClampedArray]"]=u["[object Uint16Array]"]=u["[object Uint32Array]"]=!0,u[i]=u["[object Array]"]=u["[object ArrayBuffer]"]=u["[object Boolean]"]=u["[object DataView]"]=u["[object Date]"]=u["[object Error]"]=u[o]=u["[object Map]"]=u["[object Number]"]=u[s]=u["[object RegExp]"]=u["[object Set]"]=u["[object String]"]=u["[object WeakMap]"]=!1;var c,d=typeof wo=="object"&&wo&&wo.Object===Object&&wo,h=typeof self=="object"&&self&&self.Object===Object&&self,p=d||h||Function("return this")(),m=e&&!e.nodeType&&e,_=m&&t&&!t.nodeType&&t,E=_&&_.exports===m,A=E&&d.process,g=(function(){try{var w=_&&_.require&&_.require("util").types;return w||A&&A.binding&&A.binding("util")}catch(P){}})(),S=g&&g.isTypedArray,O=Array.prototype,D=Function.prototype,I=Object.prototype,R=p["__core-js_shared__"],y=D.toString,v=I.hasOwnProperty,T=(c=/[^.]+$/.exec(R&&R.keys&&R.keys.IE_PROTO||""))?"Symbol(src)_1."+c:"",C=I.toString,N=y.call(Object),L=RegExp("^"+y.call(v).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),b=E?p.Buffer:void 0,k=p.Symbol,x=p.Uint8Array;b&&b.allocUnsafe;var M,U,V=(M=Object.getPrototypeOf,U=Object,function(w){return M(U(w))}),$=Object.create,Y=I.propertyIsEnumerable,oe=O.splice,le=k?k.toStringTag:void 0,ce=(function(){try{var w=da(Object,"defineProperty");return w({},"",{}),w}catch(P){}})(),pe=b?b.isBuffer:void 0,tt=Math.max,Vt=Date.now,nt=da(p,"Map"),ve=da(Object,"create"),Re=(function(){function w(){}return function(P){if(!Yn(P))return{};if($)return $(P);w.prototype=P;var H=new w;return w.prototype=void 0,H}})();function $n(w){var P=-1,H=w==null?0:w.length;for(this.clear();++P<H;){var G=w[P];this.set(G[0],G[1])}}function sn(w){var P=-1,H=w==null?0:w.length;for(this.clear();++P<H;){var G=w[P];this.set(G[0],G[1])}}function Rr(w){var P=-1,H=w==null?0:w.length;for(this.clear();++P<H;){var G=w[P];this.set(G[0],G[1])}}function Ir(w){var P=this.__data__=new sn(w);this.size=P.size}function ZA(w,P){var H=fa(w),G=!H&&pa(w),ue=!H&&!G&&Fu(w),Ie=!H&&!G&&!ue&&Uu(w),ge=H||G||ue||Ie,rt=ge?(function(je,an){for(var ht=-1,yr=Array(je);++ht<je;)yr[ht]=an(ht);return yr})(w.length,String):[],dt=rt.length;for(var ye in w)ge&&(ye=="length"||ue&&(ye=="offset"||ye=="parent")||Ie&&(ye=="buffer"||ye=="byteLength"||ye=="byteOffset")||Pu(ye,dt))||rt.push(ye);return rt}function ca(w,P,H){(H!==void 0&&!Ro(w[P],H)||H===void 0&&!(P in w))&&ua(w,P,H)}function QA(w,P,H){var G=w[P];v.call(w,P)&&Ro(G,H)&&(H!==void 0||P in w)||ua(w,P,H)}function vo(w,P){for(var H=w.length;H--;)if(Ro(w[H][0],P))return H;return-1}function ua(w,P,H){P=="__proto__"&&ce?ce(w,P,{configurable:!0,enumerable:!0,value:H,writable:!0}):w[P]=H}$n.prototype.clear=function(){this.__data__=ve?ve(null):{},this.size=0},$n.prototype.delete=function(w){var P=this.has(w)&&delete this.__data__[w];return this.size-=P?1:0,P},$n.prototype.get=function(w){var P=this.__data__;if(ve){var H=P[w];return H===n?void 0:H}return v.call(P,w)?P[w]:void 0},$n.prototype.has=function(w){var P=this.__data__;return ve?P[w]!==void 0:v.call(P,w)},$n.prototype.set=function(w,P){var H=this.__data__;return this.size+=this.has(w)?0:1,H[w]=ve&&P===void 0?n:P,this},sn.prototype.clear=function(){this.__data__=[],this.size=0},sn.prototype.delete=function(w){var P=this.__data__,H=vo(P,w);return!(H<0||(H==P.length-1?P.pop():oe.call(P,H,1),--this.size,0))},sn.prototype.get=function(w){var P=this.__data__,H=vo(P,w);return H<0?void 0:P[H][1]},sn.prototype.has=function(w){return vo(this.__data__,w)>-1},sn.prototype.set=function(w,P){var H=this.__data__,G=vo(H,w);return G<0?(++this.size,H.push([w,P])):H[G][1]=P,this},Rr.prototype.clear=function(){this.size=0,this.__data__={hash:new $n,map:new(nt||sn),string:new $n}},Rr.prototype.delete=function(w){var P=To(this,w).delete(w);return this.size-=P?1:0,P},Rr.prototype.get=function(w){return To(this,w).get(w)},Rr.prototype.has=function(w){return To(this,w).has(w)},Rr.prototype.set=function(w,P){var H=To(this,w),G=H.size;return H.set(w,P),this.size+=H.size==G?0:1,this},Ir.prototype.clear=function(){this.__data__=new sn,this.size=0},Ir.prototype.delete=function(w){var P=this.__data__,H=P.delete(w);return this.size=P.size,H},Ir.prototype.get=function(w){return this.__data__.get(w)},Ir.prototype.has=function(w){return this.__data__.has(w)},Ir.prototype.set=function(w,P){var H=this.__data__;if(H instanceof sn){var G=H.__data__;if(!nt||G.length<199)return G.push([w,P]),this.size=++H.size,this;H=this.__data__=new Rr(G)}return H.set(w,P),this.size=H.size,this};var eg=function(w,P,H){for(var G=-1,ue=Object(w),Ie=H(w),ge=Ie.length;ge--;){var rt=Ie[++G];if(P(ue[rt],rt,ue)===!1)break}return w};function Do(w){return w==null?w===void 0?"[object Undefined]":"[object Null]":le&&le in Object(w)?(function(P){var H=v.call(P,le),G=P[le];try{P[le]=void 0;var ue=!0}catch(ge){}var Ie=C.call(P);return ue&&(H?P[le]=G:delete P[le]),Ie})(w):(function(P){return C.call(P)})(w)}function ku(w){return hi(w)&&Do(w)==i}function tg(w){return!(!Yn(w)||(function(P){return!!T&&T in P})(w))&&(Ea(w)?L:a).test((function(P){if(P!=null){try{return y.call(P)}catch(H){}try{return P+""}catch(H){}}return""})(w))}function ng(w){if(!Yn(w))return(function(ue){var Ie=[];if(ue!=null)for(var ge in Object(ue))Ie.push(ge);return Ie})(w);var P=xu(w),H=[];for(var G in w)(G!="constructor"||!P&&v.call(w,G))&&H.push(G);return H}function Mu(w,P,H,G,ue){w!==P&&eg(P,function(Ie,ge){if(ue||(ue=new Ir),Yn(Ie))(function(dt,ye,je,an,ht,yr,pi){var zt=ha(dt,je),pt=ha(ye,je),Vu=pi.get(pt);if(Vu)ca(dt,je,Vu);else{var zu,At=yr?yr(zt,pt,je+"",dt,ye,pi):void 0,fi=At===void 0;if(fi){var Aa=fa(pt),ga=!Aa&&Fu(pt),$u=!Aa&&!ga&&Uu(pt);At=pt,Aa||ga||$u?fa(zt)?At=zt:hi(zu=zt)&&ma(zu)?At=(function(Fe,it){var ot=-1,Pt=Fe.length;for(it||(it=Array(Pt));++ot<Pt;)it[ot]=Fe[ot];return it})(zt):ga?(fi=!1,At=pt.slice()):$u?(fi=!1,At=(function(Fe){var it,ot,Pt=(it=Fe.buffer,ot=new it.constructor(it.byteLength),new x(ot).set(new x(it)),ot);return new Fe.constructor(Pt,Fe.byteOffset,Fe.length)})(pt)):At=[]:(function(Fe){if(!hi(Fe)||Do(Fe)!=s)return!1;var it=V(Fe);if(it===null)return!0;var ot=v.call(it,"constructor")&&it.constructor;return typeof ot=="function"&&ot instanceof ot&&y.call(ot)==N})(pt)||pa(pt)?(At=zt,pa(zt)?At=(function(Fe){return(function(it,ot,Pt){var ag=!Pt;Pt||(Pt={});for(var Yu=-1,lg=ot.length;++Yu<lg;){var Sa=ot[Yu],Io=void 0;Io===void 0&&(Io=it[Sa]),ag?ua(Pt,Sa,Io):QA(Pt,Sa,Io)}return Pt})(Fe,Bu(Fe))})(zt):Yn(zt)&&!Ea(zt)||(At=(function(Fe){return typeof Fe.constructor!="function"||xu(Fe)?{}:Re(V(Fe))})(pt))):fi=!1}fi&&(pi.set(pt,At),ht(At,pt,an,yr,pi),pi.delete(pt)),ca(dt,je,At)}})(w,P,ge,H,Mu,G,ue);else{var rt=G?G(ha(w,ge),Ie,ge+"",w,P,ue):void 0;rt===void 0&&(rt=Ie),ca(w,ge,rt)}},Bu)}function rg(w,P){return og((function(H,G,ue){return G=tt(G===void 0?H.length-1:G,0),function(){for(var Ie=arguments,ge=-1,rt=tt(Ie.length-G,0),dt=Array(rt);++ge<rt;)dt[ge]=Ie[G+ge];ge=-1;for(var ye=Array(G+1);++ge<G;)ye[ge]=Ie[ge];return ye[G]=ue(dt),(function(je,an,ht){switch(ht.length){case 0:return je.call(an);case 1:return je.call(an,ht[0]);case 2:return je.call(an,ht[0],ht[1]);case 3:return je.call(an,ht[0],ht[1],ht[2])}return je.apply(an,ht)})(H,this,ye)}})(w,P,ju),w+"")}var ig=ce?function(w,P){return ce(w,"toString",{configurable:!0,enumerable:!1,value:(H=P,function(){return H}),writable:!0});var H}:ju;function To(w,P){var H,G,ue=w.__data__;return((G=typeof(H=P))=="string"||G=="number"||G=="symbol"||G=="boolean"?H!=="__proto__":H===null)?ue[typeof P=="string"?"string":"hash"]:ue.map}function da(w,P){var H=(function(G,ue){return G==null?void 0:G[ue]})(w,P);return tg(H)?H:void 0}function Pu(w,P){var H=typeof w;return!!(P=P==null?r:P)&&(H=="number"||H!="symbol"&&l.test(w))&&w>-1&&w%1==0&&w<P}function xu(w){var P=w&&w.constructor;return w===(typeof P=="function"&&P.prototype||I)}function ha(w,P){if((P!=="constructor"||typeof w[P]!="function")&&P!="__proto__")return w[P]}var og=(function(w){var P=0,H=0;return function(){var G=Vt(),ue=16-(G-H);if(H=G,ue>0){if(++P>=800)return arguments[0]}else P=0;return w.apply(void 0,arguments)}})(ig);function Ro(w,P){return w===P||w!=w&&P!=P}var pa=ku((function(){return arguments})())?ku:function(w){return hi(w)&&v.call(w,"callee")&&!Y.call(w,"callee")},fa=Array.isArray;function ma(w){return w!=null&&Hu(w.length)&&!Ea(w)}var Fu=pe||function(){return!1};function Ea(w){if(!Yn(w))return!1;var P=Do(w);return P==o||P=="[object GeneratorFunction]"||P=="[object AsyncFunction]"||P=="[object Proxy]"}function Hu(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=r}function Yn(w){var P=typeof w;return w!=null&&(P=="object"||P=="function")}function hi(w){return w!=null&&typeof w=="object"}var Uu=S?(function(w){return function(P){return w(P)}})(S):function(w){return hi(w)&&Hu(w.length)&&!!u[Do(w)]};function Bu(w){return ma(w)?ZA(w):ng(w)}var _a,sg=(_a=function(w,P,H){Mu(w,P,H)},rg(function(w,P){var H=-1,G=P.length,ue=G>1?P[G-1]:void 0,Ie=G>2?P[2]:void 0;for(ue=_a.length>3&&typeof ue=="function"?(G--,ue):void 0,Ie&&(function(rt,dt,ye){if(!Yn(ye))return!1;var je=typeof dt;return!!(je=="number"?ma(ye)&&Pu(dt,ye.length):je=="string"&&dt in ye)&&Ro(ye[dt],rt)})(P[0],P[1],Ie)&&(ue=G<3?void 0:ue,G=1),w=Object(w);++H<G;){var ge=P[H];ge&&_a(w,ge,H,ue)}return w}));function ju(w){return w}t.exports=sg})(_l,_l.exports)),_l.exports);const kR=Ys(LR);class MR{constructor(e,n,r,i){this.backendRestClient=new wR(e,n,r,i)}async getApp(e){return(function(n){const r=(function(s,a){const l={general:{enableFileTransfers:a.includes("file_sharing"),enableLocation:a.includes("location_sharing"),enableMentions:!1,showTypingIndicators:!0,enablePresence:!1,enableVoiceRecording:!1},theme:{version:"v2",name:"default"},permissions:{messages:{delete:"own",edit:"own",reply:"all",emojiReactions:"all"},messagesCustom:{},conversations:{leave:"none",markAsUnread:"none"},conversationsCustom:{}},generalNotificationSettings:{timeout:"15"},emailSettings:{enabled:!0,subject:"{{sender.name}} wants to chat with you on {{app.name}}",replySeparator:"--- Write ABOVE THIS LINE to post a reply via email ---",unsubscribeText:"Unsubscribe from all chat emails",senderName:"{{sender.name}} (via {{app.name}})",header:`Hi {{recipient.name}},
1352
1352
  {{sender.name}} wants to chat with you on {{app.name}}:`,includeMessages:!0,inboxUrl:"{{app.custom.websiteUrl}}",inboxLinkText:"Join the chat",footer:`On behalf of {{sender.name}},
1353
1353
  The {{app.name}} team`,enableReplyToEmail:a.includes("reply_via_email"),emailThemeType:a.includes("email_templates")?"custom":"standard",emailTheme:"default_email",emailAttachmentMode:"enabledExcludingImages",htmlTemplate:`<div>
@@ -1372,7 +1372,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1372
1372
  {{app.custom.websiteUrl}} Join the chat
1373
1373
 
1374
1374
  On behalf of {{sender.name}},
1375
- The {{app.name}} team`},smsSettings:{enabled:a.includes("sms_notifications"),smsTemplate:'({{app.name}}) {{sender.name}}: "{{messages}}". Reply here: {{app.custom.websiteUrl}}',maximumSegments:"1",enableAutoOptOutText:!1,optOutText:"To stop receiving these messages, reply STOP."},suppressContactInfo:JSON.stringify({mode:"off",suppressLinks:!0,suppressEmailAddresses:!0,suppressPhoneNumbers:!0}),sameTabLinkRules:[]};return kR(l,s!=null?s:{})})(n.configuration,n.features),i=JSON.parse(r.suppressContactInfo),o={...r,suppressContactInfo:new W_(i)};return{appMetadata:{...n.appMetadata,id:n.appMetadata.id},features:n.features,role:o}})(await this.backendRestClient.get("/app",e===null?{}:{role_name:e}))}async checkIfAppExists(){return this.backendRestClient.get("/app").then(()=>!0).catch(e=>{if(e.message==="Could not find app.")return!1;throw e})}}class Br{constructor(e,n,r){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=n,this.restApiHttpUrl=r}getBokensUrl(e,n,r){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(n)}?signature=${encodeURIComponent(r!=null?r:"")}`}getRealtimeWsUrl(e,n,r,i,o){const s=encodeURIComponent(n);return this.realtimeWsApiUrl+`/${e}/realtime/${s}?talkjs-client-build=${o!=null?o:"standalone"}&talkjs-core=${r}&talkjs-client-id=${i}`}static fromHost(e){var r;const n=new Br("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return n;if(e==="@currentHost"){if(typeof location=="undefined")throw new Error("You can only use @currentHost in a browser.");e=((r=window.top)!=null?r:window).location.host}if(e.endsWith("talkjs.com")){const i=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(i){const o=i[1];return["app","cdn","api","realtime"].includes(o)?n:new Br(`wss://realtime-${o}.talkjs.com/v1`,`https://app-${o}.talkjs.com/api/v0`,`https://api-${o}.talkjs.com/v1`)}return n}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new Br(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new Br(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function If(t){return Object.values(t)}class PR{constructor(e,n,r){this.subscribedConversations={},this.store=e,this.session=n,this.restApi=r}subscribeToConversationListBaseData(){const e=[this.listenForErrors(),this.listenForAuth(),this.listenForUserAndApp(),this.listenForConversationSearch(),this.listenForMessageSearch()];return()=>e.forEach(n=>n())}subscribeToConversationList(e){var o;const{store:n,session:r}=this;re(n.type==="ConversationListStore"),(o=n.conversationListSubscription)==null||o.unsubscribe(),n.conversationListSubscription=null,n.conversationFilter$.set(e);const i=r.subscribeConversations({filter:e},s=>{wt(()=>{n.conversationsArray$.set(s);const a={};for(const l of s)a[l.id]=l;n.conversationsMap$.set(a)})});return n.conversationListSubscription=i,()=>{n.conversationListSubscription===i&&(i.unsubscribe(),n.conversationListSubscription=null)}}subscribeToChatboxData(){const e=[this.listenForErrors(),this.listenForAuth(),this.listenForUserAndApp(),()=>this.unsubscribeAllConversations()];return()=>e.forEach(n=>n())}listenForErrors(){const{store:e,session:n}=this;e.errors$.assign({unknownUser:!1,wrongAppId:!1,serverError:!1});const r=n.onError(o=>{Te.error(o.message),e.errors$.serverError.set(!0)}),i=n.currentUser.subscribe(o=>{e.errors$.unknownUser.set(o===null)});return()=>{r.unsubscribe(),i.unsubscribe()}}listenForAuth(){const{store:e,session:n}=this;return mt(r=>{let i=!0;const o=e.hasTokenFetcher$.get();e.authTokenState$.peek()!=="loading"&&e.authTokenState$.set("loading"),n._authProvider.getToken().then(()=>{i&&e.authTokenState$.set("valid")});const s=n._authProvider.onTokenRefreshFailed(()=>{i&&e.authTokenState$.set(o?"invalid":"expired")});r.onCleanup=()=>{i=!1,s()}})}listenForUserAndApp(){const{store:e,session:n,restApi:r}=this;return mt(i=>{let o=!0;const s=Symbol("ROLE_NOT_LOADED");let a=s;const l=n.currentUser.subscribe(async u=>{var c;if(o&&u){e.currentUser$.set(u);const d=(c=u.role)!=null?c:null;if(a===s||d!==a){a=d;try{const h=await r.getApp(d);if(!o)return;e.app$.set(h)}catch(h){if(!o)return;a=s,Te.error(`Failed to load app settings: ${h.message}`),e.errors$.serverError.set(!0)}}}});i.onCleanup=()=>{o=!1,l.unsubscribe()}})}subscribeTypingAndPresence(e){var r;if((r=this.unsubscribeTypingAndPresence)==null||r.call(this),!e)return;const n=[this.listenForTyping(e),this.listenForPresence(e)];this.unsubscribeTypingAndPresence=()=>{n.forEach(i=>i()),this.unsubscribeTypingAndPresence=void 0}}subscribeConversation(e){if(this.subscribedConversations[e])return void(this.subscribedConversations[e].touchedAt=Date.now());const n=[this.listenForConversation(e),this.listenForMessages(e),this.listenForParticipants(e)];this.subscribedConversations[e]={unsubscribe:()=>{n.forEach(i=>i()),delete this.subscribedConversations[e]},touchedAt:Date.now()};const r=If(this.subscribedConversations);r.length>10&&(function(o,s){return o.reduce((a,l)=>l[s]<a[s]?l:a,o[0])})(r,"touchedAt").unsubscribe()}unsubscribeAllConversations(){var e;for(const n of If(this.subscribedConversations))n.unsubscribe();(e=this.unsubscribeTypingAndPresence)==null||e.call(this),this.subscribedConversations={}}listenForMessages(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeMessages(async(o,s)=>{o&&(await n.readyForNewMessagesPromise,n.storeMessages(e,o,s))});return n.messageSubscriptions[e]=i,()=>i==null?void 0:i.unsubscribe()}listenForParticipants(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeParticipants(o=>{o&&n.state$.participants.child(e).set(o)});return()=>i==null?void 0:i.unsubscribe()}listenForConversation(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribe(async o=>{wt(()=>{o?(n.state$.unknownConversations.child(e).delete(),n.state$.conversations.child(e).set(o)):(n.state$.conversations.child(e).delete(),n.state$.unknownConversations.child(e).set(!0))})});return()=>i==null?void 0:i.unsubscribe()}listenForTyping(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeTyping(o=>{o&&n.storeTyping(e,o)});return()=>i==null?void 0:i.unsubscribe()}listenForPresence(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=n.state$.participants.child(e),o=n.state$.isUserConnected.child(e),s=mt(a=>{var c;const l=((c=i.get())!=null?c:[]).map(({user:d})=>d.id),u=l.map(d=>r.user(d).subscribeOnline(h=>{var p;o.child(d).set((p=h==null?void 0:h.isConnected)!=null?p:!1)}));wt(()=>{var m;const d=new Set(l),h=(p=(m=o.peek())!=null?m:{},Object.keys(p));var p;for(const _ of h)d.has(_)||o.child(_).delete()}),a.onCleanup=()=>{u.forEach(d=>d.unsubscribe())}});return()=>{s==null||s(),n.state$.isUserConnected.child(e).delete(),o.delete()}}listenForConversationSearch(){const{store:e,session:n}=this;re(e.type==="ConversationListStore");const r=n.searchConversations((s,a)=>{e.globalSearchState$.assign({conversationResults:s,conversationStatus:a})});e.conversationSearch=r;const i=Ap((s,a)=>{const l={conversation:a},u=s.trim();u.length?u.length>=3&&r.setQuery(u,l):r.setQuery("",l)},500),o=mt(()=>{i(e.globalSearchState$.query.get(),e.conversationFilter$.get())});return()=>{e.conversationSearch=null,o()}}listenForMessageSearch(){const{store:e,session:n}=this;re(e.type==="ConversationListStore");const r=n.searchMessages((s,a)=>{e.globalSearchState$.assign({messageResults:s,messageStatus:a})});e.messageSearch=r;const i=Ap((s,a)=>{const l={conversation:a},u=s.trim();u.length?u.length>=3&&r.setQuery(u,l):r.setQuery("",l)},500),o=mt(()=>{i(e.globalSearchState$.query.get(),e.conversationFilter$.get())});return()=>{e.messageSearch=null,o()}}}function jA(t,e){const n=e.appId,r=e.userId,i=X(void 0),o=Z(()=>{const c=i.current,d=typeof c!=typeof e.tokenFetcher?e.tokenFetcher:c;return i.current=d,d},[e.tokenFetcher]);We(()=>{t.updateThemeCustom(e.themeCustom)},[t,e.themeCustom]);const s=Z(()=>UA(),[e.appId,e.userId,e.token,o]);z(()=>{t.hasTokenFetcher$.set(!!o)},[t,o]);const a=cg.getTalkSession({host:e.host,appId:n,userId:r,token:e.token,tokenFetcher:o}),l=Z(()=>{const c=Br.fromHost(e.host);return new MR(c,n,s,a._authProvider)},[n,s,a,e.host]),u=Z(()=>new PR(t,a,l),[t,a,l]);return{session:a,restApi:l,fetcher:u}}class xR{constructor(e,n,r,i){this.state={type:"idle"},this.latestTicketId=0,this.uploads$=se([]),this.onClose=null,this.startFileUpload=async o=>{const s=this.latestTicketId;let a;if(this.state={type:"uploading",ticketId:s,content:{kind:"file",uploads:[],fileTokens:[]}},a=o?Array.isArray(o)?o:[o]:await new Promise(c=>{const d=document.createElement("input");d.type="file",d.multiple=!0,d.addEventListener("change",()=>{c([...d.files])}),d.addEventListener("cancel",()=>{c([])}),d.click()}),!a[0])return void this.cancelUpload();if(a.sort((c,d)=>c.lastModified!==d.lastModified?c.lastModified-d.lastModified:c.name.localeCompare(d.name)),!this.isTicketValid(s))return;const l=await Promise.all(a.map(FR));if(!this.isTicketValid(s))return;this.state={type:"uploading",ticketId:s,content:{kind:"file",uploads:l,fileTokens:[]}},wt(()=>{this.uploads$.set(l);for(const c of l){const d=c.file.size+","+c.file.name;this.store.state$.localFileBlobUrls.child(this.store.state$.currentConversationId.peek()).child(d).set({url:c.temporaryBlobUrl,fetching:!1})}});const u=await Promise.all(l.map((c,d)=>(async function(h,p){switch(h.type){case"video":return p.uploadVideo(h.file,h.metadata);case"audio":return p.uploadAudio(h.file,h.metadata);case"image":return p.uploadImage(h.file,h.metadata);case"file":return p.uploadFile(h.file,h.metadata);case"voice":re.unreachable()}})(c,this.session).then(h=>(this.isTicketValid(s)&&this.uploads$.child(d).state.set("uploaded"),h)).catch(()=>(this.isTicketValid(s)&&this.uploads$.child(d).state.set("error"),null))));this.isTicketValid(s)&&(this.state={type:"waitingForConfirmation",ticketId:s,content:{kind:"file",uploads:l,fileTokens:u}})},this.startLocationUpload=async()=>{const o=this.latestTicketId,s={type:"location",state:"uploading",location:null};this.state={type:"uploading",ticketId:o,content:{kind:"location",upload:s}},this.uploads$.set([s]);const a=await this.browserPermissionController.runWithPermissionCheck("geolocation",async d=>{const{permissionResult:h,location:p}=await new Promise(m=>{navigator.geolocation.getCurrentPosition(_=>{const E={latitude:_.coords.latitude,longitude:_.coords.longitude};m({permissionResult:"granted",location:E})},_=>{_.code===GeolocationPositionError.PERMISSION_DENIED?m({permissionResult:"denied",location:null}):m({permissionResult:"granted",location:null})})});return d(h),{permissionResult:h,location:p}});if(!this.isTicketValid(o))return;if(!a)return void this.cancelUpload();const{permissionResult:l,location:u}=a,c={type:"location",state:l==="granted"&&u?"uploaded":"error",location:u};this.state={type:"waitingForConfirmation",ticketId:o,content:{kind:"location",upload:c}},this.uploads$.set([c])},this.confirmUpload=()=>{if(this.state.type==="waitingForConfirmation"&&this.isTicketValid(this.state.ticketId)){if(this.state.content.kind==="file"){const o=this.state.content.fileTokens.filter(s=>s!==null);this.state.content.fileTokens.length===o.length&&this.sendFileMessages(this.state.content.uploads,o)}else this.state.content.kind==="location"&&this.state.content.upload.location&&this.sendLocationMessage(this.state.content.upload.location);this.terminate()}},this.cancelUpload=()=>{this.terminate()},this.session=e,this.store=n,this.controller=r,this.browserPermissionController=i}isTicketValid(e){return e===this.latestTicketId}sendFileMessages(e,n){for(const[r,i]of(function(o,s){return re(o.length===s.length),o.map((a,l)=>[a,s[l]])})(n,e))this.controller.sendFileMessage({fileToken:r}),this.store.fileUploads[r]=i}sendLocationMessage(e){this.controller.sendLocationMessage({location:e})}terminate(){var n;const e=this.state.type==="idle";this.latestTicketId+=1,this.state={type:"idle"},this.uploads$.set([]),e||((n=this.onClose)==null||n.call(this))}}async function FR(t){const e=t.name;if((function(r){return/\.(mp4|ts|mov|webm|ogv)$/i.test(r)})(t.name)){const r=await Al("video",t,o=>({width:o.videoWidth,height:o.videoHeight,duration:o.duration,filename:e})),i=(function(o){switch(o.name.split(".").pop()){case"ts":return"video/MP2T";case"mov":return"video/quicktime";case"webm":return"video/webm";case"ogv":return"video/ogg";default:return"video/mp4"}})(t);return{type:"video",file:t,metadata:r,temporaryBlobUrl:URL.createObjectURL(new Blob([t],{type:i})),state:"uploading"}}const n=URL.createObjectURL(t);return(function(r){return/\.(mp3|m4a|ogg|oga|opus|flac|wav)$/i.test(r)})(t.name)?{type:"audio",file:t,metadata:await Al("audio",t,r=>({duration:r.duration,filename:e})),temporaryBlobUrl:n,state:"uploading"}:(function(r){return/(gif|png|jpg|jpeg|svg|bmp|webp)$/i.test(r)})(t.name)?{type:"image",file:t,metadata:await Al("img",t,r=>({width:r.naturalWidth,height:r.naturalHeight,filename:e})),temporaryBlobUrl:n,state:"uploading"}:{type:"file",file:t,metadata:{filename:e},temporaryBlobUrl:n,state:"uploading"}}async function Al(t,e,n){const r=document.createElement(t);try{return r.src=URL.createObjectURL(e),await new Promise((i,o)=>{const s=t==="img"?"load":"loadedmetadata";r.addEventListener(s,()=>{try{i(n(r))}catch(a){o(a)}},{once:!0})})}finally{URL.revokeObjectURL(r.src)}}class HR{constructor(e){this.init=e}async runWithPermissionCheck(e,n){const{beforeBrowserPermissionPrompt:r,onMissingBrowserPermission:i}=this.init;function o(c){c==="denied"&&i({type:e})}if(!r||!await(async function(c){if(!("permissions"in navigator))return!1;try{return(await navigator.permissions.query({name:c})).state==="prompt"}catch(d){return!1}})(e))return n(c=>{o(c)});const s=Ec(),a=Ec(),l={type:e,showPrompt:async()=>(a.resolve({cancelled:!1}),await s.promise),cancel:()=>{a.resolve({cancelled:!0})}};try{r(l)}catch(c){Te.error("Your beforeBrowserPermissionPrompt callback threw an error: ",c),a.resolve({cancelled:!0})}const{cancelled:u}=await a.promise;return u?null:n(c=>{s.resolve(c),o(c)})}}function St(t,e,n){const r=X(t),i=X(n);return We(()=>{r.current=t,i.current=n}),q(o=>{r.current&&r.current(o),e&&(function(s,a,l){for(const u of l){const c=new Event(u);Object.assign(c,a),s.dispatchEvent(c)}})(e,o,i.current)},[e])}function VA(t){z(()=>{const e=window,n=t.current;if(e.cordova&&n){const r=i=>{i.target instanceof HTMLAnchorElement&&(i.preventDefault(),(function(o){const s=window;s.cordova.InAppBrowser?s.cordova.InAppBrowser.open(o,"_system"):window.open(o,"_system","location=yes")})(i.target.href))};return n.addEventListener("click",r),()=>n.removeEventListener("click",r)}},[t])}function zA(){const[t,e]=ee(!0);return z(()=>{e(!1)},[]),t}const UR=_t(function(t,e){var L,b;const{onSendMessage:n,onDeleteMessage:r,onMessageAction:i,onFocusMessage:o,onBackButtonClick:s,onMissingBrowserPermission:a,messageFieldPlaceholder:l,messageFieldSpellcheck:u,__hostElement:c}=t;z(()=>{var k;(k=t.__internalOnLoaded)==null||k.call(t)},[]);const d=zA(),h=X(c!=null?c:null);VA(h);const p=St(r,c,["deleteMessage","delete-message","deletemessage","DeleteMessage"]),m=St(n,c,["sendMessage","send-message","sendmessage","SendMessage"]),_=St(i,c,["messageAction","message-action","messageaction","MessageAction"]),E=St(o,c,["focusMessage","focus-message","focusmessage","FocusMessage"]),A=St(s,c,["backButtonClick","back-button-click","backbuttonclick","BackButtonClick"]),g=St(a,c,["browserPermissionDenied","browser-permission-denied","browserpermissiondenied","BrowserPermissionDenied"]),{store:S,controller:O,browserPermissionController:D,uploadController:I,editorInternals:R,session:y}=(function(k,x,M,U,V,$,Y){const oe=Z(()=>new mS(k.appId,k.userId),[]),{session:le,fetcher:ce}=jA(oe,k);z(()=>{const ve=ce.subscribeToChatboxData();return()=>ve()},[ce]);const pe=Z(()=>new U_(oe.state$.editor,oe.device$,oe.state$.userPermissions),[oe]),tt=Z(()=>new NR(oe,le,pe,x,M,U,V,$),[le,oe,pe,x,M,V,U,$]);pe.controller=tt;const Vt=Z(()=>new HR({beforeBrowserPermissionPrompt:k.beforeBrowserPermissionPrompt,onMissingBrowserPermission:Y}),[k.beforeBrowserPermissionPrompt,Y]),nt=Z(()=>new xR(le,oe,tt,Vt),[le,oe,tt,Vt]);return We(()=>{let ve=!0;const Re=k.conversationId||null;return oe.state$.loadingConversationId.set(Re),Re&&ce.subscribeConversation(Re),ce.subscribeTypingAndPresence(Re),js(()=>oe.canRenderUi(Re)).then(()=>{ve&&wt(()=>{oe.state$.currentConversationId.set(Re),oe.state$.referencedMessageId.set(null),oe.chatSearchState$.set("hidden")})}),()=>{ve=!1}},[oe,ce,k.conversationId]),{store:oe,controller:tt,browserPermissionController:Vt,uploadController:nt,editorInternals:pe,session:le}})(t,m,p,_,E,A,g),v=q(async()=>{const k=R.state$;if(k.isEmpty.peek()||k.atTextLimit.peek())return;const x=R.getText(),M=S.state$.referencedMessageId.peek();M&&O.setReferencedMessage(null),R.clearText(),S.state$.editor.showEmojiPicker.set(!1),await O.sendMessage({text:x,referencedMessage:M!=null?M:void 0})},[O,R,S]);z(()=>{var x;const k=(x=t.enterSendsMessage)!=null?x:!0;S.state$.enterSendsMessage.set(k),R.onEnter=k?v:void 0},[R,t.enterSendsMessage,v,S]);const T=X(void 0);z(()=>{var x;const k=(x=S.focusedMessage$.peek())==null?void 0:x.id;t.focusedMessageId!==T.current&&k!==t.focusedMessageId&&(T.current=t.focusedMessageId,O.focusMessage(t.focusedMessageId||null,!1))},[S,O,t.focusedMessageId]),z(()=>{const k=t.__hostElement;if(k)return S.focusedMessage$.onChange(({value:x})=>{var M;k.focusedMessageId=(M=x==null?void 0:x.id)!=null?M:null})},[S,t.__hostElement]),z(()=>{R.spellcheck$.set(u)},[R,u]),z(()=>{R.placeholder$.set(l)},[R,l]),Sn(e,()=>({controller:O,editorInternals:R}));const C=q(({error:k})=>f(la,{appId:t.appId,chatboxState:{type:"unexpected-error",error:k}}),[t.appId]),N=d?null:f(Ym,{fallbackRender:C,children:f(Qm.Provider,{value:R,children:f(eE.Provider,{value:S,children:f(Zm.Provider,{value:t.theme,children:f(oS.Provider,{value:D,children:f(tE.Provider,{value:O,children:f(cS.Provider,{value:I,children:f(jc.Provider,{value:y,children:f(aS.Provider,{value:{sendMessage:v},children:f(yR,{appId:t.appId,chatHeaderVisible:(L=t.chatHeaderVisible)!=null?L:!0,messageFieldVisible:(b=t.messageFieldVisible)!=null?b:!0})})})})})})})})})});return c?N:f("div",{className:"t-chatbox"+(t.className?` ${t.className}`:""),style:t.style,ref:h,children:N})});(function(t="Twemoji Country Flags",e="https://cdn.jsdelivr.net/npm/country-flag-emoji-polyfill@0.1/dist/TwemojiCountryFlags.woff2"){if(typeof window<"u"&&yd("😊")&&!yd("🇨🇭")){const n=document.createElement("style");return n.textContent=`@font-face {
1375
+ The {{app.name}} team`},smsSettings:{enabled:a.includes("sms_notifications"),smsTemplate:'({{app.name}}) {{sender.name}}: "{{messages}}". Reply here: {{app.custom.websiteUrl}}',maximumSegments:"1",enableAutoOptOutText:!1,optOutText:"To stop receiving these messages, reply STOP."},suppressContactInfo:JSON.stringify({mode:"off",suppressLinks:!0,suppressEmailAddresses:!0,suppressPhoneNumbers:!0}),sameTabLinkRules:[]};return kR(l,s!=null?s:{})})(n.configuration,n.features),i=JSON.parse(r.suppressContactInfo),o={...r,suppressContactInfo:new W_(i)};return{appMetadata:{...n.appMetadata,id:n.appMetadata.id},features:n.features,role:o}})(await this.backendRestClient.get("/app",e===null?{}:{role_name:e}))}async checkIfAppExists(){return this.backendRestClient.get("/app").then(()=>!0).catch(e=>{if(e.message==="Could not find app.")return!1;throw e})}}class Br{constructor(e,n,r){this.realtimeWsApiUrl=e,this.internalHttpApiUrl=n,this.restApiHttpUrl=r}getBokensUrl(e,n,r){return this.internalHttpApiUrl+`/${e}/bokens/${encodeURIComponent(n)}?signature=${encodeURIComponent(r!=null?r:"")}`}getRealtimeWsUrl(e,n,r,i,o){const s=encodeURIComponent(n);return this.realtimeWsApiUrl+`/${e}/realtime/${s}?talkjs-client-build=${o!=null?o:"standalone"}&talkjs-core=${r}&talkjs-client-id=${i}`}static fromHost(e){var r;const n=new Br("wss://realtime.talkjs.com/v1","https://app.talkjs.com/api/v0","https://api.talkjs.com/v1");if(!e)return n;if(e==="@currentHost"){if(typeof location=="undefined")throw new Error("You can only use @currentHost in a browser.");e=((r=window.top)!=null?r:window).location.host}if(e.endsWith("talkjs.com")){const i=e.match(/^(?:\w+-)?([^.]+)\.talkjs\.com$/);if(i){const o=i[1];return["app","cdn","api","realtime"].includes(o)?n:new Br(`wss://realtime-${o}.talkjs.com/v1`,`https://app-${o}.talkjs.com/api/v0`,`https://api-${o}.talkjs.com/v1`)}return n}return e.includes("localhost")||e.includes("localtest.me")||/^\d+\.\d+\.\d+\.\d+(:\d+)?$/.test(e)?new Br(`ws://${e}/public_api/v1`,`http://${e}/api/v0`,`http://${e}/public_api/v1`):new Br(`wss://${e}/public_api/v1`,`https://${e}/api/v0`,`https://${e}/public_api/v1`)}}function If(t){return Object.values(t)}class PR{constructor(e,n,r){this.subscribedConversations={},this.store=e,this.session=n,this.restApi=r}subscribeToConversationListBaseData(){const e=[this.listenForErrors(),this.listenForAuth(),this.listenForUserAndApp(),this.listenForConversationSearch(),this.listenForMessageSearch()];return()=>e.forEach(n=>n())}subscribeToConversationList(e){var o;const{store:n,session:r}=this;re(n.type==="ConversationListStore"),(o=n.conversationListSubscription)==null||o.unsubscribe(),n.conversationListSubscription=null,n.conversationFilter$.set(e);const i=r.subscribeConversations({filter:e},s=>{wt(()=>{n.conversationsArray$.set(s);const a={};for(const l of s)a[l.id]=l;n.conversationsMap$.set(a)})});return n.conversationListSubscription=i,()=>{n.conversationListSubscription===i&&(i.unsubscribe(),n.conversationListSubscription=null)}}subscribeToChatboxData(){const e=[this.listenForErrors(),this.listenForAuth(),this.listenForUserAndApp(),()=>this.unsubscribeAllConversations()];return()=>e.forEach(n=>n())}listenForErrors(){const{store:e,session:n}=this;e.errors$.assign({unknownUser:!1,wrongAppId:!1,serverError:!1});const r=n.onError(o=>{Te.error(o.message),e.errors$.serverError.set(!0)}),i=n.currentUser.subscribe(o=>{e.errors$.unknownUser.set(o===null)});return()=>{r.unsubscribe(),i.unsubscribe()}}listenForAuth(){const{store:e,session:n}=this;return mt(r=>{let i=!0;const o=e.hasTokenFetcher$.get();e.authTokenState$.peek()!=="loading"&&e.authTokenState$.set("loading"),n._authProvider.getToken().then(()=>{i&&e.authTokenState$.set("valid")});const s=n._authProvider.onTokenRefreshFailed(()=>{i&&e.authTokenState$.set(o?"invalid":"expired")});r.onCleanup=()=>{i=!1,s()}})}listenForUserAndApp(){const{store:e,session:n,restApi:r}=this;return mt(i=>{let o=!0;const s=Symbol("ROLE_NOT_LOADED");let a=s;const l=n.currentUser.subscribe(async u=>{var c;if(o&&u){e.currentUser$.set(u);const d=(c=u.role)!=null?c:null;if(a===s||d!==a){a=d;try{const h=await r.getApp(d);if(!o)return;e.app$.set(h)}catch(h){if(!o)return;a=s,Te.error(`Failed to load app settings: ${h.message}`),e.errors$.serverError.set(!0)}}}});i.onCleanup=()=>{o=!1,l.unsubscribe()}})}subscribeTypingAndPresence(e){var r;if((r=this.unsubscribeTypingAndPresence)==null||r.call(this),!e)return;const n=[this.listenForTyping(e),this.listenForPresence(e)];this.unsubscribeTypingAndPresence=()=>{n.forEach(i=>i()),this.unsubscribeTypingAndPresence=void 0}}subscribeConversation(e){if(this.subscribedConversations[e])return void(this.subscribedConversations[e].touchedAt=Date.now());const n=[this.listenForConversation(e),this.listenForMessages(e),this.listenForParticipants(e)];this.subscribedConversations[e]={unsubscribe:()=>{n.forEach(i=>i()),delete this.subscribedConversations[e]},touchedAt:Date.now()};const r=If(this.subscribedConversations);r.length>10&&(function(o,s){return o.reduce((a,l)=>l[s]<a[s]?l:a,o[0])})(r,"touchedAt").unsubscribe()}unsubscribeAllConversations(){var e;for(const n of If(this.subscribedConversations))n.unsubscribe();(e=this.unsubscribeTypingAndPresence)==null||e.call(this),this.subscribedConversations={}}listenForMessages(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeMessages(async(o,s)=>{o&&(await n.readyForNewMessagesPromise,n.storeMessages(e,o,s))});return n.messageSubscriptions[e]=i,()=>i==null?void 0:i.unsubscribe()}listenForParticipants(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeParticipants(o=>{o&&n.state$.participants.child(e).set(o)});return()=>i==null?void 0:i.unsubscribe()}listenForConversation(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribe(async o=>{wt(()=>{o?(n.state$.unknownConversations.child(e).delete(),n.state$.conversations.child(e).set(o)):(n.state$.conversations.child(e).delete(),n.state$.unknownConversations.child(e).set(!0))})});return()=>i==null?void 0:i.unsubscribe()}listenForTyping(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=r.conversation(e).subscribeTyping(o=>{o&&n.storeTyping(e,o)});return()=>i==null?void 0:i.unsubscribe()}listenForPresence(e){const{store:n,session:r}=this;re(n.type==="ChatboxStore");const i=n.state$.participants.child(e),o=n.state$.isUserConnected.child(e),s=mt(a=>{var c;const l=((c=i.get())!=null?c:[]).map(({user:d})=>d.id),u=l.map(d=>r.user(d).subscribeOnline(h=>{var p;o.child(d).set((p=h==null?void 0:h.isConnected)!=null?p:!1)}));wt(()=>{var m;const d=new Set(l),h=(p=(m=o.peek())!=null?m:{},Object.keys(p));var p;for(const _ of h)d.has(_)||o.child(_).delete()}),a.onCleanup=()=>{u.forEach(d=>d.unsubscribe())}});return()=>{s==null||s(),n.state$.isUserConnected.child(e).delete(),o.delete()}}listenForConversationSearch(){const{store:e,session:n}=this;re(e.type==="ConversationListStore");const r=n.searchConversations((s,a)=>{e.globalSearchState$.assign({conversationResults:s,conversationStatus:a})});e.conversationSearch=r;const i=Ap((s,a)=>{const l={conversation:a},u=s.trim();u.length?u.length>=3&&r.setQuery(u,l):r.setQuery("",l)},500),o=mt(()=>{i(e.globalSearchState$.query.get(),e.conversationFilter$.get())});return()=>{e.conversationSearch=null,o()}}listenForMessageSearch(){const{store:e,session:n}=this;re(e.type==="ConversationListStore");const r=n.searchMessages((s,a)=>{e.globalSearchState$.assign({messageResults:s,messageStatus:a})});e.messageSearch=r;const i=Ap((s,a)=>{const l={conversation:a},u=s.trim();u.length?u.length>=3&&r.setQuery(u,l):r.setQuery("",l)},500),o=mt(()=>{i(e.globalSearchState$.query.get(),e.conversationFilter$.get())});return()=>{e.messageSearch=null,o()}}}function jA(t,e){const n=e.appId,r=e.userId,i=X(void 0),o=Z(()=>{const c=i.current,d=typeof c!=typeof e.tokenFetcher?e.tokenFetcher:c;return i.current=d,d},[e.tokenFetcher]);We(()=>{t.updateThemeCustom(e.themeCustom)},[t,e.themeCustom]);const s=Z(()=>UA(),[e.appId,e.userId,e.token,o]);z(()=>{t.hasTokenFetcher$.set(!!o)},[t,o]);const a=cg.getTalkSession({host:e.host,appId:n,userId:r,token:e.token,tokenFetcher:o}),l=Z(()=>{const c=Br.fromHost(e.host);return new MR(c,n,s,a._authProvider)},[n,s,a,e.host]),u=Z(()=>new PR(t,a,l),[t,a,l]);return{session:a,restApi:l,fetcher:u}}class xR{constructor(e,n,r,i){this.state={type:"idle"},this.inputElement=null,this.latestTicketId=0,this.uploads$=se([]),this.onClose=null,this.onInputChange=()=>{this.resolveFiles([...this.inputElement.files])},this.onInputCancel=()=>{this.resolveFiles([])},this.startFileUpload=async o=>{const s=this.latestTicketId;let a;if(this.state={type:"uploading",ticketId:s,content:{kind:"file",uploads:[],fileTokens:[]}},a=o?Array.isArray(o)?o:[o]:await new Promise(c=>{var d;this.resolveFiles=c,(d=this.inputElement)==null||d.click()}),!a[0])return void this.cancelUpload();if(a.sort((c,d)=>c.lastModified!==d.lastModified?c.lastModified-d.lastModified:c.name.localeCompare(d.name)),!this.isTicketValid(s))return;const l=await Promise.all(a.map(FR));if(!this.isTicketValid(s))return;this.state={type:"uploading",ticketId:s,content:{kind:"file",uploads:l,fileTokens:[]}},wt(()=>{this.uploads$.set(l);for(const c of l){const d=c.file.size+","+c.file.name;this.store.state$.localFileBlobUrls.child(this.store.state$.currentConversationId.peek()).child(d).set({url:c.temporaryBlobUrl,fetching:!1})}});const u=await Promise.all(l.map((c,d)=>(async function(h,p){switch(h.type){case"video":return p.uploadVideo(h.file,h.metadata);case"audio":return p.uploadAudio(h.file,h.metadata);case"image":return p.uploadImage(h.file,h.metadata);case"file":return p.uploadFile(h.file,h.metadata);case"voice":re.unreachable()}})(c,this.session).then(h=>(this.isTicketValid(s)&&this.uploads$.child(d).state.set("uploaded"),h)).catch(()=>(this.isTicketValid(s)&&this.uploads$.child(d).state.set("error"),null))));this.isTicketValid(s)&&(this.state={type:"waitingForConfirmation",ticketId:s,content:{kind:"file",uploads:l,fileTokens:u}})},this.startLocationUpload=async()=>{const o=this.latestTicketId,s={type:"location",state:"uploading",location:null};this.state={type:"uploading",ticketId:o,content:{kind:"location",upload:s}},this.uploads$.set([s]);const a=await this.browserPermissionController.runWithPermissionCheck("geolocation",async d=>{const{permissionResult:h,location:p}=await new Promise(m=>{navigator.geolocation.getCurrentPosition(_=>{const E={latitude:_.coords.latitude,longitude:_.coords.longitude};m({permissionResult:"granted",location:E})},_=>{_.code===GeolocationPositionError.PERMISSION_DENIED?m({permissionResult:"denied",location:null}):m({permissionResult:"granted",location:null})})});return d(h),{permissionResult:h,location:p}});if(!this.isTicketValid(o))return;if(!a)return void this.cancelUpload();const{permissionResult:l,location:u}=a,c={type:"location",state:l==="granted"&&u?"uploaded":"error",location:u};this.state={type:"waitingForConfirmation",ticketId:o,content:{kind:"location",upload:c}},this.uploads$.set([c])},this.confirmUpload=()=>{if(this.state.type==="waitingForConfirmation"&&this.isTicketValid(this.state.ticketId)){if(this.state.content.kind==="file"){const o=this.state.content.fileTokens.filter(s=>s!==null);this.state.content.fileTokens.length===o.length&&this.sendFileMessages(this.state.content.uploads,o)}else this.state.content.kind==="location"&&this.state.content.upload.location&&this.sendLocationMessage(this.state.content.upload.location);this.terminate()}},this.cancelUpload=()=>{this.terminate()},this.session=e,this.store=n,this.controller=r,this.browserPermissionController=i}isTicketValid(e){return e===this.latestTicketId}sendFileMessages(e,n){for(const[r,i]of(function(o,s){return re(o.length===s.length),o.map((a,l)=>[a,s[l]])})(n,e))this.controller.sendFileMessage({fileToken:r}),this.store.fileUploads[r]=i}sendLocationMessage(e){this.controller.sendLocationMessage({location:e})}setInputElement(e){this.inputElement=e}terminate(){var n;const e=this.state.type==="idle";this.latestTicketId+=1,this.state={type:"idle"},this.uploads$.set([]),e||((n=this.onClose)==null||n.call(this))}}async function FR(t){const e=t.name;if((function(r){return/\.(mp4|ts|mov|webm|ogv)$/i.test(r)})(t.name)){const r=await Al("video",t,o=>({width:o.videoWidth,height:o.videoHeight,duration:o.duration,filename:e})),i=(function(o){switch(o.name.split(".").pop()){case"ts":return"video/MP2T";case"mov":return"video/quicktime";case"webm":return"video/webm";case"ogv":return"video/ogg";default:return"video/mp4"}})(t);return{type:"video",file:t,metadata:r,temporaryBlobUrl:URL.createObjectURL(new Blob([t],{type:i})),state:"uploading"}}const n=URL.createObjectURL(t);return(function(r){return/\.(mp3|m4a|ogg|oga|opus|flac|wav)$/i.test(r)})(t.name)?{type:"audio",file:t,metadata:await Al("audio",t,r=>({duration:r.duration,filename:e})),temporaryBlobUrl:n,state:"uploading"}:(function(r){return/(gif|png|jpg|jpeg|svg|bmp|webp)$/i.test(r)})(t.name)?{type:"image",file:t,metadata:await Al("img",t,r=>({width:r.naturalWidth,height:r.naturalHeight,filename:e})),temporaryBlobUrl:n,state:"uploading"}:{type:"file",file:t,metadata:{filename:e},temporaryBlobUrl:n,state:"uploading"}}async function Al(t,e,n){const r=document.createElement(t);try{return r.src=URL.createObjectURL(e),await new Promise((i,o)=>{const s=t==="img"?"load":"loadedmetadata";r.addEventListener(s,()=>{try{i(n(r))}catch(a){o(a)}},{once:!0})})}finally{URL.revokeObjectURL(r.src)}}class HR{constructor(e){this.init=e}async runWithPermissionCheck(e,n){const{beforeBrowserPermissionPrompt:r,onMissingBrowserPermission:i}=this.init;function o(c){c==="denied"&&i({type:e})}if(!r||!await(async function(c){if(!("permissions"in navigator))return!1;try{return(await navigator.permissions.query({name:c})).state==="prompt"}catch(d){return!1}})(e))return n(c=>{o(c)});const s=Ec(),a=Ec(),l={type:e,showPrompt:async()=>(a.resolve({cancelled:!1}),await s.promise),cancel:()=>{a.resolve({cancelled:!0})}};try{r(l)}catch(c){Te.error("Your beforeBrowserPermissionPrompt callback threw an error: ",c),a.resolve({cancelled:!0})}const{cancelled:u}=await a.promise;return u?null:n(c=>{s.resolve(c),o(c)})}}function St(t,e,n){const r=X(t),i=X(n);return We(()=>{r.current=t,i.current=n}),q(o=>{r.current&&r.current(o),e&&(function(s,a,l){for(const u of l){const c=new Event(u);Object.assign(c,a),s.dispatchEvent(c)}})(e,o,i.current)},[e])}function VA(t){z(()=>{const e=window,n=t.current;if(e.cordova&&n){const r=i=>{i.target instanceof HTMLAnchorElement&&(i.preventDefault(),(function(o){const s=window;s.cordova.InAppBrowser?s.cordova.InAppBrowser.open(o,"_system"):window.open(o,"_system","location=yes")})(i.target.href))};return n.addEventListener("click",r),()=>n.removeEventListener("click",r)}},[t])}function zA(){const[t,e]=ee(!0);return z(()=>{e(!1)},[]),t}const UR=_t(function(t,e){var L,b;const{onSendMessage:n,onDeleteMessage:r,onMessageAction:i,onFocusMessage:o,onBackButtonClick:s,onMissingBrowserPermission:a,messageFieldPlaceholder:l,messageFieldSpellcheck:u,__hostElement:c}=t;z(()=>{var k;(k=t.__internalOnLoaded)==null||k.call(t)},[]);const d=zA(),h=X(c!=null?c:null);VA(h);const p=St(r,c,["deleteMessage","delete-message","deletemessage","DeleteMessage"]),m=St(n,c,["sendMessage","send-message","sendmessage","SendMessage"]),_=St(i,c,["messageAction","message-action","messageaction","MessageAction"]),E=St(o,c,["focusMessage","focus-message","focusmessage","FocusMessage"]),A=St(s,c,["backButtonClick","back-button-click","backbuttonclick","BackButtonClick"]),g=St(a,c,["browserPermissionDenied","browser-permission-denied","browserpermissiondenied","BrowserPermissionDenied"]),{store:S,controller:O,browserPermissionController:D,uploadController:I,editorInternals:R,session:y}=(function(k,x,M,U,V,$,Y){const oe=Z(()=>new mS(k.appId,k.userId),[]),{session:le,fetcher:ce}=jA(oe,k);z(()=>{const ve=ce.subscribeToChatboxData();return()=>ve()},[ce]);const pe=Z(()=>new U_(oe.state$.editor,oe.device$,oe.state$.userPermissions),[oe]),tt=Z(()=>new NR(oe,le,pe,x,M,U,V,$),[le,oe,pe,x,M,V,U,$]);pe.controller=tt;const Vt=Z(()=>new HR({beforeBrowserPermissionPrompt:k.beforeBrowserPermissionPrompt,onMissingBrowserPermission:Y}),[k.beforeBrowserPermissionPrompt,Y]),nt=Z(()=>new xR(le,oe,tt,Vt),[le,oe,tt,Vt]);return We(()=>{let ve=!0;const Re=k.conversationId||null;return oe.state$.loadingConversationId.set(Re),Re&&ce.subscribeConversation(Re),ce.subscribeTypingAndPresence(Re),js(()=>oe.canRenderUi(Re)).then(()=>{ve&&wt(()=>{oe.state$.currentConversationId.set(Re),oe.state$.referencedMessageId.set(null),oe.chatSearchState$.set("hidden")})}),()=>{ve=!1}},[oe,ce,k.conversationId]),{store:oe,controller:tt,browserPermissionController:Vt,uploadController:nt,editorInternals:pe,session:le}})(t,m,p,_,E,A,g),v=q(async()=>{const k=R.state$;if(k.isEmpty.peek()||k.atTextLimit.peek())return;const x=R.getText(),M=S.state$.referencedMessageId.peek();M&&O.setReferencedMessage(null),R.clearText(),S.state$.editor.showEmojiPicker.set(!1),await O.sendMessage({text:x,referencedMessage:M!=null?M:void 0})},[O,R,S]);z(()=>{var x;const k=(x=t.enterSendsMessage)!=null?x:!0;S.state$.enterSendsMessage.set(k),R.onEnter=k?v:void 0},[R,t.enterSendsMessage,v,S]);const T=X(void 0);z(()=>{var x;const k=(x=S.focusedMessage$.peek())==null?void 0:x.id;t.focusedMessageId!==T.current&&k!==t.focusedMessageId&&(T.current=t.focusedMessageId,O.focusMessage(t.focusedMessageId||null,!1))},[S,O,t.focusedMessageId]),z(()=>{const k=t.__hostElement;if(k)return S.focusedMessage$.onChange(({value:x})=>{var M;k.focusedMessageId=(M=x==null?void 0:x.id)!=null?M:null})},[S,t.__hostElement]),z(()=>{R.spellcheck$.set(u)},[R,u]),z(()=>{R.placeholder$.set(l)},[R,l]),Sn(e,()=>({controller:O,editorInternals:R}));const C=q(({error:k})=>f(la,{appId:t.appId,chatboxState:{type:"unexpected-error",error:k}}),[t.appId]),N=d?null:f(Ym,{fallbackRender:C,children:f(Qm.Provider,{value:R,children:f(eE.Provider,{value:S,children:f(Zm.Provider,{value:t.theme,children:f(oS.Provider,{value:D,children:f(tE.Provider,{value:O,children:f(cS.Provider,{value:I,children:f(jc.Provider,{value:y,children:f(aS.Provider,{value:{sendMessage:v},children:f(yR,{appId:t.appId,chatHeaderVisible:(L=t.chatHeaderVisible)!=null?L:!0,messageFieldVisible:(b=t.messageFieldVisible)!=null?b:!0})})})})})})})})})});return c?N:f("div",{className:"t-chatbox"+(t.className?` ${t.className}`:""),style:t.style,ref:h,children:N})});(function(t="Twemoji Country Flags",e="https://cdn.jsdelivr.net/npm/country-flag-emoji-polyfill@0.1/dist/TwemojiCountryFlags.woff2"){if(typeof window<"u"&&yd("😊")&&!yd("🇨🇭")){const n=document.createElement("style");return n.textContent=`@font-face {
1376
1376
  font-family: "${t}";
1377
1377
  unicode-range: U+1F1E6-1F1FF, U+1F3F4, U+E0062-E0063, U+E0065, U+E0067,
1378
1378
  U+E006C, U+E006E, U+E0073-E0074, U+E0077, U+E007F;
package/default.js CHANGED
@@ -17102,79 +17102,84 @@ function MA({ containerRef: t }) {
17102
17102
  }
17103
17103
  function TR({ appId: t, chatHeaderVisible: e, messageFieldVisible: n }) {
17104
17104
  const r = co(), i = (function() {
17105
- const E = ae(), A = ct(() => {
17106
- const O = E.errors$.get(), D = E.authTokenState$.get(), I = E.state$.loadingConversationId.get(), R = E.state$.currentConversationId.get();
17107
- return O.serverError ? "server-error" : O.wrongAppId ? "wrong-app-id" : D === "loading" || D === "idle" ? "loading-token" : D === "invalid" ? "invalid-token" : D === "expired" ? "expired-token" : D === "valid" ? O.unknownUser ? "unknown-user" : I && E.state$.unknownConversations.child(I).get() ? "loading-conv-failed" : E.canRenderUi(I) || R !== I && E.canRenderUi(R) ? "loaded" : "loading-data" : void re.unreachable();
17108
- }), g = ct({ type: "loading" });
17109
- zi((O) => {
17110
- const D = A.get(), I = E.state$.currentConversationId.get(), R = E.extUserId$.get(), y = E.appId$.get();
17111
- function v(T) {
17112
- g.set({ type: "loading" });
17113
- const C = setTimeout(() => {
17114
- g.set(T);
17105
+ const A = ae(), g = ct(() => {
17106
+ const D = A.errors$.get(), I = A.authTokenState$.get(), R = A.state$.loadingConversationId.get(), y = A.state$.currentConversationId.get();
17107
+ return D.serverError ? "server-error" : D.wrongAppId ? "wrong-app-id" : I === "loading" || I === "idle" ? "loading-token" : I === "invalid" ? "invalid-token" : I === "expired" ? "expired-token" : I === "valid" ? D.unknownUser ? "unknown-user" : R && A.state$.unknownConversations.child(R).get() ? "loading-conv-failed" : A.canRenderUi(R) || y !== R && A.canRenderUi(y) ? "loaded" : "loading-data" : void re.unreachable();
17108
+ }), S = ct({ type: "loading" });
17109
+ zi((D) => {
17110
+ const I = g.get(), R = A.state$.currentConversationId.get(), y = A.extUserId$.get(), v = A.appId$.get();
17111
+ function T(C) {
17112
+ S.set({ type: "loading" });
17113
+ const N = setTimeout(() => {
17114
+ S.set(C);
17115
17115
  }, 5e3);
17116
- return () => clearTimeout(C);
17116
+ return () => clearTimeout(N);
17117
17117
  }
17118
- switch (D) {
17118
+ switch (I) {
17119
17119
  case "invalid-token":
17120
- g.set({ type: "auth-failed" });
17120
+ S.set({ type: "auth-failed" });
17121
17121
  break;
17122
17122
  case "expired-token":
17123
- g.set({ type: "expired-token" });
17123
+ S.set({ type: "expired-token" });
17124
17124
  break;
17125
17125
  case "wrong-app-id":
17126
- g.set({ type: "wrong-app-id", appId: y });
17126
+ S.set({ type: "wrong-app-id", appId: v });
17127
17127
  break;
17128
17128
  case "server-error":
17129
- g.set({ type: "server-error" });
17129
+ S.set({ type: "server-error" });
17130
17130
  break;
17131
17131
  case "loading-data":
17132
17132
  case "loading-token":
17133
- g.set({ type: "loading" });
17133
+ S.set({ type: "loading" });
17134
17134
  break;
17135
17135
  case "loaded":
17136
- g.set({ type: "loaded", conversationId: I, userId: R });
17136
+ S.set({ type: "loaded", conversationId: R, userId: y });
17137
17137
  break;
17138
17138
  case "loading-conv-failed":
17139
- O.onCleanup = v({ type: "inaccessible-conversation", userId: R, conversationId: I });
17139
+ D.onCleanup = T({ type: "inaccessible-conversation", userId: y, conversationId: R });
17140
17140
  break;
17141
17141
  case "unknown-user":
17142
- O.onCleanup = v({ type: "unknown-user", userId: R });
17142
+ D.onCleanup = T({ type: "unknown-user", userId: y });
17143
17143
  break;
17144
17144
  default:
17145
- re.never(D);
17145
+ re.never(I);
17146
17146
  }
17147
17147
  });
17148
- const S = ct({ type: "loading" });
17149
- return zi((O) => {
17150
- if (g.type.get() === "loading") {
17151
- S.set({ type: "invisible-loading" });
17152
- const D = setTimeout(() => {
17153
- S.set({ type: "loading" });
17148
+ const O = ct({ type: "loading" });
17149
+ return zi((D) => {
17150
+ if (S.type.get() === "loading") {
17151
+ O.set({ type: "invisible-loading" });
17152
+ const I = setTimeout(() => {
17153
+ O.set({ type: "loading" });
17154
17154
  }, 1e3);
17155
- O.onCleanup = () => {
17156
- clearTimeout(D);
17155
+ D.onCleanup = () => {
17156
+ clearTimeout(I);
17157
17157
  };
17158
- } else S.set(g.get());
17159
- }), J(S);
17160
- })(), o = jm();
17158
+ } else O.set(S.get());
17159
+ }), J(O);
17160
+ })(), o = jm(), s = X(null);
17161
17161
  z(() => {
17162
+ const A = s.current;
17163
+ return o.setInputElement(A), A == null || A.addEventListener("change", o.onInputChange), A == null || A.addEventListener("cancel", o.onInputCancel), () => {
17164
+ o.setInputElement(null), A == null || A.removeEventListener("change", o.onInputChange), A == null || A.removeEventListener("cancel", o.onInputCancel);
17165
+ };
17166
+ }), z(() => {
17162
17167
  r.uploadFile = o.startFileUpload, o.onClose = () => {
17163
17168
  r.focus();
17164
17169
  };
17165
17170
  }, [r, o]);
17166
- const [s, a] = ee(!1), l = ae(), u = J(() => !!l.app$.get() && l.state$.userPermissions.canShareFile.get()), c = J(() => o.uploads$.get().length > 0), d = u && !c;
17171
+ const [a, l] = ee(!1), u = ae(), c = J(() => !!u.app$.get() && u.state$.userPermissions.canShareFile.get()), d = J(() => o.uploads$.get().length > 0), h = c && !d;
17167
17172
  z(() => {
17168
- i.type === "loaded" ? l.renderedConversationId$.set(i.conversationId) : l.renderedConversationId$.set(void 0);
17169
- }, [i, l]);
17170
- const h = q((E) => {
17171
- o.startFileUpload([...E.dataTransfer.files]), E.preventDefault(), a(!1);
17172
- }, [o]), p = q((E) => {
17173
- E.preventDefault(), E.dataTransfer.types.includes("Files") && a(!0);
17174
- }, []), m = q((E) => {
17175
- E.preventDefault(), a(!1);
17176
- }, []), _ = X(null);
17177
- return uu(), i.type === "invisible-loading" ? f(ie, {}) : i.type === "loading" ? f(NA, {}) : i.type === "inaccessible-conversation" ? f(hR, {}) : i.type === "unknown-user" || i.type === "auth-failed" || i.type === "wrong-app-id" || i.type === "server-error" || i.type === "unexpected-error" ? f(sa, { appId: t, chatboxState: i }) : i.type == "expired-token" ? f(bA, {}) : i.type === "loaded" ? i.conversationId === null ? f(DR, {}) : f("div", { className: "t-chatbox-content", onDragOver: d ? p : void 0, onDragLeave: d ? m : void 0, onDrop: d ? h : void 0, "t-menu-boundary": "root", ref: _, children: [e && f(SR, {}), f(OR, {}), f(cR, { conversationId: i.conversationId }), f(vR, {}), n && f(CA, { attachFile: o.startFileUpload, shareLocation: o.startLocationUpload }), c && f(pR, {}), s && f(wA, { className: "t-drop-overlay", children: f(B, { type: "attachment" }) }), f(MA, { containerRef: _ })] }) : f(ie, {});
17173
+ i.type === "loaded" ? u.renderedConversationId$.set(i.conversationId) : u.renderedConversationId$.set(void 0);
17174
+ }, [i, u]);
17175
+ const p = q((A) => {
17176
+ o.startFileUpload([...A.dataTransfer.files]), A.preventDefault(), l(!1);
17177
+ }, [o]), m = q((A) => {
17178
+ A.preventDefault(), A.dataTransfer.types.includes("Files") && l(!0);
17179
+ }, []), _ = q((A) => {
17180
+ A.preventDefault(), l(!1);
17181
+ }, []), E = X(null);
17182
+ return uu(), i.type === "invisible-loading" ? f(ie, {}) : i.type === "loading" ? f(NA, {}) : i.type === "inaccessible-conversation" ? f(hR, {}) : i.type === "unknown-user" || i.type === "auth-failed" || i.type === "wrong-app-id" || i.type === "server-error" || i.type === "unexpected-error" ? f(sa, { appId: t, chatboxState: i }) : i.type == "expired-token" ? f(bA, {}) : i.type === "loaded" ? i.conversationId === null ? f(DR, {}) : f("div", { className: "t-chatbox-content", onDragOver: h ? m : void 0, onDragLeave: h ? _ : void 0, onDrop: h ? p : void 0, "t-menu-boundary": "root", ref: E, children: [e && f(SR, {}), f(OR, {}), f(cR, { conversationId: i.conversationId }), f(vR, {}), n && f(CA, { attachFile: o.startFileUpload, shareLocation: o.startLocationUpload }), d && f(pR, {}), a && f(wA, { className: "t-drop-overlay", children: f(B, { type: "attachment" }) }), f("input", { ref: s, type: "file", multiple: !0, style: { display: "none" } }), f(MA, { containerRef: E })] }) : f(ie, {});
17178
17183
  }
17179
17184
  const RR = () => !0;
17180
17185
  async function _u(t, e, { initialDelay: n, maxDelay: r, log: i, shouldRetry: o = RR }) {
@@ -18131,16 +18136,16 @@ function FA(t, e) {
18131
18136
  }
18132
18137
  class kR {
18133
18138
  constructor(e, n, r, i) {
18134
- this.state = { type: "idle" }, this.latestTicketId = 0, this.uploads$ = se([]), this.onClose = null, this.startFileUpload = async (o) => {
18139
+ this.state = { type: "idle" }, this.inputElement = null, this.latestTicketId = 0, this.uploads$ = se([]), this.onClose = null, this.onInputChange = () => {
18140
+ this.resolveFiles([...this.inputElement.files]);
18141
+ }, this.onInputCancel = () => {
18142
+ this.resolveFiles([]);
18143
+ }, this.startFileUpload = async (o) => {
18135
18144
  const s = this.latestTicketId;
18136
18145
  let a;
18137
18146
  if (this.state = { type: "uploading", ticketId: s, content: { kind: "file", uploads: [], fileTokens: [] } }, a = o ? Array.isArray(o) ? o : [o] : await new Promise((c) => {
18138
- const d = document.createElement("input");
18139
- d.type = "file", d.multiple = !0, d.addEventListener("change", () => {
18140
- c([...d.files]);
18141
- }), d.addEventListener("cancel", () => {
18142
- c([]);
18143
- }), d.click();
18147
+ var d;
18148
+ this.resolveFiles = c, (d = this.inputElement) == null || d.click();
18144
18149
  }), !a[0]) return void this.cancelUpload();
18145
18150
  if (a.sort((c, d) => c.lastModified !== d.lastModified ? c.lastModified - d.lastModified : c.name.localeCompare(d.name)), !this.isTicketValid(s)) return;
18146
18151
  const l = await Promise.all(a.map(MR));
@@ -18208,6 +18213,9 @@ class kR {
18208
18213
  sendLocationMessage(e) {
18209
18214
  this.controller.sendLocationMessage({ location: e });
18210
18215
  }
18216
+ setInputElement(e) {
18217
+ this.inputElement = e;
18218
+ }
18211
18219
  terminate() {
18212
18220
  var n;
18213
18221
  const e = this.state.type === "idle";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talkjs/web-components",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "bugs": {
5
5
  "url": "https://talkjs.com/?chat"
6
6
  },