useyuva 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/chat.js CHANGED
@@ -106,4 +106,4 @@ import{resolveLocale,catalogFor,translatePlain}from"./index-c6q8br7d.js";import{
106
106
  block-size: 100%;
107
107
  min-block-size: 320px;
108
108
  }
109
- `,chatIcon='<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z"/></svg>',closeIcon='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',scriptSrc=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";class YuvaChatElement extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",scriptSrc||location.href).href);#root;#launcher=null;#badge=null;#panel;#controller=null;#messages={};#open=!1;#unread=0;#identity=null;#refused=!1;constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#panel=document.createElement("section"),this.#panel.className="panel",this.#panel.setAttribute("role","dialog"),this.#panel.hidden=!0,this.#panel.addEventListener("keydown",(event)=>{if(event.key==="Escape"&&this.layout==="launcher")this.close()})}get layout(){return this.getAttribute("layout")==="embedded"?"embedded":"launcher"}get channel(){return this.getAttribute("channel")}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}get locale(){return resolveLocale(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#open}get unread(){return this.#unread}setIdentityToken(source){if(this.#identity=source,this.#controller)this.#controller.then((controller)=>controller.identityChanged())}async signOut(){if(this.#identity=null,this.removeAttribute("identity-token"),this.#controller)await(await this.#controller).signOut()}async rate(conversationId,rating,comment){return(await this.#ensureController()).rate(conversationId,rating,comment)}connectedCallback(){this.#render();let channel=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!channel)return;let stored=readStored(channel);if(stored.launcher)this.#applyLauncher(stored.launcher);let idle=()=>{if(!this.isConnected||this.#controller||this.channel!==channel)return;if(stored.session)this.#ensureController();else this.#styleLauncher(channel)};if("requestIdleCallback"in window)requestIdleCallback(idle,{timeout:3000});else setTimeout(idle,1000)}#styleLauncher(channel){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(channel)}`,{credentials:"omit"}).then((response)=>{if(response.status===403||response.status===404)this.#refuse();return response.ok?response.json():null}).then((inbox)=>{if(!inbox||this.channel!==channel||this.#controller)return;let launcher=launcherOf(inbox);this.#applyLauncher(launcher),writeStored(channel,{...readStored(channel),launcher})}).catch(()=>{return})}disconnectedCallback(){let controller=this.#controller;if(this.#controller=null,controller)controller.then((c)=>c.destroy())}attributeChangedCallback(name,previous,value){if(!this.isConnected||previous===value)return;if(name==="open"){value===null?this.close():this.open();return}if(name==="identity-token"){if(this.#controller)this.#controller.then((controller)=>controller.identityChanged());return}if(name==="channel"||name==="server"){this.disconnectedCallback(),this.#refused=!1,this.#render();return}if(this.#render(),this.#controller)this.#controller.then((controller)=>controller.update())}async open(){if(this.#open||this.#refused)return;this.#open=!0,this.toggleAttribute("open-panel",!0),this.#syncLauncher();let controller=await this.#ensureController();if(!this.#open)return;if(this.#panel.hidden=!1,controller.opened(),this.layout!=="embedded")this.dispatchEvent(new Event("yuva-open",{bubbles:!0,composed:!0}))}close(){if(!this.#open||this.layout==="embedded")return;if(this.#open=!1,this.toggleAttribute("open-panel",!1),this.#panel.hidden=!0,this.#syncLauncher(),this.#launcher?.focus(),this.#controller)this.#controller.then((controller)=>controller.closed())}toggle(){return this.#open?this.close():this.open()}#config(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#ensureController(){return this.#controller??=YuvaChatElement.loadPanel().then(({mount})=>mount({panel:this.#panel,config:()=>this.#config(),identityToken:async()=>this.#identity?await this.#identity()??null:this.getAttribute("identity-token"),isOpen:()=>this.#open,close:()=>this.close(),setUnread:(count)=>{this.#unread=count,this.#syncLauncher(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count}}))},setLauncher:(style)=>this.#applyLauncher(style),refused:()=>this.#refuse()})),this.#controller}#refuse(){if(this.#refused)return;this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#open=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#render()}#applyLauncher(style){if(this.setAttribute("position",style.position==="left"?"left":"right"),style.color&&/^#[0-9a-f]{6}$/i.test(style.color))this.style.setProperty("--yuva-accent",style.color),this.style.setProperty("--yuva-on-accent",contrastOn(style.color))}#render(){let locale=this.locale;this.#messages=catalogFor(locale),this.setAttribute("lang",locale);let style=document.createElement("style");if(style.textContent=styles,this.#panel.dir=this.getAttribute("dir")??directionOf(locale),this.#panel.setAttribute("aria-modal","false"),this.#refused){this.#launcher=null,this.#badge=null,this.#root.replaceChildren();return}if(this.layout==="embedded"){this.#launcher=null,this.#badge=null,this.#root.replaceChildren(style,this.#panel),this.#open=!1,this.open();return}let launcher=document.createElement("button");if(launcher.type="button",launcher.className="launcher",launcher.addEventListener("click",()=>void this.toggle()),this.#launcher=launcher,this.#badge=document.createElement("span"),this.#badge.className="badge",this.#badge.setAttribute("aria-hidden","true"),this.#root.replaceChildren(style,this.#panel,launcher),this.#syncLauncher(),this.hasAttribute("open")&&!this.#open)this.open()}#syncLauncher(){let launcher=this.#launcher,badge=this.#badge;if(!launcher||!badge)return;let count=this.#unread;launcher.setAttribute("aria-expanded",String(this.#open)),launcher.setAttribute("aria-label",this.#open?translatePlain(this.#messages,{id:"pqZJT2"}):count>0?translatePlain(this.#messages,{id:"OkHvGB",values:{count}}):translatePlain(this.#messages,{id:"6I7cJR"})),launcher.innerHTML=this.#open?closeIcon:chatIcon,badge.textContent=count>9?"9+":String(count),badge.hidden=this.#open||count===0,launcher.append(badge)}}function define(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",YuvaChatElement)}YuvaChatElement.loadPanel=()=>import("./yuva-chat-zzebx8pk.js");define();export{YuvaChatElement,define};
109
+ `,chatIcon='<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M4 5h16v11H9l-5 4z"/></svg>',closeIcon='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',scriptSrc=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";class YuvaChatElement extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",scriptSrc||location.href).href);#root;#launcher=null;#badge=null;#panel;#controller=null;#messages={};#open=!1;#unread=0;#identity=null;#refused=!1;constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#panel=document.createElement("section"),this.#panel.className="panel",this.#panel.setAttribute("role","dialog"),this.#panel.hidden=!0,this.#panel.addEventListener("keydown",(event)=>{if(event.key==="Escape"&&this.layout==="launcher")this.close()})}get layout(){return this.getAttribute("layout")==="embedded"?"embedded":"launcher"}get channel(){return this.getAttribute("channel")}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}get locale(){return resolveLocale(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#open}get unread(){return this.#unread}setIdentityToken(source){if(this.#identity=source,this.#controller)this.#controller.then((controller)=>controller.identityChanged())}async signOut(){if(this.#identity=null,this.removeAttribute("identity-token"),this.#controller)await(await this.#controller).signOut()}async rate(conversationId,rating,comment){return(await this.#ensureController()).rate(conversationId,rating,comment)}connectedCallback(){this.#render();let channel=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!channel)return;let stored=readStored(channel);if(stored.launcher)this.#applyLauncher(stored.launcher);let idle=()=>{if(!this.isConnected||this.#controller||this.channel!==channel)return;if(stored.session)this.#ensureController();else this.#styleLauncher(channel)};if("requestIdleCallback"in window)requestIdleCallback(idle,{timeout:3000});else setTimeout(idle,1000)}#styleLauncher(channel){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(channel)}`,{credentials:"omit"}).then((response)=>{if(response.status===403||response.status===404)this.#refuse();return response.ok?response.json():null}).then((inbox)=>{if(!inbox||this.channel!==channel||this.#controller)return;let launcher=launcherOf(inbox);this.#applyLauncher(launcher),writeStored(channel,{...readStored(channel),launcher})}).catch(()=>{return})}disconnectedCallback(){let controller=this.#controller;if(this.#controller=null,controller)controller.then((c)=>c.destroy())}attributeChangedCallback(name,previous,value){if(!this.isConnected||previous===value)return;if(name==="open"){value===null?this.close():this.open();return}if(name==="identity-token"){if(this.#controller)this.#controller.then((controller)=>controller.identityChanged());return}if(name==="channel"||name==="server"){this.disconnectedCallback(),this.#refused=!1,this.#render();return}if(this.#render(),this.#controller)this.#controller.then((controller)=>controller.update())}async open(){if(this.#open||this.#refused)return;this.#open=!0,this.toggleAttribute("open-panel",!0),this.#syncLauncher();let controller=await this.#ensureController();if(!this.#open)return;if(this.#panel.hidden=!1,controller.opened(),this.layout!=="embedded")this.dispatchEvent(new Event("yuva-open",{bubbles:!0,composed:!0}))}close(){if(!this.#open||this.layout==="embedded")return;if(this.#open=!1,this.toggleAttribute("open-panel",!1),this.#panel.hidden=!0,this.#syncLauncher(),this.#launcher?.focus(),this.#controller)this.#controller.then((controller)=>controller.closed())}toggle(){return this.#open?this.close():this.open()}#config(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#ensureController(){return this.#controller??=YuvaChatElement.loadPanel().then(({mount})=>mount({panel:this.#panel,config:()=>this.#config(),identityToken:async()=>this.#identity?await this.#identity()??null:this.getAttribute("identity-token"),isOpen:()=>this.#open,close:()=>this.close(),setUnread:(count)=>{this.#unread=count,this.#syncLauncher(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count}}))},setLauncher:(style)=>this.#applyLauncher(style),refused:()=>this.#refuse()})),this.#controller}#refuse(){if(this.#refused)return;this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#open=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#render()}#applyLauncher(style){if(this.setAttribute("position",style.position==="left"?"left":"right"),style.color&&/^#[0-9a-f]{6}$/i.test(style.color))this.style.setProperty("--yuva-accent",style.color),this.style.setProperty("--yuva-on-accent",contrastOn(style.color))}#render(){let locale=this.locale;this.#messages=catalogFor(locale),this.setAttribute("lang",locale);let style=document.createElement("style");if(style.textContent=styles,this.#panel.dir=this.getAttribute("dir")??directionOf(locale),this.#panel.setAttribute("aria-modal","false"),this.#refused){this.#launcher=null,this.#badge=null,this.#root.replaceChildren();return}if(this.layout==="embedded"){this.#launcher=null,this.#badge=null,this.#root.replaceChildren(style,this.#panel),this.#open=!1,this.open();return}let launcher=document.createElement("button");if(launcher.type="button",launcher.className="launcher",launcher.addEventListener("click",()=>void this.toggle()),this.#launcher=launcher,this.#badge=document.createElement("span"),this.#badge.className="badge",this.#badge.setAttribute("aria-hidden","true"),this.#root.replaceChildren(style,this.#panel,launcher),this.#syncLauncher(),this.hasAttribute("open")&&!this.#open)this.open()}#syncLauncher(){let launcher=this.#launcher,badge=this.#badge;if(!launcher||!badge)return;let count=this.#unread;launcher.setAttribute("aria-expanded",String(this.#open)),launcher.setAttribute("aria-label",this.#open?translatePlain(this.#messages,{id:"pqZJT2"}):count>0?translatePlain(this.#messages,{id:"OkHvGB",values:{count}}):translatePlain(this.#messages,{id:"6I7cJR"})),launcher.innerHTML=this.#open?closeIcon:chatIcon,badge.textContent=count>9?"9+":String(count),badge.hidden=this.#open||count===0,launcher.append(badge)}}function define(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",YuvaChatElement)}YuvaChatElement.loadPanel=()=>import("./yuva-chat-nkt3xjhb.js");define();export{YuvaChatElement,define};
@@ -1 +1 @@
1
- import{storageKey2,readerStorageKey2,randomId2,YuvaClient2,createYuvaClient2}from"./index-8hzbxjv3.js";export{YuvaClient2 as YuvaClient,createYuvaClient2 as createYuvaClient,randomId2 as randomId,readerStorageKey2 as readerStorageKey,storageKey2 as storageKey};
1
+ import{storageKey2,readerStorageKey2,randomId2,YuvaClient2,createYuvaClient2}from"./index-geeh5h34.js";export{YuvaClient2 as YuvaClient,createYuvaClient2 as createYuvaClient,randomId2 as randomId,readerStorageKey2 as readerStorageKey,storageKey2 as storageKey};
package/dist/esm/docs.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createYuvaClient2}from"./index-8hzbxjv3.js";import{resolveLocale,translatePlain}from"./index-c6q8br7d.js";import{el}from"./index-rdzxvj2r.js";import{ApiError2}from"./index-gk84nm8f.js";import{directionOf,launcherOf,contrastOn,readStored,writeStored}from"./index-98r96a7e.js";var messages=JSON.parse(`{"-UxBoG":["Deleted member"],"1UzENP":["No"],"2lF8Zj":["Unanswered"],"5lWFkC":["Sign in"],"78dEKp":["Sort discussions"],"7oGBMv":["Discussions"],"8Ekoev":["You can't do that."],"8ntmc1":["Votes: ",["0"]],"D16wQE":["Could not open the discussion. Try again."],"D9CFV5":["Anonymous"],"E_qvzP":["Enter a valid e-mail address."],"EmiQvf":["Thanks! Anything we could add? (optional)"],"FMWGhb":["Deleted reader"],"G2fuEb":["Locked"],"GQVIIl":["You seem to be offline."],"GqCA_t":["Answered"],"Hw3P48":["Replies: ",["0"]],"JlFcis":["Send"],"KDw4GX":["Try again"],"KEjhwb":["This discussion is locked."],"KM6m8p":["Team"],"LwDe8g":["Sign in to take part in the discussion."],"MDmQKn":["Could not load the discussions."],"Pwqkdw":["Loading…"],"SOvBw9":["Was this page helpful?"],"Sad2tK":["Sending…"],"Su3Vyp":["Check the title and the text and try again."],"U7H5Fm":["Sorry about that. What was missing or unclear?"],"UbRKMZ":["Pending"],"WWy8TN":["Top"],"XJURKP":["E-mail address"],"a_qtPP":["E-mail for a reply (optional)"],"b6Orhy":["Have a question or an idea? Start the first one."],"b_f4xj":["Posts can be edited for 30 minutes after they are written."],"d6N994":["Thanks for your feedback."],"fMPkxb":["Show more"],"fcWrnU":["Sign out"],"isRobC":["New"],"j-3eim":["Discussions about this page"],"l75CjT":["Yes"],"lWv8id":["Awaiting approval"],"nLqMRA":["Team member"],"nW3go1":["Your browser blocked the sign-in window. Allow pop-ups for this site and try again."],"pzatAP":["Loading discussions…"],"rpfOwz":["No discussions about this page yet."],"tA4dAO":["No thanks"],"tAL5wg":["Could not send. Try again."],"tayT8P":["Discussions are turned off for this site."],"twEQ41":["Every discussion on this page has an answer."],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uuIskV":["Sign in to write to us."],"xOTzt5":["just now"],"z1qf6l":["Start a discussion"],"zmA6sS":["Reader"]}`);var messages2=JSON.parse('{"-UxBoG":["Gelöschtes Mitglied"],"1UzENP":["Nein"],"2lF8Zj":["Unbeantwortet"],"5lWFkC":["Anmelden"],"78dEKp":["Diskussionen sortieren"],"7oGBMv":["Diskussionen"],"8Ekoev":["Das können Sie nicht tun."],"8ntmc1":["Stimmen: ",["0"]],"D16wQE":["Die Diskussion konnte nicht eröffnet werden. Versuchen Sie es erneut."],"D9CFV5":["Anonym"],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"EmiQvf":["Danke! Können wir noch etwas ergänzen? (optional)"],"FMWGhb":["Gelöschter Leser"],"G2fuEb":["Gesperrt"],"GQVIIl":["Sie scheinen offline zu sein."],"GqCA_t":["Beantwortet"],"Hw3P48":["Antworten: ",["0"]],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"KEjhwb":["Diese Diskussion ist gesperrt."],"KM6m8p":["Team"],"LwDe8g":["Melden Sie sich an, um an der Diskussion teilzunehmen."],"MDmQKn":["Die Diskussionen konnten nicht geladen werden."],"Pwqkdw":["Wird geladen…"],"SOvBw9":["War diese Seite hilfreich?"],"Sad2tK":["Wird gesendet…"],"Su3Vyp":["Prüfen Sie Titel und Text und versuchen Sie es erneut."],"U7H5Fm":["Das tut uns leid. Was hat gefehlt oder war unklar?"],"UbRKMZ":["Ausstehend"],"WWy8TN":["Beliebteste"],"XJURKP":["E-Mail-Adresse"],"a_qtPP":["E-Mail für eine Antwort (optional)"],"b6Orhy":["Haben Sie eine Frage oder eine Idee? Starten Sie die erste Diskussion."],"b_f4xj":["Beiträge können bis 30 Minuten nach dem Schreiben bearbeitet werden."],"d6N994":["Danke für Ihr Feedback."],"fMPkxb":["Mehr anzeigen"],"fcWrnU":["Abmelden"],"isRobC":["Neu"],"j-3eim":["Diskussionen zu dieser Seite"],"l75CjT":["Ja"],"lWv8id":["Wartet auf Freigabe"],"nLqMRA":["Teammitglied"],"nW3go1":["Ihr Browser hat das Anmeldefenster blockiert. Erlauben Sie Pop-ups für diese Website und versuchen Sie es erneut."],"pzatAP":["Diskussionen werden geladen…"],"rpfOwz":["Zu dieser Seite gibt es noch keine Diskussionen."],"tA4dAO":["Nein, danke"],"tAL5wg":["Senden fehlgeschlagen. Versuchen Sie es erneut."],"tayT8P":["Diskussionen sind für diese Website deaktiviert."],"twEQ41":["Jede Diskussion auf dieser Seite hat eine Antwort."],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uuIskV":["Melden Sie sich an, um uns zu schreiben."],"xOTzt5":["gerade eben"],"z1qf6l":["Diskussion starten"],"zmA6sS":["Leser"]}');var messages3=JSON.parse('{"-UxBoG":["Silinmiş üye"],"1UzENP":["Hayır"],"2lF8Zj":["Yanıtsız"],"5lWFkC":["Giriş yap"],"78dEKp":["Tartışmaları sırala"],"7oGBMv":["Tartışmalar"],"8Ekoev":["Bunu yapamazsınız."],"8ntmc1":["Oylar: ",["0"]],"D16wQE":["Tartışma açılamadı. Yeniden deneyin."],"D9CFV5":["Anonim"],"E_qvzP":["Geçerli bir e-posta adresi girin."],"EmiQvf":["Teşekkürler! Ekleyebileceğimiz bir şey var mı? (isteğe bağlı)"],"FMWGhb":["Silinmiş okuyucu"],"G2fuEb":["Kilitli"],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"GqCA_t":["Yanıtlandı"],"Hw3P48":["Yanıtlar: ",["0"]],"JlFcis":["Gönder"],"KDw4GX":["Yeniden dene"],"KEjhwb":["Bu tartışma kilitli."],"KM6m8p":["Ekip"],"LwDe8g":["Tartışmaya katılmak için giriş yapın."],"MDmQKn":["Tartışmalar yüklenemedi."],"Pwqkdw":["Yükleniyor…"],"SOvBw9":["Bu sayfa işinize yaradı mı?"],"Sad2tK":["Gönderiliyor…"],"Su3Vyp":["Başlığı ve metni kontrol edip yeniden deneyin."],"U7H5Fm":["Üzgünüz. Eksik ya da anlaşılmayan ne vardı?"],"UbRKMZ":["Bekliyor"],"WWy8TN":["En çok oy alan"],"XJURKP":["E-posta adresi"],"a_qtPP":["Yanıt için e-posta (isteğe bağlı)"],"b6Orhy":["Bir sorunuz ya da fikriniz mi var? İlk tartışmayı siz başlatın."],"b_f4xj":["Gönderiler yazıldıktan sonra 30 dakika içinde düzenlenebilir."],"d6N994":["Geri bildiriminiz için teşekkürler."],"fMPkxb":["Daha fazla göster"],"fcWrnU":["Çıkış yap"],"isRobC":["Yeni"],"j-3eim":["Bu sayfayla ilgili tartışmalar"],"l75CjT":["Evet"],"lWv8id":["Onay bekliyor"],"nLqMRA":["Ekip üyesi"],"nW3go1":["Tarayıcınız giriş penceresini engelledi. Bu site için açılır pencerelere izin verip yeniden deneyin."],"pzatAP":["Tartışmalar yükleniyor…"],"rpfOwz":["Bu sayfayla ilgili henüz bir tartışma yok."],"tA4dAO":["Hayır, teşekkürler"],"tAL5wg":["Gönderilemedi. Yeniden deneyin."],"tayT8P":["Bu sitede tartışmalar kapalı."],"twEQ41":["Bu sayfadaki her tartışmanın bir yanıtı var."],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uuIskV":["Bize yazmak için oturum açın."],"xOTzt5":["az önce"],"z1qf6l":["Tartışma başlat"],"zmA6sS":["Okur"]}');var shared=Symbol.for("yuva.navigation");function navigation(){let win=window,target=win[shared];if(target)return target;let created=new EventTarget;target=win[shared]=created;let notify=()=>created.dispatchEvent(new Event("change"));for(let name of["pushState","replaceState"]){let original=history[name];history[name]=function(...args){let result=original.apply(this,args);return notify(),result}}return window.addEventListener("popstate",notify),window.addEventListener("hashchange",notify),target}function pageOf(value){try{let url=new URL(value||location.href,location.href);return url.search="",url.hash="",url.href}catch{return value||location.href}}function followPage(listener){let target=navigation(),scheduled=!1,changed=()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{scheduled=!1,listener()})};return target.addEventListener("change",changed),()=>target.removeEventListener("change",changed)}var catalogs={en:messages,tr:messages3,de:messages2},settings=new Map,Base=typeof HTMLElement>"u"?class{}:HTMLElement,scriptSrc=typeof document<"u"&&document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"",baseStyles=`
1
+ import{createYuvaClient2}from"./index-geeh5h34.js";import{resolveLocale,translatePlain}from"./index-c6q8br7d.js";import{el}from"./index-rdzxvj2r.js";import{ApiError2}from"./index-gk84nm8f.js";import{directionOf,launcherOf,contrastOn,readStored,writeStored}from"./index-98r96a7e.js";var messages=JSON.parse(`{"-UxBoG":["Deleted member"],"1UzENP":["No"],"2lF8Zj":["Unanswered"],"5lWFkC":["Sign in"],"78dEKp":["Sort discussions"],"7oGBMv":["Discussions"],"8Ekoev":["You can't do that."],"8ntmc1":["Votes: ",["0"]],"D16wQE":["Could not open the discussion. Try again."],"D9CFV5":["Anonymous"],"E_qvzP":["Enter a valid e-mail address."],"EmiQvf":["Thanks! Anything we could add? (optional)"],"FMWGhb":["Deleted reader"],"G2fuEb":["Locked"],"GQVIIl":["You seem to be offline."],"GqCA_t":["Answered"],"Hw3P48":["Replies: ",["0"]],"JlFcis":["Send"],"KDw4GX":["Try again"],"KEjhwb":["This discussion is locked."],"KM6m8p":["Team"],"LwDe8g":["Sign in to take part in the discussion."],"MDmQKn":["Could not load the discussions."],"Pwqkdw":["Loading…"],"SOvBw9":["Was this page helpful?"],"Sad2tK":["Sending…"],"Su3Vyp":["Check the title and the text and try again."],"U7H5Fm":["Sorry about that. What was missing or unclear?"],"UbRKMZ":["Pending"],"WWy8TN":["Top"],"XJURKP":["E-mail address"],"a_qtPP":["E-mail for a reply (optional)"],"b6Orhy":["Have a question or an idea? Start the first one."],"b_f4xj":["Posts can be edited for 30 minutes after they are written."],"d6N994":["Thanks for your feedback."],"fMPkxb":["Show more"],"fcWrnU":["Sign out"],"isRobC":["New"],"j-3eim":["Discussions about this page"],"l75CjT":["Yes"],"lWv8id":["Awaiting approval"],"nLqMRA":["Team member"],"nW3go1":["Your browser blocked the sign-in window. Allow pop-ups for this site and try again."],"pzatAP":["Loading discussions…"],"rpfOwz":["No discussions about this page yet."],"tA4dAO":["No thanks"],"tAL5wg":["Could not send. Try again."],"tayT8P":["Discussions are turned off for this site."],"twEQ41":["Every discussion on this page has an answer."],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uuIskV":["Sign in to write to us."],"xOTzt5":["just now"],"z1qf6l":["Start a discussion"],"zmA6sS":["Reader"]}`);var messages2=JSON.parse('{"-UxBoG":["Gelöschtes Mitglied"],"1UzENP":["Nein"],"2lF8Zj":["Unbeantwortet"],"5lWFkC":["Anmelden"],"78dEKp":["Diskussionen sortieren"],"7oGBMv":["Diskussionen"],"8Ekoev":["Das können Sie nicht tun."],"8ntmc1":["Stimmen: ",["0"]],"D16wQE":["Die Diskussion konnte nicht eröffnet werden. Versuchen Sie es erneut."],"D9CFV5":["Anonym"],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"EmiQvf":["Danke! Können wir noch etwas ergänzen? (optional)"],"FMWGhb":["Gelöschter Leser"],"G2fuEb":["Gesperrt"],"GQVIIl":["Sie scheinen offline zu sein."],"GqCA_t":["Beantwortet"],"Hw3P48":["Antworten: ",["0"]],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"KEjhwb":["Diese Diskussion ist gesperrt."],"KM6m8p":["Team"],"LwDe8g":["Melden Sie sich an, um an der Diskussion teilzunehmen."],"MDmQKn":["Die Diskussionen konnten nicht geladen werden."],"Pwqkdw":["Wird geladen…"],"SOvBw9":["War diese Seite hilfreich?"],"Sad2tK":["Wird gesendet…"],"Su3Vyp":["Prüfen Sie Titel und Text und versuchen Sie es erneut."],"U7H5Fm":["Das tut uns leid. Was hat gefehlt oder war unklar?"],"UbRKMZ":["Ausstehend"],"WWy8TN":["Beliebteste"],"XJURKP":["E-Mail-Adresse"],"a_qtPP":["E-Mail für eine Antwort (optional)"],"b6Orhy":["Haben Sie eine Frage oder eine Idee? Starten Sie die erste Diskussion."],"b_f4xj":["Beiträge können bis 30 Minuten nach dem Schreiben bearbeitet werden."],"d6N994":["Danke für Ihr Feedback."],"fMPkxb":["Mehr anzeigen"],"fcWrnU":["Abmelden"],"isRobC":["Neu"],"j-3eim":["Diskussionen zu dieser Seite"],"l75CjT":["Ja"],"lWv8id":["Wartet auf Freigabe"],"nLqMRA":["Teammitglied"],"nW3go1":["Ihr Browser hat das Anmeldefenster blockiert. Erlauben Sie Pop-ups für diese Website und versuchen Sie es erneut."],"pzatAP":["Diskussionen werden geladen…"],"rpfOwz":["Zu dieser Seite gibt es noch keine Diskussionen."],"tA4dAO":["Nein, danke"],"tAL5wg":["Senden fehlgeschlagen. Versuchen Sie es erneut."],"tayT8P":["Diskussionen sind für diese Website deaktiviert."],"twEQ41":["Jede Diskussion auf dieser Seite hat eine Antwort."],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uuIskV":["Melden Sie sich an, um uns zu schreiben."],"xOTzt5":["gerade eben"],"z1qf6l":["Diskussion starten"],"zmA6sS":["Leser"]}');var messages3=JSON.parse('{"-UxBoG":["Silinmiş üye"],"1UzENP":["Hayır"],"2lF8Zj":["Yanıtsız"],"5lWFkC":["Giriş yap"],"78dEKp":["Tartışmaları sırala"],"7oGBMv":["Tartışmalar"],"8Ekoev":["Bunu yapamazsınız."],"8ntmc1":["Oylar: ",["0"]],"D16wQE":["Tartışma açılamadı. Yeniden deneyin."],"D9CFV5":["Anonim"],"E_qvzP":["Geçerli bir e-posta adresi girin."],"EmiQvf":["Teşekkürler! Ekleyebileceğimiz bir şey var mı? (isteğe bağlı)"],"FMWGhb":["Silinmiş okuyucu"],"G2fuEb":["Kilitli"],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"GqCA_t":["Yanıtlandı"],"Hw3P48":["Yanıtlar: ",["0"]],"JlFcis":["Gönder"],"KDw4GX":["Yeniden dene"],"KEjhwb":["Bu tartışma kilitli."],"KM6m8p":["Ekip"],"LwDe8g":["Tartışmaya katılmak için giriş yapın."],"MDmQKn":["Tartışmalar yüklenemedi."],"Pwqkdw":["Yükleniyor…"],"SOvBw9":["Bu sayfa işinize yaradı mı?"],"Sad2tK":["Gönderiliyor…"],"Su3Vyp":["Başlığı ve metni kontrol edip yeniden deneyin."],"U7H5Fm":["Üzgünüz. Eksik ya da anlaşılmayan ne vardı?"],"UbRKMZ":["Bekliyor"],"WWy8TN":["En çok oy alan"],"XJURKP":["E-posta adresi"],"a_qtPP":["Yanıt için e-posta (isteğe bağlı)"],"b6Orhy":["Bir sorunuz ya da fikriniz mi var? İlk tartışmayı siz başlatın."],"b_f4xj":["Gönderiler yazıldıktan sonra 30 dakika içinde düzenlenebilir."],"d6N994":["Geri bildiriminiz için teşekkürler."],"fMPkxb":["Daha fazla göster"],"fcWrnU":["Çıkış yap"],"isRobC":["Yeni"],"j-3eim":["Bu sayfayla ilgili tartışmalar"],"l75CjT":["Evet"],"lWv8id":["Onay bekliyor"],"nLqMRA":["Ekip üyesi"],"nW3go1":["Tarayıcınız giriş penceresini engelledi. Bu site için açılır pencerelere izin verip yeniden deneyin."],"pzatAP":["Tartışmalar yükleniyor…"],"rpfOwz":["Bu sayfayla ilgili henüz bir tartışma yok."],"tA4dAO":["Hayır, teşekkürler"],"tAL5wg":["Gönderilemedi. Yeniden deneyin."],"tayT8P":["Bu sitede tartışmalar kapalı."],"twEQ41":["Bu sayfadaki her tartışmanın bir yanıtı var."],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uuIskV":["Bize yazmak için oturum açın."],"xOTzt5":["az önce"],"z1qf6l":["Tartışma başlat"],"zmA6sS":["Okur"]}');var shared=Symbol.for("yuva.navigation");function navigation(){let win=window,target=win[shared];if(target)return target;let created=new EventTarget;target=win[shared]=created;let notify=()=>created.dispatchEvent(new Event("change"));for(let name of["pushState","replaceState"]){let original=history[name];history[name]=function(...args){let result=original.apply(this,args);return notify(),result}}return window.addEventListener("popstate",notify),window.addEventListener("hashchange",notify),target}function pageOf(value){try{let url=new URL(value||location.href,location.href);return url.search="",url.hash="",url.href}catch{return value||location.href}}function followPage(listener){let target=navigation(),scheduled=!1,changed=()=>{if(scheduled)return;scheduled=!0,queueMicrotask(()=>{scheduled=!1,listener()})};return target.addEventListener("change",changed),()=>target.removeEventListener("change",changed)}var catalogs={en:messages,tr:messages3,de:messages2},settings=new Map,Base=typeof HTMLElement>"u"?class{}:HTMLElement,scriptSrc=typeof document<"u"&&document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"",baseStyles=`
2
2
  :host {
3
3
  --yuva-accent: #2563eb;
4
4
  --yuva-on-accent: #ffffff;
@@ -1,4 +1,4 @@
1
- import{ApiError2,call,mailingLists,createSubscription}from"./index-gk84nm8f.js";class Realtime{server;socketClass;handlers;#socket=null;#lastEventId=0;#attempt=0;#timer=null;#stopped=!0;constructor(server,socketClass,handlers){this.server=server;this.socketClass=socketClass;this.handlers=handlers}get connected(){return this.#socket?.readyState===1}start(){if(this.#stopped=!1,!this.#socket)this.#connect()}stop(){if(this.#stopped=!0,this.#timer)clearTimeout(this.#timer);this.#timer=null;let socket=this.#socket;this.#socket=null,socket?.close(1000)}reset(){this.#lastEventId=0}nudge(){if(this.#stopped||this.#socket)return;if(this.#timer)clearTimeout(this.#timer);this.#timer=null,this.#connect()}#connect(){let token=this.handlers.token();if(!token||this.#stopped)return;let url=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(url.protocol=url.protocol==="https:"?"wss:":"ws:",this.#lastEventId>0)url.searchParams.set("last_event_id",String(this.#lastEventId));let socket;try{socket=new this.socketClass(url,["yuva",`yuva.token.${token}`])}catch{this.#schedule();return}this.#socket=socket,socket.onmessage=(event)=>{let message;try{message=JSON.parse(String(event.data))}catch{return}if(message.type==="ready")this.#attempt=0,this.#lastEventId=Math.max(this.#lastEventId,message.last_event_id);else if("id"in message&&typeof message.id==="number")this.#lastEventId=Math.max(this.#lastEventId,message.id);this.handlers.event(message)},socket.onclose=(event)=>{if(this.#socket!==socket)return;if(this.#socket=null,this.#stopped)return;if(event.code===1008){this.#lastEventId=0,this.handlers.sessionEnded();return}this.#schedule()}}#schedule(){if(this.#stopped||this.#timer)return;let attempt=this.#attempt++;this.handlers.reconnecting(attempt);let delay=Math.min(30000,1000*2**attempt)*(0.75+Math.random()*0.5);this.#timer=setTimeout(()=>{this.#timer=null,this.#connect()},delay)}}function readerConnectUrl2(server,channel,origin){let url=new URL("/account/connect",server);return url.searchParams.set("channel",channel),url.searchParams.set("origin",origin),url.href}function isReaderToken(value){let data=value;return!!data&&typeof data.token==="string"&&data.token.startsWith("yuva_rd_")&&typeof data.expires_at==="string"&&!Number.isNaN(Date.parse(data.expires_at))&&typeof data.channel_key==="string"&&typeof data.origin==="string"&&!!data.reader&&typeof data.reader.initials==="string"}function openReaderPopup2(server,channel,{width=460,height=640}={}){let serverOrigin=new URL(server).origin,origin=location.origin,left=Math.max(0,(window.screenX??0)+((window.outerWidth??width)-width)/2),top=Math.max(0,(window.screenY??0)+((window.outerHeight??height)-height)/2),popup=window.open(readerConnectUrl2(server,channel,origin),"yuva-reader",`popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`);if(!popup)return Promise.reject(new ApiError2(0,"popup_blocked"));return new Promise((resolve,reject)=>{let done=!1,finish=()=>{done=!0,window.removeEventListener("message",received),clearInterval(watch)},received=(event)=>{if(done||event.origin!==serverOrigin||event.source&&event.source!==popup)return;let data=event.data;if(!isReaderToken(data)||data.channel_key!==channel||data.origin!==origin)return;finish();try{popup.close()}catch{}resolve({token:data.token,expires_at:data.expires_at,reader:data.reader})},watch=setInterval(()=>{let closed=!1;try{closed=popup.closed}catch{}if(!closed)return;clearInterval(watch),setTimeout(()=>{if(done)return;finish(),reject(new ApiError2(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",received)})}function storageKey2(channel){return`yuva:${channel}`}function readerStorageKey2(server,channel){return`yuva:reader:${server} ${channel}`}function randomId2(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(b)=>b.toString(16).padStart(2,"0")).join("")}function jwtSubject(token){try{let part=(token.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),payload=JSON.parse(atob(part));return typeof payload.sub==="string"?payload.sub:null}catch{return null}}function defaultStorage(){try{let storage=globalThis.localStorage;if(storage)return storage}catch{}let memory=new Map;return{getItem:(key)=>memory.get(key)??null,setItem:(key,value)=>void memory.set(key,value)}}function query(params){let search=new URLSearchParams;for(let[name,value]of Object.entries(params))if(value!==void 0)search.set(name,String(value));let text=search.toString();return text?`?${text}`:""}function quoted(value){return value.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function multipart(fields,files,boundary){let parts=[];for(let[name,value]of fields)parts.push(`--${boundary}\r
1
+ import{ApiError2,call,mailingLists,createSubscription}from"./index-gk84nm8f.js";class Realtime{server;socketClass;handlers;#socket=null;#lastEventId=0;#attempt=0;#timer=null;#stopped=!0;constructor(server,socketClass,handlers){this.server=server;this.socketClass=socketClass;this.handlers=handlers}get connected(){return this.#socket?.readyState===1}start(){if(this.#stopped=!1,!this.#socket&&!this.#timer)this.#connect()}stop(){if(this.#stopped=!0,this.#timer)clearTimeout(this.#timer);this.#timer=null;let socket=this.#socket;this.#socket=null,socket?.close(1000)}reset(){this.#lastEventId=0}nudge(){if(this.#stopped||this.#socket)return;if(this.#timer)clearTimeout(this.#timer);this.#timer=null,this.#connect()}#connect(){let token=this.handlers.token();if(!token||this.#stopped)return;let url=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(url.protocol=url.protocol==="https:"?"wss:":"ws:",this.#lastEventId>0)url.searchParams.set("last_event_id",String(this.#lastEventId));let socket;try{socket=new this.socketClass(url,["yuva",`yuva.token.${token}`])}catch{this.#schedule();return}this.#socket=socket,socket.onmessage=(event)=>{let message;try{message=JSON.parse(String(event.data))}catch{return}if(message.type==="ready")this.#attempt=0,this.#lastEventId=Math.max(this.#lastEventId,message.last_event_id);else if("id"in message&&typeof message.id==="number")this.#lastEventId=Math.max(this.#lastEventId,message.id);this.handlers.event(message)},socket.onclose=(event)=>{if(this.#socket!==socket)return;if(this.#socket=null,this.#stopped)return;if(event.code===1008){this.#lastEventId=0,this.handlers.sessionEnded();return}this.#schedule()}}#schedule(){if(this.#stopped||this.#timer)return;let attempt=this.#attempt++;this.handlers.reconnecting(attempt);let delay=Math.min(30000,1000*2**attempt)*(0.75+Math.random()*0.5);this.#timer=setTimeout(()=>{this.#timer=null,this.#connect()},delay)}}function readerConnectUrl2(server,channel,origin){let url=new URL("/account/connect",server);return url.searchParams.set("channel",channel),url.searchParams.set("origin",origin),url.href}function isReaderToken(value){let data=value;return!!data&&typeof data.token==="string"&&data.token.startsWith("yuva_rd_")&&typeof data.expires_at==="string"&&!Number.isNaN(Date.parse(data.expires_at))&&typeof data.channel_key==="string"&&typeof data.origin==="string"&&!!data.reader&&typeof data.reader.initials==="string"}function openReaderPopup2(server,channel,{width=460,height=640}={}){let serverOrigin=new URL(server).origin,origin=location.origin,left=Math.max(0,(window.screenX??0)+((window.outerWidth??width)-width)/2),top=Math.max(0,(window.screenY??0)+((window.outerHeight??height)-height)/2),popup=window.open(readerConnectUrl2(server,channel,origin),"yuva-reader",`popup=yes,width=${width},height=${height},left=${Math.round(left)},top=${Math.round(top)}`);if(!popup)return Promise.reject(new ApiError2(0,"popup_blocked"));return new Promise((resolve,reject)=>{let done=!1,finish=()=>{done=!0,window.removeEventListener("message",received),clearInterval(watch)},received=(event)=>{if(done||event.origin!==serverOrigin||event.source&&event.source!==popup)return;let data=event.data;if(!isReaderToken(data)||data.channel_key!==channel||data.origin!==origin)return;finish();try{popup.close()}catch{}resolve({token:data.token,expires_at:data.expires_at,reader:data.reader})},watch=setInterval(()=>{let closed=!1;try{closed=popup.closed}catch{}if(!closed)return;clearInterval(watch),setTimeout(()=>{if(done)return;finish(),reject(new ApiError2(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",received)})}function storageKey2(channel){return`yuva:${channel}`}function readerStorageKey2(server,channel){return`yuva:reader:${server} ${channel}`}function randomId2(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(b)=>b.toString(16).padStart(2,"0")).join("")}function jwtSubject(token){try{let part=(token.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),payload=JSON.parse(atob(part));return typeof payload.sub==="string"?payload.sub:null}catch{return null}}function defaultStorage(){try{let storage=globalThis.localStorage;if(storage)return storage}catch{}let memory=new Map;return{getItem:(key)=>memory.get(key)??null,setItem:(key,value)=>void memory.set(key,value)}}function query(params){let search=new URLSearchParams;for(let[name,value]of Object.entries(params))if(value!==void 0)search.set(name,String(value));let text=search.toString();return text?`?${text}`:""}function quoted(value){return value.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function multipart(fields,files,boundary){let parts=[];for(let[name,value]of fields)parts.push(`--${boundary}\r
2
2
  Content-Disposition: form-data; name="${name}"\r
3
3
  \r
4
4
  ${value}\r
package/dist/esm/index.js CHANGED
@@ -1 +1 @@
1
- import{readerConnectUrl2,openReaderPopup2,YuvaClient2,createYuvaClient2}from"./index-8hzbxjv3.js";import{ApiError2}from"./index-gk84nm8f.js";export{ApiError2 as ApiError,YuvaClient2 as YuvaClient,createYuvaClient2 as createYuvaClient,openReaderPopup2 as openReaderPopup,readerConnectUrl2 as readerConnectUrl};
1
+ import{readerConnectUrl2,openReaderPopup2,YuvaClient2,createYuvaClient2}from"./index-geeh5h34.js";import{ApiError2}from"./index-gk84nm8f.js";export{ApiError2 as ApiError,YuvaClient2 as YuvaClient,createYuvaClient2 as createYuvaClient,openReaderPopup2 as openReaderPopup,readerConnectUrl2 as readerConnectUrl};
@@ -30,4 +30,4 @@ legend{padding:0;margin-block-end:4px;font-weight:600}
30
30
  .error{color:var(--d)}
31
31
  .trap{position:absolute;inset-inline-start:-1e4px;inline-size:1px;overflow:hidden}
32
32
  @media (max-width:480px){input{font-size:16px}}
33
- `;class YuvaSubscribeElement extends Base{static observedAttributes=["channel","server","locale","dir","lists","layout","name","button-text","consent","privacy-url","identity-token"];static loadClient=null;#root;#messages=messages;#connected=!1;#generation=0;#phase="loading";#refused=!1;#inbox=null;#offered=[];#chosen=new Set;#token="";#tokenAt=0;#confirmation=!1;#error="";#emailError="";#nameError="";#consentError="";#identity=null;#client=null;#busy=new Set;#email=el("input");#name=el("input");#trap=el("input");#consent=el("input");#status=el("p");constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#email.type="email",this.#email.autocomplete="email",this.#email.required=!0,this.#email.maxLength=320,this.#email.id="email",this.#name.autocomplete="name",this.#name.maxLength=200,this.#name.id="name",this.#trap.name="website",this.#trap.tabIndex=-1,this.#trap.autocomplete="off",this.#consent.type="checkbox",this.#consent.id="consent",this.#consent.addEventListener("change",()=>{this.#consentError="",this.#render()});for(let input of[this.#email,this.#name])input.setAttribute("part","field"),input.dir="auto";this.#status.setAttribute("part","status"),this.#status.setAttribute("role","status"),this.#status.setAttribute("aria-live","polite")}get channel(){return this.getAttribute("channel")}set channel(value){this.#attribute("channel",value)}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}set server(value){this.#attribute("server",value)}get locale(){return localeIn(catalogs,[this.getAttribute("locale"),navigator.language])}set locale(value){this.#attribute("locale",value)}get lists(){return this.#offered.map((item)=>item.list)}setIdentityToken(source){if(this.#identity=source,this.#connected)this.#load()}connectedCallback(){this.#connected=!0,this.#load()}disconnectedCallback(){this.#connected=!1}attributeChangedCallback(name,previous,value){if(!this.#connected||previous===value)return;if(["channel","server","lists","identity-token"].includes(name))return void this.#load();this.#render()}#attribute(name,value){if(value===null||value===void 0||value==="")this.removeAttribute(name);else this.setAttribute(name,value)}#t(descriptor){return translate(this.#messages,descriptor,messages)}get#identified(){return!!this.#identity||this.hasAttribute("identity-token")}async#identityToken(){return this.#identity?await this.#identity()??null:this.getAttribute("identity-token")}#wanted(lists){let ids=(this.getAttribute("lists")??"").split(",").map((id)=>id.trim()).filter((id)=>id&&id!=="all");if(ids.length===0)return lists;let found=ids.map((id)=>lists.find((list)=>list.id===id)).filter((list)=>!!list);if(found.length<ids.length)console.warn(`Yuva: some lists in "${ids.join(",")}" are not public lists`);return found}async#load(){let generation=++this.#generation,channel=this.channel;if(this.#refused=!1,this.#phase="loading",this.#offered=[],this.#error="",this.#client=null,this.#render(),!channel)return;let server=this.server;try{let inbox=call(fetcher,server,`/client/v1/channels/${encodeURIComponent(channel)}`),offered=null;if(this.#identified&&YuvaSubscribeElement.loadClient&&await this.#identityToken()){let{createYuvaClient}=await YuvaSubscribeElement.loadClient(),client=createYuvaClient({server,channel,identityToken:()=>this.#identityToken()});try{let{items}=await client.subscriptions(),wanted=new Set(this.#wanted(items.map((item)=>item.list)));offered=items.filter((item)=>wanted.has(item.list)),this.#client=client}catch(error){if(!(error instanceof ApiError2)||error.code!=="identity_required")throw error}}if(!offered){let{lists,form_token}=await mailingLists(fetcher,server,channel);offered=this.#wanted(lists).map((list)=>({list})),this.#token=form_token,this.#tokenAt=Date.now()}if(this.#inbox=await inbox,generation!==this.#generation)return;if(this.#offered=offered,this.#chosen=new Set(offered.length===1?[offered[0].list.id]:[]),this.#phase="idle",offered.length===0)console.warn(`Yuva: channel ${channel} has no public mailing lists to offer`)}catch(error){if(generation!==this.#generation)return;if(this.#refusal(error))return;this.#phase="idle",this.#error=this.#errorText(error)}this.#render()}#refusal(error){let refused=error instanceof ApiError2&&(error.status===404||error.code==="origin_not_allowed"||error.code==="page_origin");if(refused)this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown, offers no such list or does not allow ${location.origin}`),this.#render();return refused}#errorText(error){let code=error instanceof ApiError2?error.code:"";if(code==="rate_limited")return this.#t({id:"tzsBOP"});if(code==="network")return this.#t({id:"GQVIIl"});if(code==="no_email")return this.#t({id:"eku1-t"});return this.#t({id:"jWgNnM"})}#emit(type,detail){this.dispatchEvent(new CustomEvent(type,{detail,bubbles:!0,composed:!0}))}#failed(error){this.#emit("yuva-subscribe-error",{code:error instanceof ApiError2?error.code:"error"})}consentText(lists=this.#selected()){let custom=this.getAttribute("consent")?.trim();if(custom)return custom;let names=(lists.length?lists:this.lists).map((list)=>list.name),list=new Intl.ListFormat(this.locale,{type:"conjunction"}).format(names),inbox=this.#inbox?.name??"";return this.#t({id:"dMJfG5",values:{list,inbox}})}#selected(){return this.lists.filter((list)=>this.#chosen.has(list.id))}async#submit(){if(this.#phase!=="idle"||!this.channel)return;let lists=this.#selected(),email=this.#email.value.trim(),name=this.#name.value.trim(),asksName=this.getAttribute("name");if(this.#error=lists.length===0?this.#t({id:"-g5O6h"}):"",this.#emailError=this.#email.checkValidity()&&email?"":this.#t({id:"E_qvzP"}),this.#nameError=asksName==="required"&&!name?this.#t({id:"E_LjOR"}):"",this.#consentError=this.#consent.checked?"":this.#t({id:"lDEbTy"}),this.#error||this.#emailError||this.#nameError||this.#consentError){this.#render();let invalid=[this.#emailError&&this.#email,this.#nameError&&this.#name,this.#consentError&&this.#consent];for(let input of invalid)if(input)return input.focus();return}let channel=this.channel,generation=this.#generation,consent_text=this.consentText(lists);this.#phase="submitting",this.#render();let send=async(retry)=>{let wait=this.#tokenAt+tokenMinimumAge-Date.now();if(wait>0)await new Promise((resolve)=>setTimeout(resolve,wait));try{let{confirmation}=await createSubscription(fetcher,this.server,channel,{email,name:asksName==="optional"||asksName==="required"?name||void 0:void 0,list_ids:lists.map((list)=>list.id),locale:this.locale,page_url:location.href.split("#")[0].slice(0,2000),consent_text,form_token:this.#token,website:this.#trap.value||void 0});return this.#confirmation=confirmation,!0}catch(error){if(retry&&error instanceof ApiError2&&error.code==="form_token"){let fresh=await mailingLists(fetcher,this.server,channel);return this.#token=fresh.form_token,this.#tokenAt=Date.now(),send(!1)}throw error}};try{await send(!0)}catch(error){if(generation!==this.#generation)return;if(this.#failed(error),this.#phase="idle",this.#refusal(error))return;if(error instanceof ApiError2&&error.code==="invalid_email")return this.#emailError=this.#t({id:"E_qvzP"}),this.#render(),this.#email.focus();return this.#error=this.#errorText(error),this.#render()}if(generation!==this.#generation)return;this.#phase="done",this.#emit("yuva-subscribe",{lists:lists.map((list)=>list.id),confirmation:this.#confirmation}),this.#render()}async#toggle(item,on){let client=this.#client;if(!client||this.#busy.has(item.list.id))return;this.#busy.add(item.list.id),this.#error="",this.#render();try{if(on){let{state}=await client.subscribeList(item.list.id,{consent_text:this.consentText([item.list]),page_url:location.href.split("#")[0].slice(0,2000)});item.state=state,this.#emit("yuva-subscribe",{lists:[item.list.id],confirmation:state==="pending"})}else await client.unsubscribeList(item.list.id),item.state="unsubscribed"}catch(error){this.#failed(error),this.#error=this.#errorText(error)}if(this.#busy.delete(item.list.id),client===this.#client)this.#render()}#errorFor(input,text){if(input.setAttribute("aria-invalid",String(!!text)),!text)return input.removeAttribute("aria-describedby"),null;let id=`${input.id}-error`;input.setAttribute("aria-describedby",id);let error=el("p","error",text);return error.id=id,error}#check(text,checked,onChange,key){let label=el("label","check"),box=el("input");box.type="checkbox",box.checked=checked,box.dataset.key=key,box.addEventListener("change",()=>onChange(box.checked));let body=el("span","text");return body.append(...text),label.append(box,body),label}#lists(identity){if(!identity&&this.#offered.length<2)return null;let group=el("fieldset");group.append(el("legend","",this.#t({id:"h16FyT"})));for(let item of this.#offered){let text=[el("span","",item.list.name)];if(item.list.description)text.push(el("span","muted",item.list.description));if(identity){if(text.push(el("span","muted consent",this.consentText([item.list]))),item.state==="pending")text.push(el("span","muted",this.#t({id:"x6dU53"})))}let on=identity?item.state==="subscribed"||item.state==="pending":this.#chosen.has(item.list.id),label=this.#check(text,on,(checked)=>{if(identity)return void this.#toggle(item,checked);if(checked)this.#chosen.add(item.list.id);else this.#chosen.delete(item.list.id);this.#error="",this.#render()},item.list.id),box=label.querySelector("input");if(identity)box.setAttribute("role","switch"),box.setAttribute("aria-checked",String(box.checked)),box.addEventListener("keydown",(event)=>{if(event.key!=="Enter")return;event.preventDefault(),box.click()}),box.disabled=this.#busy.has(item.list.id);else box.disabled=this.#phase==="submitting";group.append(label)}return group}#form(){let form=el("form",this.getAttribute("layout")==="inline"?"inline":"");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#submit()});let busy=this.#phase==="submitting",lists=this.#lists(!1);if(lists)form.append(lists);let row=el("div","row"),errors=[],asksName=this.getAttribute("name");if(asksName==="optional"||asksName==="required"){this.#name.placeholder=asksName==="required"?this.#t({id:"q8yluz"}):this.#t({id:"YnOaHp"}),this.#name.setAttribute("aria-label",this.#name.placeholder),this.#name.required=asksName==="required",this.#name.disabled=busy,row.append(this.#name);let error=this.#errorFor(this.#name,this.#nameError);if(error)errors.push(error)}this.#email.placeholder=this.#t({id:"XJURKP"}),this.#email.setAttribute("aria-label",this.#email.placeholder),this.#email.disabled=busy,row.append(this.#email);let emailError=this.#errorFor(this.#email,this.#emailError);if(emailError)errors.push(emailError);let button=el("button","",busy?this.#t({id:"1w51t9"}):this.getAttribute("button-text")||this.#t({id:"EDl9kS"}));button.type="submit",button.disabled=busy,button.setAttribute("part","button"),row.append(button);let trap=el("div","trap");trap.setAttribute("aria-hidden","true"),trap.append(this.#trap);let consentText=el("span","",this.consentText()),consent=el("label","check consent");consent.setAttribute("part","consent"),this.#consent.disabled=busy;let body=el("span");body.append(consentText);let privacy=this.getAttribute("privacy-url");if(privacy&&/^https?:\/\//i.test(privacy)){let link=el("a","",this.#t({id:"ScJ9fj"}));link.href=privacy,link.target="_blank",link.rel="noopener noreferrer",body.append(" ",link)}consent.append(this.#consent,body);let consentError=this.#errorFor(this.#consent,this.#consentError);if(form.append(row,...errors,consent),consentError)form.append(consentError);return form.append(trap),form}#render(){if(this.#refused||!this.channel||this.#phase!=="loading"&&this.#offered.length===0&&!this.#error){this.#root.replaceChildren();return}let locale=this.locale;this.#messages=catalogs[locale]??messages;let dir=this.getAttribute("dir"),wrapper=el("div","frame");wrapper.dir=dir==="rtl"||dir==="ltr"?dir:directionOf(locale),wrapper.lang=locale;let brand=this.#inbox?.chat.launcher_color??this.#inbox?.branding.color;if(brand&&/^#[0-9a-f]{6}$/i.test(brand))wrapper.style.setProperty("--brand",brand),wrapper.style.setProperty("--brand-on",contrastOn(brand));let status="";if(this.#phase==="done")status=this.#confirmation?this.#t({id:"y3k2zM"}):this.#t({id:"rgySXy"});if(this.#status.textContent=status,this.#phase==="idle"||this.#phase==="submitting"){let content=this.#client?this.#lists(!0):this.#form();if(content)wrapper.append(content)}if(wrapper.append(this.#status),this.#error){let error=el("p","error",this.#error);error.setAttribute("role","alert"),wrapper.append(error)}let focusedKey,focused=null;try{focused=this.#root.activeElement}catch{}if(focused instanceof HTMLInputElement)focusedKey=focused.dataset.key;let style=el("style");style.textContent=styles,this.#root.replaceChildren(style,wrapper);let again=focusedKey?this.#root.querySelector(`[data-key="${focusedKey}"]`):focused;if(again instanceof HTMLElement&&again.isConnected)again.focus({preventScroll:!0})}}function defineSubscribe(){if(typeof customElements>"u")return;if(!customElements.get("yuva-subscribe"))customElements.define("yuva-subscribe",YuvaSubscribeElement)}YuvaSubscribeElement.loadClient=()=>import("./client-p9899hvt.js");defineSubscribe();export{YuvaSubscribeElement,defineSubscribe};
33
+ `;class YuvaSubscribeElement extends Base{static observedAttributes=["channel","server","locale","dir","lists","layout","name","button-text","consent","privacy-url","identity-token"];static loadClient=null;#root;#messages=messages;#connected=!1;#generation=0;#phase="loading";#refused=!1;#inbox=null;#offered=[];#chosen=new Set;#token="";#tokenAt=0;#confirmation=!1;#error="";#emailError="";#nameError="";#consentError="";#identity=null;#client=null;#busy=new Set;#email=el("input");#name=el("input");#trap=el("input");#consent=el("input");#status=el("p");constructor(){super();this.#root=this.attachShadow({mode:"open"}),this.#email.type="email",this.#email.autocomplete="email",this.#email.required=!0,this.#email.maxLength=320,this.#email.id="email",this.#name.autocomplete="name",this.#name.maxLength=200,this.#name.id="name",this.#trap.name="website",this.#trap.tabIndex=-1,this.#trap.autocomplete="off",this.#consent.type="checkbox",this.#consent.id="consent",this.#consent.addEventListener("change",()=>{this.#consentError="",this.#render()});for(let input of[this.#email,this.#name])input.setAttribute("part","field"),input.dir="auto";this.#status.setAttribute("part","status"),this.#status.setAttribute("role","status"),this.#status.setAttribute("aria-live","polite")}get channel(){return this.getAttribute("channel")}set channel(value){this.#attribute("channel",value)}get server(){return(this.getAttribute("server")||(scriptSrc?new URL(scriptSrc).origin:location.origin)).replace(/\/+$/,"")}set server(value){this.#attribute("server",value)}get locale(){return localeIn(catalogs,[this.getAttribute("locale"),navigator.language])}set locale(value){this.#attribute("locale",value)}get lists(){return this.#offered.map((item)=>item.list)}setIdentityToken(source){if(this.#identity=source,this.#connected)this.#load()}connectedCallback(){this.#connected=!0,this.#load()}disconnectedCallback(){this.#connected=!1}attributeChangedCallback(name,previous,value){if(!this.#connected||previous===value)return;if(["channel","server","lists","identity-token"].includes(name))return void this.#load();this.#render()}#attribute(name,value){if(value===null||value===void 0||value==="")this.removeAttribute(name);else this.setAttribute(name,value)}#t(descriptor){return translate(this.#messages,descriptor,messages)}get#identified(){return!!this.#identity||this.hasAttribute("identity-token")}async#identityToken(){return this.#identity?await this.#identity()??null:this.getAttribute("identity-token")}#wanted(lists){let ids=(this.getAttribute("lists")??"").split(",").map((id)=>id.trim()).filter((id)=>id&&id!=="all");if(ids.length===0)return lists;let found=ids.map((id)=>lists.find((list)=>list.id===id)).filter((list)=>!!list);if(found.length<ids.length)console.warn(`Yuva: some lists in "${ids.join(",")}" are not public lists`);return found}async#load(){let generation=++this.#generation,channel=this.channel;if(this.#refused=!1,this.#phase="loading",this.#offered=[],this.#error="",this.#client=null,this.#render(),!channel)return;let server=this.server;try{let inbox=call(fetcher,server,`/client/v1/channels/${encodeURIComponent(channel)}`),offered=null;if(this.#identified&&YuvaSubscribeElement.loadClient&&await this.#identityToken()){let{createYuvaClient}=await YuvaSubscribeElement.loadClient(),client=createYuvaClient({server,channel,identityToken:()=>this.#identityToken()});try{let{items}=await client.subscriptions(),wanted=new Set(this.#wanted(items.map((item)=>item.list)));offered=items.filter((item)=>wanted.has(item.list)),this.#client=client}catch(error){if(!(error instanceof ApiError2)||error.code!=="identity_required")throw error}}if(!offered){let{lists,form_token}=await mailingLists(fetcher,server,channel);offered=this.#wanted(lists).map((list)=>({list})),this.#token=form_token,this.#tokenAt=Date.now()}if(this.#inbox=await inbox,generation!==this.#generation)return;if(this.#offered=offered,this.#chosen=new Set(offered.length===1?[offered[0].list.id]:[]),this.#phase="idle",offered.length===0)console.warn(`Yuva: channel ${channel} has no public mailing lists to offer`)}catch(error){if(generation!==this.#generation)return;if(this.#refusal(error))return;this.#phase="idle",this.#error=this.#errorText(error)}this.#render()}#refusal(error){let refused=error instanceof ApiError2&&(error.status===404||error.code==="origin_not_allowed"||error.code==="page_origin");if(refused)this.#refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown, offers no such list or does not allow ${location.origin}`),this.#render();return refused}#errorText(error){let code=error instanceof ApiError2?error.code:"";if(code==="rate_limited")return this.#t({id:"tzsBOP"});if(code==="network")return this.#t({id:"GQVIIl"});if(code==="no_email")return this.#t({id:"eku1-t"});return this.#t({id:"jWgNnM"})}#emit(type,detail){this.dispatchEvent(new CustomEvent(type,{detail,bubbles:!0,composed:!0}))}#failed(error){this.#emit("yuva-subscribe-error",{code:error instanceof ApiError2?error.code:"error"})}consentText(lists=this.#selected()){let custom=this.getAttribute("consent")?.trim();if(custom)return custom;let names=(lists.length?lists:this.lists).map((list)=>list.name),list=new Intl.ListFormat(this.locale,{type:"conjunction"}).format(names),inbox=this.#inbox?.name??"";return this.#t({id:"dMJfG5",values:{list,inbox}})}#selected(){return this.lists.filter((list)=>this.#chosen.has(list.id))}async#submit(){if(this.#phase!=="idle"||!this.channel)return;let lists=this.#selected(),email=this.#email.value.trim(),name=this.#name.value.trim(),asksName=this.getAttribute("name");if(this.#error=lists.length===0?this.#t({id:"-g5O6h"}):"",this.#emailError=this.#email.checkValidity()&&email?"":this.#t({id:"E_qvzP"}),this.#nameError=asksName==="required"&&!name?this.#t({id:"E_LjOR"}):"",this.#consentError=this.#consent.checked?"":this.#t({id:"lDEbTy"}),this.#error||this.#emailError||this.#nameError||this.#consentError){this.#render();let invalid=[this.#emailError&&this.#email,this.#nameError&&this.#name,this.#consentError&&this.#consent];for(let input of invalid)if(input)return input.focus();return}let channel=this.channel,generation=this.#generation,consent_text=this.consentText(lists);this.#phase="submitting",this.#render();let send=async(retry)=>{let wait=this.#tokenAt+tokenMinimumAge-Date.now();if(wait>0)await new Promise((resolve)=>setTimeout(resolve,wait));try{let{confirmation}=await createSubscription(fetcher,this.server,channel,{email,name:asksName==="optional"||asksName==="required"?name||void 0:void 0,list_ids:lists.map((list)=>list.id),locale:this.locale,page_url:location.href.split("#")[0].slice(0,2000),consent_text,form_token:this.#token,website:this.#trap.value||void 0});return this.#confirmation=confirmation,!0}catch(error){if(retry&&error instanceof ApiError2&&error.code==="form_token"){let fresh=await mailingLists(fetcher,this.server,channel);return this.#token=fresh.form_token,this.#tokenAt=Date.now(),send(!1)}throw error}};try{await send(!0)}catch(error){if(generation!==this.#generation)return;if(this.#failed(error),this.#phase="idle",this.#refusal(error))return;if(error instanceof ApiError2&&error.code==="invalid_email")return this.#emailError=this.#t({id:"E_qvzP"}),this.#render(),this.#email.focus();return this.#error=this.#errorText(error),this.#render()}if(generation!==this.#generation)return;this.#phase="done",this.#emit("yuva-subscribe",{lists:lists.map((list)=>list.id),confirmation:this.#confirmation}),this.#render()}async#toggle(item,on){let client=this.#client;if(!client||this.#busy.has(item.list.id))return;this.#busy.add(item.list.id),this.#error="",this.#render();try{if(on){let{state}=await client.subscribeList(item.list.id,{consent_text:this.consentText([item.list]),page_url:location.href.split("#")[0].slice(0,2000)});item.state=state,this.#emit("yuva-subscribe",{lists:[item.list.id],confirmation:state==="pending"})}else await client.unsubscribeList(item.list.id),item.state="unsubscribed"}catch(error){this.#failed(error),this.#error=this.#errorText(error)}if(this.#busy.delete(item.list.id),client===this.#client)this.#render()}#errorFor(input,text){if(input.setAttribute("aria-invalid",String(!!text)),!text)return input.removeAttribute("aria-describedby"),null;let id=`${input.id}-error`;input.setAttribute("aria-describedby",id);let error=el("p","error",text);return error.id=id,error}#check(text,checked,onChange,key){let label=el("label","check"),box=el("input");box.type="checkbox",box.checked=checked,box.dataset.key=key,box.addEventListener("change",()=>onChange(box.checked));let body=el("span","text");return body.append(...text),label.append(box,body),label}#lists(identity){if(!identity&&this.#offered.length<2)return null;let group=el("fieldset");group.append(el("legend","",this.#t({id:"h16FyT"})));for(let item of this.#offered){let text=[el("span","",item.list.name)];if(item.list.description)text.push(el("span","muted",item.list.description));if(identity){if(text.push(el("span","muted consent",this.consentText([item.list]))),item.state==="pending")text.push(el("span","muted",this.#t({id:"x6dU53"})))}let on=identity?item.state==="subscribed"||item.state==="pending":this.#chosen.has(item.list.id),label=this.#check(text,on,(checked)=>{if(identity)return void this.#toggle(item,checked);if(checked)this.#chosen.add(item.list.id);else this.#chosen.delete(item.list.id);this.#error="",this.#render()},item.list.id),box=label.querySelector("input");if(identity)box.setAttribute("role","switch"),box.setAttribute("aria-checked",String(box.checked)),box.addEventListener("keydown",(event)=>{if(event.key!=="Enter")return;event.preventDefault(),box.click()}),box.disabled=this.#busy.has(item.list.id);else box.disabled=this.#phase==="submitting";group.append(label)}return group}#form(){let form=el("form",this.getAttribute("layout")==="inline"?"inline":"");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#submit()});let busy=this.#phase==="submitting",lists=this.#lists(!1);if(lists)form.append(lists);let row=el("div","row"),errors=[],asksName=this.getAttribute("name");if(asksName==="optional"||asksName==="required"){this.#name.placeholder=asksName==="required"?this.#t({id:"q8yluz"}):this.#t({id:"YnOaHp"}),this.#name.setAttribute("aria-label",this.#name.placeholder),this.#name.required=asksName==="required",this.#name.disabled=busy,row.append(this.#name);let error=this.#errorFor(this.#name,this.#nameError);if(error)errors.push(error)}this.#email.placeholder=this.#t({id:"XJURKP"}),this.#email.setAttribute("aria-label",this.#email.placeholder),this.#email.disabled=busy,row.append(this.#email);let emailError=this.#errorFor(this.#email,this.#emailError);if(emailError)errors.push(emailError);let button=el("button","",busy?this.#t({id:"1w51t9"}):this.getAttribute("button-text")||this.#t({id:"EDl9kS"}));button.type="submit",button.disabled=busy,button.setAttribute("part","button"),row.append(button);let trap=el("div","trap");trap.setAttribute("aria-hidden","true"),trap.append(this.#trap);let consentText=el("span","",this.consentText()),consent=el("label","check consent");consent.setAttribute("part","consent"),this.#consent.disabled=busy;let body=el("span");body.append(consentText);let privacy=this.getAttribute("privacy-url");if(privacy&&/^https?:\/\//i.test(privacy)){let link=el("a","",this.#t({id:"ScJ9fj"}));link.href=privacy,link.target="_blank",link.rel="noopener noreferrer",body.append(" ",link)}consent.append(this.#consent,body);let consentError=this.#errorFor(this.#consent,this.#consentError);if(form.append(row,...errors,consent),consentError)form.append(consentError);return form.append(trap),form}#render(){if(this.#refused||!this.channel||this.#phase!=="loading"&&this.#offered.length===0&&!this.#error){this.#root.replaceChildren();return}let locale=this.locale;this.#messages=catalogs[locale]??messages;let dir=this.getAttribute("dir"),wrapper=el("div","frame");wrapper.dir=dir==="rtl"||dir==="ltr"?dir:directionOf(locale),wrapper.lang=locale;let brand=this.#inbox?.chat.launcher_color??this.#inbox?.branding.color;if(brand&&/^#[0-9a-f]{6}$/i.test(brand))wrapper.style.setProperty("--brand",brand),wrapper.style.setProperty("--brand-on",contrastOn(brand));let status="";if(this.#phase==="done")status=this.#confirmation?this.#t({id:"y3k2zM"}):this.#t({id:"rgySXy"});if(this.#status.textContent=status,this.#phase==="idle"||this.#phase==="submitting"){let content=this.#client?this.#lists(!0):this.#form();if(content)wrapper.append(content)}if(wrapper.append(this.#status),this.#error){let error=el("p","error",this.#error);error.setAttribute("role","alert"),wrapper.append(error)}let focusedKey,focused=null;try{focused=this.#root.activeElement}catch{}if(focused instanceof HTMLInputElement)focusedKey=focused.dataset.key;let style=el("style");style.textContent=styles,this.#root.replaceChildren(style,wrapper);let again=focusedKey?this.#root.querySelector(`[data-key="${focusedKey}"]`):focused;if(again instanceof HTMLElement&&again.isConnected)again.focus({preventScroll:!0})}}function defineSubscribe(){if(typeof customElements>"u")return;if(!customElements.get("yuva-subscribe"))customElements.define("yuva-subscribe",YuvaSubscribeElement)}YuvaSubscribeElement.loadClient=()=>import("./client-9wy8zy77.js");defineSubscribe();export{YuvaSubscribeElement,defineSubscribe};
@@ -0,0 +1,193 @@
1
+ import{randomId2,createYuvaClient2}from"./index-geeh5h34.js";import{richText}from"./index-jdxce2se.js";import{ApiError2}from"./index-gk84nm8f.js";import{launcherOf,readStored,writeStored}from"./index-98r96a7e.js";import{setupI18n}from"@lingui/core";var messages=JSON.parse(`{"-HY5kX":["New conversation"],"-f5Tkb":["Bad"],"09Tv5j":["Reconnecting…"],"0XGLbP":["Your sign-in has expired. Reload the page and try again."],"1EICzz":["We're away right now"],"4TqZiz":["Could not send your rating. Try again."],"6Uau97":["Skip"],"6gRgw8":["Retry"],"6lGaum":["Seen"],"ASr-r0":["Show older conversations"],"Amai22":["Chat is not available right now."],"E_qvzP":["Enter a valid e-mail address."],"GQVIIl":["You seem to be offline."],"JkW3Ph":["This file type is not accepted."],"JlFcis":["Send"],"KDw4GX":["Try again"],"M62PBt":["Nobody is available right now. Leave your e-mail and we'll send the reply there too."],"N7m8E-":["Attach files"],"NBdIgR":["Comment"],"OEEQKT":["Good"],"Pwqkdw":["Loading…"],"PxYAul":["Typing…"],"RzWUUK":["Write a message…"],"S63MQu":["All conversations"],"SOk0EB":["Thanks for your feedback"],"Sad2tK":["Sending…"],"SdV5Cn":["Send us a message and we will reply here."],"UY1vmE":["Attachment"],"VggdQJ":["Usually replies in ",["duration"]],"XJURKP":["E-mail address"],"YyNOE7":["Conversation"],"ZxJcgC":["Could not save your e-mail address. Try again."],"axQ1h6":["Anything you'd like to add? (optional)"],"eOu9Px":["The file is too large."],"h69WC6":["Sent"],"iGNUZJ":["Thanks! We'll e-mail you at ",["known"]," if you're gone when we reply."],"meAa31":["No conversations yet"],"nhTADq":["We'll reply as soon as we can"],"njBr8W":["you@example.com"],"oXOSPE":["Online"],"t7TeQU":["Messages"],"tHaDPf":[["name"]," is typing…"],"tfDRzk":["Save"],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uA8iBc":["How did we do?"],"upFvcp":["Not sent."],"w61W3L":["Remove ",["0"]],"xDAtGP":["Message"],"ydzYKJ":["You:"],"yz7wBu":["Close"],"zLzEI3":["Sign in to chat with us."]}`);var messages2=JSON.parse('{"-HY5kX":["Neue Unterhaltung"],"-f5Tkb":["Schlecht"],"09Tv5j":["Verbindung wird wiederhergestellt…"],"0XGLbP":["Ihre Anmeldung ist abgelaufen. Laden Sie die Seite neu und versuchen Sie es erneut."],"1EICzz":["Wir sind gerade nicht da"],"4TqZiz":["Ihre Bewertung konnte nicht gesendet werden. Versuchen Sie es erneut."],"6Uau97":["Überspringen"],"6gRgw8":["Erneut versuchen"],"6lGaum":["Gesehen"],"ASr-r0":["Ältere Unterhaltungen anzeigen"],"Amai22":["Der Chat ist gerade nicht verfügbar."],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"GQVIIl":["Sie scheinen offline zu sein."],"JkW3Ph":["Dieser Dateityp wird nicht akzeptiert."],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"M62PBt":["Gerade ist niemand erreichbar. Hinterlassen Sie Ihre E-Mail-Adresse, dann senden wir die Antwort auch dorthin."],"N7m8E-":["Dateien anhängen"],"NBdIgR":["Kommentar"],"OEEQKT":["Gut"],"Pwqkdw":["Wird geladen…"],"PxYAul":["Schreibt…"],"RzWUUK":["Nachricht schreiben…"],"S63MQu":["Alle Unterhaltungen"],"SOk0EB":["Danke für Ihr Feedback"],"Sad2tK":["Wird gesendet…"],"SdV5Cn":["Schreiben Sie uns, wir antworten hier."],"UY1vmE":["Anhang"],"VggdQJ":["Übliche Antwortzeit: ",["duration"]],"XJURKP":["E-Mail-Adresse"],"YyNOE7":["Unterhaltung"],"ZxJcgC":["Ihre E-Mail-Adresse konnte nicht gespeichert werden. Versuchen Sie es erneut."],"axQ1h6":["Möchten Sie noch etwas ergänzen? (optional)"],"eOu9Px":["Die Datei ist zu groß."],"h69WC6":["Gesendet"],"iGNUZJ":["Danke! Falls Sie nicht mehr da sind, wenn wir antworten, schreiben wir Ihnen an ",["known"],"."],"meAa31":["Noch keine Unterhaltungen"],"nhTADq":["Wir antworten so schnell wie möglich"],"njBr8W":["sie@beispiel.de"],"oXOSPE":["Online"],"t7TeQU":["Nachrichten"],"tHaDPf":[["name"]," schreibt…"],"tfDRzk":["Speichern"],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uA8iBc":["Wie zufrieden waren Sie?"],"upFvcp":["Nicht gesendet."],"w61W3L":[["0"]," entfernen"],"xDAtGP":["Nachricht"],"ydzYKJ":["Sie:"],"yz7wBu":["Schließen"],"zLzEI3":["Melden Sie sich an, um mit uns zu chatten."]}');var messages3=JSON.parse('{"-HY5kX":["Yeni konuşma"],"-f5Tkb":["Kötü"],"09Tv5j":["Yeniden bağlanıyor…"],"0XGLbP":["Oturumunuzun süresi doldu. Sayfayı yenileyip tekrar deneyin."],"1EICzz":["Şu anda uzaktayız"],"4TqZiz":["Değerlendirmeniz gönderilemedi. Tekrar deneyin."],"6Uau97":["Geç"],"6gRgw8":["Tekrar dene"],"6lGaum":["Görüldü"],"ASr-r0":["Eski konuşmaları göster"],"Amai22":["Sohbet şu anda kullanılamıyor."],"E_qvzP":["Geçerli bir e-posta adresi girin."],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"JkW3Ph":["Bu dosya türü kabul edilmiyor."],"JlFcis":["Gönder"],"KDw4GX":["Tekrar dene"],"M62PBt":["Şu anda müsait kimse yok. E-posta adresinizi bırakın, yanıtı oraya da gönderelim."],"N7m8E-":["Dosya ekle"],"NBdIgR":["Yorum"],"OEEQKT":["İyi"],"Pwqkdw":["Yükleniyor…"],"PxYAul":["Yazıyor…"],"RzWUUK":["Bir mesaj yazın…"],"S63MQu":["Tüm konuşmalar"],"SOk0EB":["Geri bildiriminiz için teşekkürler"],"Sad2tK":["Gönderiliyor…"],"SdV5Cn":["Bize bir mesaj gönderin, yanıtımız burada görünecek."],"UY1vmE":["Ek"],"VggdQJ":["Genellikle ",["duration"]," içinde yanıt verir"],"XJURKP":["E-posta adresi"],"YyNOE7":["Konuşma"],"ZxJcgC":["E-posta adresiniz kaydedilemedi. Tekrar deneyin."],"axQ1h6":["Eklemek istediğiniz bir şey var mı? (isteğe bağlı)"],"eOu9Px":["Dosya çok büyük."],"h69WC6":["Gönderildi"],"iGNUZJ":["Teşekkürler! Yanıtladığımızda burada değilseniz ",["known"]," adresine e-posta göndereceğiz."],"meAa31":["Henüz konuşma yok"],"nhTADq":["En kısa sürede yanıt vereceğiz"],"njBr8W":["siz@ornek.com"],"oXOSPE":["Çevrimiçi"],"t7TeQU":["Mesajlar"],"tHaDPf":[["name"]," yazıyor…"],"tfDRzk":["Kaydet"],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uA8iBc":["Nasıldık?"],"upFvcp":["Gönderilemedi."],"w61W3L":[["0"]," kaldır"],"xDAtGP":["Mesaj"],"ydzYKJ":["Siz:"],"yz7wBu":["Kapat"],"zLzEI3":["Bizimle sohbet etmek için giriş yapın."]}');var styles=`
2
+ [hidden] { display: none !important; }
3
+ .header {
4
+ display: flex;
5
+ align-items: center;
6
+ gap: 10px;
7
+ padding-block: 12px;
8
+ padding-inline: 14px 10px;
9
+ background: var(--yuva-accent);
10
+ color: var(--yuva-on-accent);
11
+ }
12
+ .heading { flex: 1; min-inline-size: 0; }
13
+ .title {
14
+ margin: 0;
15
+ font-size: 16px;
16
+ font-weight: 600;
17
+ overflow: hidden;
18
+ text-overflow: ellipsis;
19
+ white-space: nowrap;
20
+ }
21
+ .status { display: flex; align-items: center; gap: 6px; font-size: 13px; opacity: 0.9; }
22
+ .dot { inline-size: 8px; block-size: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 0 2px rgb(255 255 255 / 0.6); }
23
+ .dot.away { background: #9ca3af; }
24
+ .avatars { display: flex; }
25
+ .avatars .avatar { margin-inline-start: -8px; box-shadow: 0 0 0 2px var(--yuva-accent); }
26
+ .avatars .avatar:first-child { margin-inline-start: 0; }
27
+ .avatar {
28
+ display: grid;
29
+ place-items: center;
30
+ flex: none;
31
+ inline-size: 28px;
32
+ block-size: 28px;
33
+ border-radius: 50%;
34
+ background: var(--yuva-soft);
35
+ color: var(--yuva-fg);
36
+ font-size: 11px;
37
+ font-weight: 700;
38
+ text-transform: uppercase;
39
+ }
40
+ .icon {
41
+ display: grid;
42
+ place-items: center;
43
+ flex: none;
44
+ inline-size: 32px;
45
+ block-size: 32px;
46
+ padding: 0;
47
+ border: 0;
48
+ border-radius: 8px;
49
+ background: transparent;
50
+ color: inherit;
51
+ cursor: pointer;
52
+ }
53
+ .icon:hover { background: rgb(127 127 127 / 0.18); }
54
+ .icon:focus-visible { outline: 2px solid currentColor; outline-offset: -4px; }
55
+ [dir="rtl"] .flip { transform: scaleX(-1); }
56
+ .body { position: relative; flex: 1; min-block-size: 0; display: flex; flex-direction: column; }
57
+ .scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; padding: 14px; display: flex; flex-direction: column; gap: 4px; }
58
+ .center { flex: 1; display: grid; place-content: center; gap: 6px; padding: 24px; text-align: center; }
59
+ .empty { margin: 0; font-weight: 600; }
60
+ .hint { margin: 0; color: var(--yuva-muted); font-size: 14px; }
61
+ .list { list-style: none; margin: 0; padding: 6px; overflow-y: auto; flex: 1; }
62
+ .item {
63
+ display: flex;
64
+ gap: 10px;
65
+ align-items: center;
66
+ inline-size: 100%;
67
+ padding: 10px;
68
+ border: 0;
69
+ border-radius: 10px;
70
+ background: transparent;
71
+ color: inherit;
72
+ font: inherit;
73
+ text-align: start;
74
+ cursor: pointer;
75
+ }
76
+ .item:hover, .item:focus-visible { background: var(--yuva-soft); outline: none; }
77
+ .item-main { flex: 1; min-inline-size: 0; }
78
+ .item-top { display: flex; gap: 8px; justify-content: space-between; }
79
+ .item-subject, .item-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
80
+ .item-subject { font-weight: 600; }
81
+ .item-preview { color: var(--yuva-muted); font-size: 14px; }
82
+ .item.unread .item-preview { color: var(--yuva-fg); font-weight: 600; }
83
+ .item-time { flex: none; color: var(--yuva-muted); font-size: 12px; }
84
+ .unread-dot { flex: none; inline-size: 9px; block-size: 9px; border-radius: 50%; background: var(--yuva-accent); }
85
+ .primary {
86
+ margin: 10px;
87
+ padding: 10px 14px;
88
+ border: 0;
89
+ border-radius: 10px;
90
+ background: var(--yuva-accent);
91
+ color: var(--yuva-on-accent);
92
+ font: inherit;
93
+ font-weight: 600;
94
+ cursor: pointer;
95
+ }
96
+ .row { display: flex; gap: 8px; align-items: flex-end; max-inline-size: 85%; }
97
+ .row.mine { align-self: flex-end; }
98
+ .row.theirs .avatar { margin-block-end: 2px; }
99
+ .avatar img { inline-size: 100%; block-size: 100%; border-radius: 50%; object-fit: cover; }
100
+ .group-gap { margin-block-start: 8px; }
101
+ .author { margin: 6px 0 2px; margin-inline-start: 36px; color: var(--yuva-muted); font-size: 12px; }
102
+ .bubble {
103
+ padding: 8px 12px;
104
+ border-radius: 16px;
105
+ background: var(--yuva-soft);
106
+ overflow-wrap: anywhere;
107
+ white-space: normal;
108
+ }
109
+ .mine .bubble { background: var(--yuva-accent); color: var(--yuva-on-accent); border-end-end-radius: 4px; }
110
+ .theirs .bubble { border-end-start-radius: 4px; }
111
+ .bubble a { color: inherit; text-decoration: underline; }
112
+ .bubble code { font-family: ui-monospace, Menlo, monospace; font-size: 13px; padding: 1px 4px; border-radius: 4px; background: rgb(127 127 127 / 0.2); }
113
+ .bubble pre { margin: 4px 0; padding: 8px; border-radius: 8px; background: rgb(127 127 127 / 0.2); font-family: ui-monospace, Menlo, monospace; font-size: 13px; white-space: pre-wrap; }
114
+ .greeting { align-self: flex-start; max-inline-size: 85%; }
115
+ .files { display: flex; flex-direction: column; gap: 4px; margin-block-start: 4px; }
116
+ .files img { display: block; max-inline-size: 100%; max-block-size: 220px; border-radius: 10px; cursor: zoom-in; }
117
+ .file {
118
+ display: inline-flex;
119
+ gap: 6px;
120
+ align-items: center;
121
+ padding: 6px 10px;
122
+ border: 1px solid currentColor;
123
+ border-radius: 8px;
124
+ background: transparent;
125
+ color: inherit;
126
+ font: inherit;
127
+ font-size: 13px;
128
+ cursor: pointer;
129
+ }
130
+ .meta { align-self: flex-end; color: var(--yuva-muted); font-size: 12px; margin-block-start: 2px; }
131
+ .meta.failed { color: var(--yuva-danger); }
132
+ .link { padding: 0; border: 0; background: none; color: inherit; font: inherit; text-decoration: underline; cursor: pointer; }
133
+ .typing { display: flex; gap: 6px; align-items: center; color: var(--yuva-muted); font-size: 13px; margin-block-start: 6px; }
134
+ .typing i { display: inline-block; inline-size: 6px; block-size: 6px; border-radius: 50%; background: currentColor; animation: blink 1.2s infinite both; }
135
+ .typing i:nth-child(2) { animation-delay: 0.2s; }
136
+ .typing i:nth-child(3) { animation-delay: 0.4s; }
137
+ @keyframes blink { 0%, 80%, 100% { opacity: 0.25; } 40% { opacity: 1; } }
138
+ @media (prefers-reduced-motion: reduce) { .typing i { animation: none; } }
139
+ .card { margin-block-start: 10px; padding: 12px; border: 1px solid var(--yuva-border); border-radius: 12px; font-size: 14px; }
140
+ .card p { margin: 0 0 8px; }
141
+ .card form { display: flex; gap: 6px; }
142
+ .card input {
143
+ flex: 1;
144
+ min-inline-size: 0;
145
+ padding: 8px 10px;
146
+ border: 1px solid var(--yuva-border);
147
+ border-radius: 8px;
148
+ background: var(--yuva-bg);
149
+ color: inherit;
150
+ font: inherit;
151
+ }
152
+ .card button { padding: 8px 12px; border: 0; border-radius: 8px; background: var(--yuva-accent); color: var(--yuva-on-accent); font: inherit; font-weight: 600; cursor: pointer; }
153
+ .card .error { margin: 6px 0 0; color: var(--yuva-danger); }
154
+ .card button:disabled { opacity: 0.6; cursor: default; }
155
+ .rate { text-align: center; }
156
+ .choices { display: flex; justify-content: center; gap: 10px; }
157
+ .card .choice { inline-size: 44px; block-size: 44px; padding: 0; border: 1px solid var(--yuva-border); border-radius: 50%; background: var(--yuva-bg); font-size: 20px; line-height: 1; }
158
+ .card .choice:hover:not(:disabled), .card .choice[aria-pressed="true"] { border-color: var(--yuva-accent); box-shadow: 0 0 0 1px var(--yuva-accent); }
159
+ .card .choice:disabled { opacity: 1; }
160
+ .card .choice:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
161
+ .rate .choices + p { margin: 8px 0 0; }
162
+ .rate form { flex-direction: column; margin-block-start: 10px; }
163
+ .rate textarea { box-sizing: border-box; inline-size: 100%; padding: 8px 10px; border: 1px solid var(--yuva-border); border-radius: 8px; background: var(--yuva-bg); color: inherit; font: inherit; resize: vertical; }
164
+ .rate .actions { display: flex; justify-content: flex-end; align-items: center; gap: 14px; }
165
+ .card .link { padding: 0; background: none; color: var(--yuva-muted); font-weight: 400; }
166
+ .composer { border-block-start: 1px solid var(--yuva-border); padding: 8px; }
167
+ .composer form { display: flex; gap: 4px; align-items: flex-end; }
168
+ .composer textarea {
169
+ flex: 1;
170
+ min-inline-size: 0;
171
+ box-sizing: border-box;
172
+ block-size: 38px;
173
+ max-block-size: 140px;
174
+ padding: 8px 10px;
175
+ border: 0;
176
+ border-radius: 10px;
177
+ background: transparent;
178
+ color: inherit;
179
+ font: inherit;
180
+ resize: none;
181
+ outline: none;
182
+ }
183
+ .composer .icon { color: var(--yuva-muted); }
184
+ .composer .send { color: var(--yuva-accent); }
185
+ .composer .send:disabled { opacity: 0.4; cursor: default; }
186
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 6px 6px; }
187
+ .chip { display: inline-flex; gap: 4px; align-items: center; max-inline-size: 100%; padding: 2px 4px 2px 10px; border-radius: 999px; background: var(--yuva-soft); font-size: 13px; }
188
+ .chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-inline-size: 180px; }
189
+ .chip .icon { inline-size: 22px; block-size: 22px; }
190
+ .banner { padding: 6px 12px; background: var(--yuva-soft); color: var(--yuva-muted); font-size: 13px; text-align: center; }
191
+ @media (max-width: 480px) { .composer textarea, .card input, .card textarea { font-size: 16px; } }
192
+ .sr { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
193
+ `;var catalogs={en:messages,tr:messages3,de:messages2},maxFiles=10,groupGap=300000,icons={close:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',back:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>',attach:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 11.5l-8.3 8.3a5 5 0 01-7-7L13 4.5a3.3 3.3 0 014.7 4.7l-8.3 8.3a1.7 1.7 0 01-2.4-2.4L14.5 7.6"/></svg>',send:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M3.4 20.4l17.5-7.5a1 1 0 000-1.8L3.4 3.6a1 1 0 00-1.4 1.2L4.5 12l-2.5 7.2a1 1 0 001.4 1.2zM4.5 12h7"/></svg>',file:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M14 3H6v18h12V7z M14 3v4h4"/></svg>'};function el(tag,className,text){let element=document.createElement(tag);if(className)element.className=className;if(text!==void 0)element.textContent=text;return element}function iconButton(icon,label,onClick,className="icon"){let button=el("button",className);return button.type="button",button.innerHTML=icon,button.setAttribute("aria-label",label),button.title=label,button.addEventListener("click",onClick),button}var time=(value)=>Date.parse(value),byCreated=(a,b)=>time(a.created_at)-time(b.created_at),byActivity=(a,b)=>time(b.last_message_at??b.created_at)-time(a.last_message_at??a.created_at),authorKey=(m)=>m.author.type==="contact"?"contact":`${m.author.type}:${m.author.name??""}`,isImage=(a)=>/^image\/(png|jpeg|gif|webp)$/.test(a.content_type);class Chat{#host;#i18n;#client;#inbox=null;#contact=null;#phase="loading";#error="";#starting=null;#beginning=null;#conversations=new Map;#conversationCursor;#threads=new Map;#pending=[];#typing=new Map;#view=null;#reconnecting=!1;#files=[];#typingSentAt=0;#typingIdle=null;#blobs=new Map;#blobLoads=new Map;#avatars=new Map;#emailSaved=!1;#emailError="";#connectedBefore=!1;#ratings=new Map;#rateCard=el("div","card rate");#rateComment=el("textarea");#rateKey="";#rateFor=null;#header=el("header","header");#banner=el("div","banner");#body=el("div","body");#scroll=el("div","scroll");#email=el("div","card");#emailInput=el("input");#composer=el("div","composer");#chips=el("div","chips");#textarea=el("textarea");#fileInput=el("input");#sendButton;#attachButton;#live=el("div","sr");#scrollThread;#atEnd=!0;constructor(host){this.#host=host;let{server,channel}=host.config();this.#client=createYuvaClient2({server,channel:channel??"",identityToken:()=>host.identityToken()}),this.#client.on("event",(message)=>this.#event(message)),this.#client.on("connection",({state,attempt})=>{if(state!=="reconnecting")return;this.#reconnecting=attempt>0,this.#renderBanner()}),this.#client.on("session",({session,renewed})=>{if(this.#setInbox(session.inbox),this.#contact=session.contact,renewed)this.#reload();else if(!this.#beginning)this.#client.connect().catch(()=>{return})}),this.#setLocale(),this.#live.setAttribute("aria-live","polite"),this.#scroll.addEventListener("scroll",()=>{if(this.#atEnd=this.#scroll.scrollHeight-this.#scroll.scrollTop-this.#scroll.clientHeight<48,this.#scroll.scrollTop<60&&this.#view?.kind==="thread"&&this.#view.id)this.#loadMessages(this.#view.id,!0)}),this.#textarea.rows=1,this.#textarea.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing)event.preventDefault(),this.#send()}),this.#textarea.addEventListener("input",()=>{this.#autosize(),this.#syncSend(),this.#typingInput()}),this.#textarea.addEventListener("paste",(event)=>{let files=Array.from(event.clipboardData?.files??[]);if(files.length===0)return;event.preventDefault(),this.#addFiles(files)}),this.#fileInput.type="file",this.#fileInput.multiple=!0,this.#fileInput.hidden=!0,this.#fileInput.addEventListener("change",()=>{this.#addFiles(Array.from(this.#fileInput.files??[])),this.#fileInput.value=""}),this.#attachButton=iconButton(icons.attach,"",()=>this.#fileInput.click()),this.#sendButton=iconButton(icons.send,"",()=>void this.#send(),"icon send");let form=el("form");form.addEventListener("submit",(event)=>{event.preventDefault(),this.#send()}),form.append(this.#attachButton,this.#textarea,this.#sendButton,this.#fileInput),this.#composer.append(this.#chips,form),this.#emailInput.type="email",this.#emailInput.required=!0,this.#emailInput.autocomplete="email",this.#rateComment.rows=2,this.#rateComment.maxLength=2000,this.#rateComment.dir="auto",document.addEventListener("visibilitychange",this.#onVisible),window.addEventListener("online",this.#onVisible),this.#renderAll(),this.#start()}update(){this.#setLocale(),this.#renderAll()}opened(){if(this.#phase==="error"){this.#starting=null,this.#start();return}if(this.#phase==="ready")this.#client.token?this.#refreshSession():this.#preview().then(()=>this.#render()).catch(()=>{return});if(this.#render(),this.#scrollToEnd(),this.#markRead(),this.#host.config().layout==="launcher")this.#textarea.focus({preventScroll:!0})}closed(){this.#stopTyping()}identityChanged(){this.#reset(),this.#start()}async signOut(){let signingOut=this.#client.signOut();if(this.#reset(),await signingOut,this.#host.isOpen())this.#start();else this.#render()}destroy(){this.#client.reset(),this.#stopTyping(),document.removeEventListener("visibilitychange",this.#onVisible),window.removeEventListener("online",this.#onVisible);for(let url of this.#blobs.values())URL.revokeObjectURL(url)}#reset(){this.#client.reset(),this.#starting=null,this.#beginning=null,this.#inbox=null,this.#contact=null,this.#phase="loading",this.#conversations.clear(),this.#threads.clear(),this.#pending=[],this.#ratings.clear(),this.#rateKey="",this.#view=null,this.#connectedBefore=!1,this.#host.setUnread(0)}#onVisible=()=>{if(document.visibilityState!=="visible")return;this.#client.reconnect(),this.#markRead(),this.#refreshInbox()};#setLocale(){let{locale}=this.#host.config();this.#i18n=setupI18n({locale,messages:{[locale]:catalogs[locale]??messages}})}#t(descriptor){return this.#i18n._(descriptor)}#start(){return this.#starting??=(async()=>{this.#phase="loading",this.#render();let{channel}=this.#host.config();if(!channel)throw new ApiError2(0,"not_configured");if(await this.#host.identityToken()||readStored(channel).session)await this.#begin();else if(await this.#preview(),!this.#inbox?.chat.allow_anonymous)throw new ApiError2(403,"anonymous_not_allowed");if(this.#phase="ready",!this.#view){let list=this.#sorted();if(this.#view=list.length>1?{kind:"list"}:{kind:"thread",id:list[0]?.id??null},this.#view.kind==="thread"&&this.#view.id)await this.#loadMessages(this.#view.id)}this.#render(),this.#scrollToEnd(),this.#markRead()})().catch((error)=>{if(this.#starting=null,this.#refusal(error))return;this.#phase="error",this.#error=error instanceof ApiError2?error.code:"error",this.#render()}),this.#starting}async#preview(){let inbox=await this.#fetchInbox();if(!this.#client.token)this.#setInbox(inbox)}#fetchInbox(){if(!this.#host.config().channel)throw new ApiError2(0,"not_configured");return this.#client.channelSettings()}#setInbox(inbox){let{channel}=this.#host.config();this.#inbox=inbox;let launcher=launcherOf(inbox);if(this.#host.setLauncher(launcher),channel)writeStored(channel,{...readStored(channel),launcher})}async#refreshInbox(){if(this.#phase!=="ready")return;try{this.#setInbox(await this.#fetchInbox()),this.#render()}catch(error){this.#refusal(error,!0)}}#refusal(error,channelRequest=!this.#client.token){let refused=error instanceof ApiError2&&(error.code==="origin_not_allowed"||error.status===404&&channelRequest);if(refused)this.#host.refused();return refused}#begin(){return this.#beginning??=(async()=>{await this.#client.start(),await this.#loadConversations(),await this.#client.connect()})().finally(()=>{this.#beginning=null}),this.#beginning}async#refreshSession(){try{await this.#client.refresh(),this.#render()}catch{}}async#loadConversations(more=!1){let page=await this.#client.listConversations({limit:50,cursor:more?this.#conversationCursor:void 0});if(!more)this.#conversations.clear();for(let conversation of page.items)this.#conversations.set(conversation.id,conversation);this.#conversationCursor=page.next_cursor,this.#syncUnread()}async#reload(){await this.#loadConversations();let current=this.#view?.kind==="thread"?this.#view.id:null;for(let id of this.#threads.keys())if(id!==current)this.#threads.delete(id);if(current)this.#threads.delete(current),await this.#loadMessages(current);this.#render()}async#loadMessages(id,older=!1){let thread=this.#threads.get(id);if(!thread)thread={messages:[],complete:!1,loading:!1},this.#threads.set(id,thread);if(thread.loading||older&&(thread.complete||!thread.cursor))return;thread.loading=!0;let before=this.#scroll.scrollHeight-this.#scroll.scrollTop;try{let page=await this.#client.listMessages(id,{order:"desc",limit:30,cursor:older?thread.cursor:void 0}),known=new Set(thread.messages.map((m)=>m.id));thread.messages=[...thread.messages,...page.items.filter((m)=>!known.has(m.id))].sort(byCreated),thread.cursor=page.next_cursor,thread.complete=!page.next_cursor}finally{thread.loading=!1}if(older)this.#render(),this.#scroll.scrollTop=this.#scroll.scrollHeight-before}#event(message){switch(message.type){case"ready":if(this.#reconnecting=!1,this.#renderBanner(),this.#connectedBefore)this.#refreshInbox();this.#connectedBefore=!0;return;case"inbox.updated":{let asked=this.#inbox?.ask_for_rating;if(this.#setInbox(message.data),asked!==void 0&&asked!==message.data.ask_for_rating)this.#loadConversations().then(()=>this.#render()).catch(()=>{return});break}case"resync_required":this.#reload();return;case"presence":if(this.#inbox)this.#inbox={...this.#inbox,presence:message.data};break;case"conversation.created":if(!this.#conversations.has(message.data.id))this.#conversations.set(message.data.id,message.data);if(this.#view?.kind==="thread"&&this.#view.id===null&&this.#conversations.size>1)this.#view=this.#pending.some((p)=>p.conversation===null)?this.#view:{kind:"list"};this.#syncUnread();break;case"conversation.updated":{let conversation=this.#conversations.get(message.data.id),{status,can_rate,rating}=message.data;if(conversation)this.#conversations.set(conversation.id,{...conversation,status,can_rate,rating});if(!can_rate)this.#ratings.delete(message.data.id);break}case"message.created":case"message.updated":this.#upsertMessage(message.data,message.type==="message.created");break;case"read":{let conversation=this.#conversations.get(message.data.conversation_id),previous=conversation?.last_read_by_member_at;if(conversation&&(!previous||time(message.data.read_at)>time(previous)))this.#conversations.set(conversation.id,{...conversation,last_read_by_member_at:message.data.read_at});break}case"typing":{let id=message.data.conversation_id,previous=this.#typing.get(id);if(previous)clearTimeout(previous.timer);if(message.data.typing){let name=message.data.author.name??"";this.#typing.set(id,{name,timer:setTimeout(()=>this.#typing.delete(id)&&this.#render(),8000)})}else this.#typing.delete(id);break}}this.#render()}#upsertMessage(message,created){let id=message.conversation_id,thread=this.#threads.get(id);if(thread){let index=thread.messages.findIndex((m)=>m.id===message.id);if(index>=0)thread.messages[index]=message;else thread.messages=[...thread.messages,message].sort(byCreated)}if(message.client_id)this.#pending=this.#pending.filter((p)=>p.client_id!==message.client_id);let conversation=this.#conversations.get(id);if(!conversation){this.#client.getConversation(id).then((c)=>{this.#conversations.set(c.id,c),this.#syncUnread(),this.#render()}).catch(()=>{return});return}if(created){let text=message.body.replace(/\s+/g," ").trim();if(this.#conversations.set(id,{...conversation,last_message:{id:message.id,author_type:message.author.type,text:text.length>140?`${text.slice(0,139)}…`:text,created_at:message.created_at},last_message_at:message.created_at,unread:conversation.unread||message.author.type!=="contact"}),message.author.type!=="contact"){let typing=this.#typing.get(id);if(typing)clearTimeout(typing.timer);this.#typing.delete(id),this.#announce(message)}}this.#syncUnread(),this.#markRead()}#announce(message){this.#live.textContent=`${message.author.name||this.#inbox?.name||""}: ${message.body.slice(0,200)}`}#syncUnread(){let count=0;for(let conversation of this.#conversations.values())if(conversation.unread)count++;this.#host.setUnread(count)}#visibleThread(){if(!this.#host.isOpen()||document.visibilityState!=="visible")return null;return this.#view?.kind==="thread"?this.#view.id:null}#markRead(){let id=this.#visibleThread(),conversation=id?this.#conversations.get(id):void 0;if(!id||!conversation?.unread)return;this.#conversations.set(id,{...conversation,unread:!1}),this.#syncUnread(),this.#client.markRead(id).catch(()=>{let current=this.#conversations.get(id);if(current)this.#conversations.set(id,{...current,unread:!0});this.#syncUnread()})}#addFiles(files){this.#files=[...this.#files,...files].slice(0,maxFiles),this.#renderChips(),this.#syncSend(),this.#textarea.focus()}#autosize(){if(this.#textarea.style.blockSize="",this.#textarea.value==="")return;this.#textarea.style.blockSize="auto",this.#textarea.style.blockSize=`${Math.max(38,Math.min(this.#textarea.scrollHeight,140))}px`}#syncSend(){this.#sendButton.disabled=this.#textarea.value.trim()===""&&this.#files.length===0}#typingInput(){let id=this.#view?.kind==="thread"?this.#view.id:null;if(!id||this.#textarea.value.trim()===""){this.#stopTyping();return}if(Date.now()-this.#typingSentAt>3000)this.#typingSentAt=Date.now(),this.#client.setTyping(id,!0).catch(()=>{return});if(this.#typingIdle)clearTimeout(this.#typingIdle);this.#typingIdle=setTimeout(()=>this.#stopTyping(),4000)}#stopTyping(){if(this.#typingIdle)clearTimeout(this.#typingIdle);if(this.#typingIdle=null,this.#typingSentAt===0)return;this.#typingSentAt=0;let id=this.#view?.kind==="thread"?this.#view.id:null;if(id)this.#client.setTyping(id,!1).catch(()=>{return})}async#send(){if(this.#phase!=="ready"||this.#view?.kind!=="thread")return;let body=this.#textarea.value.trim(),files=this.#files;if(!body&&files.length===0)return;if(this.#view.id===null&&this.#pending.some((p)=>p.conversation===null))return;this.#stopTyping(),this.#textarea.value="",this.#files=[],this.#autosize(),this.#renderChips(),this.#syncSend();let pending={client_id:randomId2(),conversation:this.#view.id,body,files,state:"sending"};this.#pending.push(pending),this.#render(),this.#scrollToEnd(),await this.#deliver(pending)}async#deliver(pending){pending.state="sending",this.#render();let input={body:pending.body,files:pending.files,client_id:pending.client_id};try{if(pending.conversation===null){let created=await this.#client.startConversation(input),id=created.conversation.id;if(!this.#conversations.has(id))this.#conversations.set(id,created.conversation);if(!this.#threads.has(id))this.#threads.set(id,{messages:[],complete:!0,loading:!1});if(this.#view?.kind==="thread"&&this.#view.id===null)this.#view={kind:"thread",id};this.#upsertMessage(created.message,!1)}else{let message=await this.#client.sendMessage(pending.conversation,input);this.#upsertMessage(message,!0)}this.#pending=this.#pending.filter((p)=>p!==pending)}catch(error){let status=error instanceof ApiError2?error.status:0;pending.state=status===413||status===415?"refused":"failed",pending.status=status}this.#render(),this.#scrollToEnd()}async rate(id,rating,comment){try{let conversation=await this.#client.rate(id,rating,comment);return this.#conversations.set(conversation.id,conversation),this.#ratings.delete(id),this.#render(),conversation}catch(error){if(error instanceof ApiError2&&error.status===409){let current=await this.#client.getConversation(id).catch(()=>null);if(current)this.#conversations.set(current.id,current);this.#ratings.delete(id),this.#render()}throw error}}#choose(id,choice){if(this.#ratings.get(id)?.state==="sending")return;if(this.#ratings.set(id,{choice,state:"choosing"}),this.#render(),this.#rateComment.focus({preventScroll:!0}),this.#atEnd)this.#scrollToEnd()}async#submitRating(id,withComment){let draft=this.#ratings.get(id);if(!draft||draft.state==="sending")return;draft.state="sending",this.#render();try{await this.rate(id,draft.choice,withComment?this.#rateComment.value:void 0),this.#rateComment.value=""}catch(error){if(error instanceof ApiError2&&error.status===409)return;draft.state="failed",this.#render()}}async#saveEmail(){let email=this.#emailInput.value.trim();if(!email||!this.#emailInput.checkValidity()){this.#emailError=this.#t({id:"E_qvzP"}),this.#renderEmail();return}try{this.#contact=await this.#client.setEmail(email),this.#emailSaved=!0,this.#emailError=""}catch{this.#emailError=this.#t({id:"ZxJcgC"})}this.#renderEmail()}#attachmentUrl(attachment){let cached=this.#blobs.get(attachment.id);if(cached)return Promise.resolve(cached);let load=this.#blobLoads.get(attachment.id);if(!load)load=this.#client.attachment(attachment.id).then((blob)=>{let url=URL.createObjectURL(blob);return this.#blobs.set(attachment.id,url),url}),load.catch(()=>this.#blobLoads.delete(attachment.id)),this.#blobLoads.set(attachment.id,load);return load}async#download(attachment){let url=await this.#attachmentUrl(attachment),a=el("a");a.href=url,a.download=attachment.filename,a.rel="noopener",a.click()}#sorted(){return[...this.#conversations.values()].sort(byActivity)}#nobodyAvailable(){let inbox=this.#inbox;if(!inbox)return!1;return!inbox.open_now||inbox.mode==="async"||!inbox.presence?.available}#scrollToEnd(){this.#atEnd=!0,this.#scroll.scrollTop=this.#scroll.scrollHeight,requestAnimationFrame(()=>{if(this.#atEnd)this.#scroll.scrollTop=this.#scroll.scrollHeight})}#renderAll(){this.#textarea.placeholder=this.#t({id:"RzWUUK"}),this.#textarea.setAttribute("aria-label",this.#t({id:"xDAtGP"})),this.#attachButton.setAttribute("aria-label",this.#t({id:"N7m8E-"})),this.#attachButton.title=this.#t({id:"N7m8E-"}),this.#sendButton.setAttribute("aria-label",this.#t({id:"JlFcis"})),this.#sendButton.title=this.#t({id:"JlFcis"}),this.#emailInput.placeholder=this.#t({id:"njBr8W"}),this.#emailInput.setAttribute("aria-label",this.#t({id:"XJURKP"})),this.#syncSend(),this.#renderChips(),this.#render()}#render(){let panel=this.#host.panel;if(panel.childElementCount===0){let style=el("style");style.textContent=styles,panel.append(style,this.#header,this.#banner,this.#body,this.#live),this.#header.id="yuva-title",panel.setAttribute("aria-labelledby","yuva-title")}if(this.#renderHeader(),this.#renderBanner(),this.#phase!=="ready"){this.#scrollThread=void 0;let center=el("div","center");if(this.#phase==="loading")center.append(el("p","hint",this.#t({id:"Pwqkdw"})));else{center.append(el("p","empty",this.#errorText()));let retry=el("button","primary",this.#t({id:"KDw4GX"}));retry.type="button",retry.addEventListener("click",()=>{this.#starting=null,this.#start()}),center.append(retry)}this.#body.replaceChildren(center);return}if(this.#view?.kind==="list")this.#renderList();else this.#renderThread()}#errorText(){switch(this.#error){case"anonymous_not_allowed":return this.#t({id:"zLzEI3"});case"invalid_identity_token":return this.#t({id:"0XGLbP"});case"rate_limited":return this.#t({id:"tzsBOP"});case"network":return this.#t({id:"GQVIIl"});default:return this.#t({id:"Amai22"})}}#renderHeader(){let{layout}=this.#host.config(),inbox=this.#inbox,children=[],view=this.#view;if(this.#phase==="ready"&&view?.kind==="thread"&&(this.#conversations.size>1||view.id===null&&this.#conversations.size>0))children.push(iconButton(icons.back,this.#t({id:"S63MQu"}),()=>{this.#stopTyping(),this.#view={kind:"list"},this.#render()}));let heading=el("div","heading");if(heading.append(el("h2","title",inbox?.name||this.#t({id:"t7TeQU"}))),inbox){let status=el("div","status");if(inbox.mode==="live"&&inbox.open_now&&inbox.presence?.available){let avatars=el("div","avatars");for(let member of inbox.presence?.members.slice(0,3)??[]){let avatar=el("span","avatar",member.initials||"•");avatar.title=member.name,avatars.append(avatar)}status.append(avatars,el("span","dot"),el("span","",this.#t({id:"oXOSPE"})))}else if(!inbox.open_now||inbox.mode==="live")status.append(el("span","dot away"),el("span","",this.#t({id:"1EICzz"})));else status.append(el("span","",this.#replyTime(inbox.expected_reply_minutes)));heading.append(status)}if(children.push(heading),layout==="launcher")children.push(iconButton(icons.close,this.#t({id:"yz7wBu"}),()=>this.#host.close()));this.#header.replaceChildren(...children)}#replyTime(minutes){if(!minutes)return this.#t({id:"nhTADq"});let{locale}=this.#host.config(),[value,unit]=minutes<60?[minutes,"minute"]:minutes<1440?[Math.round(minutes/60),"hour"]:[Math.round(minutes/1440),"day"],duration=new Intl.NumberFormat(locale,{style:"unit",unit,unitDisplay:"long"}).format(value);return this.#t({id:"VggdQJ",values:{duration}})}#renderBanner(){this.#banner.hidden=!this.#reconnecting,this.#banner.textContent=this.#t({id:"09Tv5j"})}#renderList(){this.#scrollThread=void 0;let{locale}=this.#host.config(),list=el("ul","list"),today=new Date().toDateString();for(let conversation of this.#sorted()){let button=el("button",conversation.unread?"item unread":"item");button.type="button";let main=el("div","item-main"),top=el("div","item-top");top.append(el("span","item-subject",conversation.subject||this.#inbox?.name||this.#t({id:"YyNOE7"})));let at=new Date(conversation.last_message_at??conversation.created_at);top.append(el("span","item-time",new Intl.DateTimeFormat(locale,at.toDateString()===today?{timeStyle:"short"}:{month:"short",day:"numeric"}).format(at)));let preview=conversation.last_message?`${conversation.last_message.author_type==="contact"?this.#t({id:"ydzYKJ"})+" ":""}${conversation.last_message.text||this.#t({id:"UY1vmE"})}`:"",previewLine=el("div","item-preview",preview.replace(/\*\*|`/g,""));if(previewLine.dir="auto",main.append(top,previewLine),button.append(main),conversation.unread)button.append(el("span","unread-dot"));button.addEventListener("click",()=>void this.#openThread(conversation.id));let item=el("li");item.append(button),list.append(item)}if(this.#conversationCursor){let more=el("button","link",this.#t({id:"ASr-r0"}));more.type="button",more.style.margin="8px auto",more.style.display="block",more.addEventListener("click",()=>void this.#loadConversations(!0).then(()=>this.#render())),list.append(more)}let start=el("button","primary",this.#t({id:"-HY5kX"}));start.type="button",start.addEventListener("click",()=>{this.#view={kind:"thread",id:null},this.#render(),this.#textarea.focus()}),this.#body.replaceChildren(list,start)}async#openThread(id){if(this.#view={kind:"thread",id},this.#render(),!this.#threads.get(id)?.complete&&!this.#threads.get(id)?.messages.length)await this.#loadMessages(id).catch(()=>{return});this.#render(),this.#scrollToEnd(),this.#markRead()}#avatar(author){let avatar=el("span","avatar",author.initials||""),url=author.avatar_url,state=url?this.#avatars.get(url):!1;if(!url||state===!1)return avatar;let img=el("img");if(img.alt="",img.referrerPolicy="no-referrer",state)return img.src=url,avatar.replaceChildren(img),avatar;return img.addEventListener("load",()=>{if(this.#avatars.set(url,!0),avatar.isConnected)avatar.replaceChildren(img)}),img.addEventListener("error",()=>this.#avatars.set(url,!1)),img.src=url,avatar}#renderThread(){let view=this.#view;if(view?.kind!=="thread")return;let id=view.id,sameThread=this.#scrollThread===id,atEnd=this.#atEnd,thread=id?this.#threads.get(id):void 0,messages=thread?.messages??[],pending=this.#pending.filter((p)=>p.conversation===id),nodes=[],greeting=this.#inbox?.chat.greeting;if(!thread||thread.complete){if(greeting){let bubble=el("div","bubble greeting");bubble.append(richText(greeting)),nodes.push(bubble)}else if(messages.length===0&&pending.length===0){let center=el("div","center");center.append(el("p","empty",this.#t({id:"meAa31"})),el("p","hint",this.#t({id:"SdV5Cn"}))),nodes.push(center)}}else if(thread.loading)nodes.push(el("p","hint",this.#t({id:"Pwqkdw"})));messages.forEach((message,i)=>{let previous=messages[i-1],next=messages[i+1]??(pending.length>0?null:void 0),mine=message.author.type==="contact",starts=!previous||authorKey(previous)!==authorKey(message)||time(message.created_at)-time(previous.created_at)>groupGap,ends=next===void 0||(next===null?!mine:authorKey(next)!==authorKey(message)||time(next.created_at)-time(message.created_at)>groupGap);if(!mine&&starts&&message.author.name)nodes.push(el("div","author",message.author.name));let row=el("div",`row ${mine?"mine":"theirs"}${starts&&i>0?" group-gap":""}`);if(!mine){let avatar=this.#avatar(message.author);if(!ends)avatar.style.visibility="hidden";row.append(avatar)}let bubble=el("div","bubble");if(bubble.dir="auto",bubble.title=new Date(message.created_at).toLocaleString(this.#host.config().locale),message.body.trim())bubble.append(richText(message.body));if(message.attachments.length>0)bubble.append(this.#renderAttachments(message.attachments));if(row.append(bubble),nodes.push(row),ends){let meta=this.#formatTime(message.created_at);if(mine&&i===messages.length-1&&pending.length===0){let readAt=id?this.#conversations.get(id)?.last_read_by_member_at:void 0,seen=readAt&&time(readAt)>=time(message.created_at);meta+=` · ${seen?this.#t({id:"6lGaum"}):this.#t({id:"h69WC6"})}`}let line=el("div","meta",meta);if(!mine)line.style.alignSelf="flex-start";if(!mine)line.style.marginInlineStart="36px";nodes.push(line)}});let conversation=id?this.#conversations.get(id):void 0,rate=conversation?this.#renderRating(conversation):null;if(rate)nodes.push(rate);pending.forEach((item,i)=>{let row=el("div",`row mine${i===0&&messages.length>0&&messages[messages.length-1]?.author.type!=="contact"?" group-gap":""}`),bubble=el("div","bubble");if(bubble.dir="auto",item.body)bubble.append(richText(item.body));if(item.files.length>0){let files=el("div","files");for(let file of item.files)files.append(el("span","file",file.name||"image"));bubble.append(files)}if(row.append(bubble),nodes.push(row),item.state==="failed"){let line=el("div","meta failed",`${this.#t({id:"upFvcp"})} `),retry=el("button","link",this.#t({id:"6gRgw8"}));retry.type="button",retry.addEventListener("click",()=>void this.#deliver(item)),line.append(retry),nodes.push(line)}else if(item.state==="refused"){let reason=item.status===413?this.#t({id:"eOu9Px"}):this.#t({id:"JkW3Ph"});nodes.push(el("div","meta failed",`${this.#t({id:"upFvcp"})} ${reason}`))}else if(i===pending.length-1)nodes.push(el("div","meta",this.#t({id:"Sad2tK"})))});let typing=id?this.#typing.get(id):void 0;if(typing){let line=el("div","typing");line.append(el("i"),el("i"),el("i"));let name=typing.name;line.append(el("span","",name?this.#t({id:"tHaDPf",values:{name}}):this.#t({id:"PxYAul"}))),nodes.push(line)}let focused=this.#scroll.getRootNode().activeElement===this.#rateComment,{selectionStart,selectionEnd}=this.#rateComment;if(this.#scroll.replaceChildren(...nodes),focused&&this.#rateComment.isConnected)this.#rateComment.focus({preventScroll:!0}),this.#rateComment.setSelectionRange(selectionStart,selectionEnd);if(this.#renderEmail(),this.#body.firstChild!==this.#scroll)this.#body.replaceChildren(this.#scroll,this.#email,this.#composer);if(this.#scrollThread=id,!sameThread||atEnd)this.#scrollToEnd()}#renderRating(conversation){let rated=conversation.status==="closed"?conversation.rating:void 0,draft=conversation.can_rate&&this.#inbox?.ask_for_rating?this.#ratings.get(conversation.id):void 0;if(!rated&&!(conversation.can_rate&&this.#inbox?.ask_for_rating))return null;let card=this.#rateCard,key=[conversation.id,rated,draft?.choice,draft?.state,this.#host.config().locale].join(":");if(key===this.#rateKey)return card;if(this.#rateKey=key,this.#rateFor!==conversation.id)this.#rateFor=conversation.id,this.#rateComment.value="";let question=this.#t({id:"uA8iBc"});card.setAttribute("role","group"),card.setAttribute("aria-label",question);let choices=el("div","choices");for(let value of["good","bad"]){if(rated&&rated!==value)continue;let button=el("button","choice",value==="good"?"\uD83D\uDC4D":"\uD83D\uDC4E");button.type="button";let label=value==="good"?this.#t({id:"OEEQKT"}):this.#t({id:"-f5Tkb"});button.setAttribute("aria-label",label),button.title=label,button.setAttribute("aria-pressed",String((rated??draft?.choice)===value)),button.disabled=!!rated||draft?.state==="sending",button.addEventListener("click",()=>this.#choose(conversation.id,value)),choices.append(button)}if(rated)return card.replaceChildren(choices,el("p","",this.#t({id:"SOk0EB"}))),card;if(card.replaceChildren(el("p","",question),choices),!draft)return card;this.#rateComment.placeholder=this.#t({id:"axQ1h6"}),this.#rateComment.setAttribute("aria-label",this.#t({id:"NBdIgR"})),this.#rateComment.disabled=draft.state==="sending";let form=el("form");form.addEventListener("submit",(event)=>{event.preventDefault(),this.#submitRating(conversation.id,!0)});let skip=el("button","link",this.#t({id:"6Uau97"}));skip.type="button",skip.disabled=draft.state==="sending",skip.addEventListener("click",()=>void this.#submitRating(conversation.id,!1));let send=el("button","",draft.state==="sending"?this.#t({id:"Sad2tK"}):this.#t({id:"JlFcis"}));send.type="submit",send.disabled=draft.state==="sending";let actions=el("div","actions");if(actions.append(skip,send),form.append(this.#rateComment,actions),card.append(form),draft.state==="failed")card.append(el("p","error",this.#t({id:"4TqZiz"})));return card}#renderAttachments(attachments){let files=el("div","files");for(let attachment of attachments)if(isImage(attachment)){let img=el("img");img.alt=attachment.filename;let cached=this.#blobs.get(attachment.id);if(cached)img.src=cached;else this.#attachmentUrl(attachment).then((url)=>{img.src=url}).catch(()=>{return});img.addEventListener("load",()=>{if(this.#atEnd)this.#scroll.scrollTop=this.#scroll.scrollHeight}),img.addEventListener("click",()=>void this.#download(attachment)),files.append(img)}else{let button=el("button","file");button.type="button",button.innerHTML=icons.file,button.append(el("span","",attachment.filename)),button.addEventListener("click",()=>void this.#download(attachment)),files.append(button)}return files}#formatTime(value){return new Intl.DateTimeFormat(this.#host.config().locale,{timeStyle:"short"}).format(new Date(value))}#renderEmail(){let contact=this.#contact,chat=this.#inbox?.chat,sent=(this.#view?.kind==="thread"?this.#view.id:null)!==null||this.#pending.length>0,known=contact?.email||contact?.typed_email,show=!!chat?.ask_email_offline&&this.#nobodyAvailable()&&sent&&(!known||this.#emailSaved);if(this.#email.hidden=!show,!show)return;if(known&&this.#emailSaved){this.#email.replaceChildren(el("p","",this.#t({id:"iGNUZJ",values:{known}})));return}if(this.#email.querySelector("form")){let error=this.#email.querySelector(".error");if(error)error.textContent=this.#emailError;else if(this.#emailError)this.#email.append(el("p","error",this.#emailError));return}let form=el("form");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#saveEmail()});let save=el("button","",this.#t({id:"tfDRzk"}));if(save.type="submit",form.append(this.#emailInput,save),this.#email.replaceChildren(el("p","",this.#t({id:"M62PBt"})),form),this.#emailError)this.#email.append(el("p","error",this.#emailError))}#renderChips(){this.#chips.hidden=this.#files.length===0,this.#chips.replaceChildren(...this.#files.map((file,index)=>{let chip=el("span","chip");return chip.append(el("span","",file.name||"image"),iconButton(icons.close,this.#t({id:"w61W3L",values:{0:file.name}}),()=>{this.#files=this.#files.filter((_,i)=>i!==index),this.#renderChips(),this.#syncSend()})),chip}))}}function mount(host){return new Chat(host)}export{mount};
@@ -1,4 +1,4 @@
1
- class c extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function g(e,t,n,{method:s="GET",json:i,body:o,headers:a={},token:p,blob:r}={}){if(a={...a},p)a.Authorization=`Bearer ${p}`;let m=o;if(i!==void 0)a["Content-Type"]="application/json",m=JSON.stringify(i);let l;try{l=await e(t+n,{method:s,headers:a,body:m,credentials:"omit"})}catch{throw new c(0,"network")}if(!l.ok){let u="error";try{u=(await l.json()).code??u}catch{}throw new c(l.status,u)}if(l.status===204)return;return r?await l.blob():await l.json()}function P(e,t,n){return g(e,t,`/client/v1/channels/${encodeURIComponent(n)}/lists`)}function b(e,t,n,s){return g(e,t,`/client/v1/channels/${encodeURIComponent(n)}/subscriptions`,{method:"POST",json:s})}class C{server;socketClass;handlers;#s=null;#o=0;#p=0;#t=null;#a=!0;constructor(e,t,n){this.server=e;this.socketClass=t;this.handlers=n}get connected(){return this.#s?.readyState===1}start(){if(this.#a=!1,!this.#s)this.#r()}stop(){if(this.#a=!0,this.#t)clearTimeout(this.#t);this.#t=null;let e=this.#s;this.#s=null,e?.close(1000)}reset(){this.#o=0}nudge(){if(this.#a||this.#s)return;if(this.#t)clearTimeout(this.#t);this.#t=null,this.#r()}#r(){let e=this.handlers.token();if(!e||this.#a)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#o>0)t.searchParams.set("last_event_id",String(this.#o));let n;try{n=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#n();return}this.#s=n,n.onmessage=(s)=>{let i;try{i=JSON.parse(String(s.data))}catch{return}if(i.type==="ready")this.#p=0,this.#o=Math.max(this.#o,i.last_event_id);else if("id"in i&&typeof i.id==="number")this.#o=Math.max(this.#o,i.id);this.handlers.event(i)},n.onclose=(s)=>{if(this.#s!==n)return;if(this.#s=null,this.#a)return;if(s.code===1008){this.#o=0,this.handlers.sessionEnded();return}this.#n()}}#n(){if(this.#a||this.#t)return;let e=this.#p++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#t=setTimeout(()=>{this.#t=null,this.#r()},t)}}function I(e,t,n){let s=new URL("/account/connect",e);return s.searchParams.set("channel",t),s.searchParams.set("origin",n),s.href}function T(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function R(e,t,{width:n=460,height:s=640}={}){let i=new URL(e).origin,o=location.origin,a=Math.max(0,(window.screenX??0)+((window.outerWidth??n)-n)/2),p=Math.max(0,(window.screenY??0)+((window.outerHeight??s)-s)/2),r=window.open(I(e,t,o),"yuva-reader",`popup=yes,width=${n},height=${s},left=${Math.round(a)},top=${Math.round(p)}`);if(!r)return Promise.reject(new c(0,"popup_blocked"));return new Promise((m,l)=>{let u=!1,f=()=>{u=!0,window.removeEventListener("message",S),clearInterval(v)},S=(h)=>{if(u||h.origin!==i||h.source&&h.source!==r)return;let d=h.data;if(!T(d)||d.channel_key!==t||d.origin!==o)return;f();try{r.close()}catch{}m({token:d.token,expires_at:d.expires_at,reader:d.reader})},v=setInterval(()=>{let h=!1;try{h=r.closed}catch{}if(!h)return;clearInterval(v),setTimeout(()=>{if(u)return;f(),l(new c(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",S)})}function x(e){return`yuva:${e}`}function w(e,t){return`yuva:reader:${e} ${t}`}function k(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function M(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t));return typeof n.sub==="string"?n.sub:null}catch{return null}}function U(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n)}}function y(e){let t=new URLSearchParams;for(let[s,i]of Object.entries(e))if(i!==void 0)t.set(s,String(i));let n=t.toString();return n?`?${n}`:""}function E(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function _(e,t,n){let s=[];for(let[i,o]of e)s.push(`--${n}\r
1
+ class c extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function g(e,t,n,{method:s="GET",json:i,body:o,headers:a={},token:p,blob:r}={}){if(a={...a},p)a.Authorization=`Bearer ${p}`;let m=o;if(i!==void 0)a["Content-Type"]="application/json",m=JSON.stringify(i);let l;try{l=await e(t+n,{method:s,headers:a,body:m,credentials:"omit"})}catch{throw new c(0,"network")}if(!l.ok){let u="error";try{u=(await l.json()).code??u}catch{}throw new c(l.status,u)}if(l.status===204)return;return r?await l.blob():await l.json()}function P(e,t,n){return g(e,t,`/client/v1/channels/${encodeURIComponent(n)}/lists`)}function b(e,t,n,s){return g(e,t,`/client/v1/channels/${encodeURIComponent(n)}/subscriptions`,{method:"POST",json:s})}class C{server;socketClass;handlers;#s=null;#o=0;#p=0;#t=null;#a=!0;constructor(e,t,n){this.server=e;this.socketClass=t;this.handlers=n}get connected(){return this.#s?.readyState===1}start(){if(this.#a=!1,!this.#s&&!this.#t)this.#r()}stop(){if(this.#a=!0,this.#t)clearTimeout(this.#t);this.#t=null;let e=this.#s;this.#s=null,e?.close(1000)}reset(){this.#o=0}nudge(){if(this.#a||this.#s)return;if(this.#t)clearTimeout(this.#t);this.#t=null,this.#r()}#r(){let e=this.handlers.token();if(!e||this.#a)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#o>0)t.searchParams.set("last_event_id",String(this.#o));let n;try{n=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#n();return}this.#s=n,n.onmessage=(s)=>{let i;try{i=JSON.parse(String(s.data))}catch{return}if(i.type==="ready")this.#p=0,this.#o=Math.max(this.#o,i.last_event_id);else if("id"in i&&typeof i.id==="number")this.#o=Math.max(this.#o,i.id);this.handlers.event(i)},n.onclose=(s)=>{if(this.#s!==n)return;if(this.#s=null,this.#a)return;if(s.code===1008){this.#o=0,this.handlers.sessionEnded();return}this.#n()}}#n(){if(this.#a||this.#t)return;let e=this.#p++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#t=setTimeout(()=>{this.#t=null,this.#r()},t)}}function I(e,t,n){let s=new URL("/account/connect",e);return s.searchParams.set("channel",t),s.searchParams.set("origin",n),s.href}function T(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function R(e,t,{width:n=460,height:s=640}={}){let i=new URL(e).origin,o=location.origin,a=Math.max(0,(window.screenX??0)+((window.outerWidth??n)-n)/2),p=Math.max(0,(window.screenY??0)+((window.outerHeight??s)-s)/2),r=window.open(I(e,t,o),"yuva-reader",`popup=yes,width=${n},height=${s},left=${Math.round(a)},top=${Math.round(p)}`);if(!r)return Promise.reject(new c(0,"popup_blocked"));return new Promise((m,l)=>{let u=!1,f=()=>{u=!0,window.removeEventListener("message",S),clearInterval(v)},S=(h)=>{if(u||h.origin!==i||h.source&&h.source!==r)return;let d=h.data;if(!T(d)||d.channel_key!==t||d.origin!==o)return;f();try{r.close()}catch{}m({token:d.token,expires_at:d.expires_at,reader:d.reader})},v=setInterval(()=>{let h=!1;try{h=r.closed}catch{}if(!h)return;clearInterval(v),setTimeout(()=>{if(u)return;f(),l(new c(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",S)})}function x(e){return`yuva:${e}`}function w(e,t){return`yuva:reader:${e} ${t}`}function k(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function M(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=JSON.parse(atob(t));return typeof n.sub==="string"?n.sub:null}catch{return null}}function U(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,n)=>void e.set(t,n)}}function y(e){let t=new URLSearchParams;for(let[s,i]of Object.entries(e))if(i!==void 0)t.set(s,String(i));let n=t.toString();return n?`?${n}`:""}function E(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function _(e,t,n){let s=[];for(let[i,o]of e)s.push(`--${n}\r
2
2
  Content-Disposition: form-data; name="${i}"\r
3
3
  \r
4
4
  ${o}\r
package/dist/yuva-chat.js CHANGED
@@ -6,7 +6,7 @@ That means you use raw catalog or your catalog doesn't have a translation for th
6
6
  ICU features such as interpolation and plurals will not work properly for that message.
7
7
 
8
8
  Please compile your catalog first.
9
- `);if(S(c)&&ee.test(c))return te(c);if(S(c))return c;return Pe(c,this._locale,this._locales)(t,i?.formats)}t=this._.bind(this);date(e,t){return B(this._locales||this._locale,e,t)}number(e,t){return N(this._locales||this._locale,e,t)}}function K(e={}){return new se(e)}var je=K();var Y=JSON.parse(`{"-HY5kX":["New conversation"],"-f5Tkb":["Bad"],"09Tv5j":["Reconnecting…"],"0XGLbP":["Your sign-in has expired. Reload the page and try again."],"1EICzz":["We're away right now"],"4TqZiz":["Could not send your rating. Try again."],"6Uau97":["Skip"],"6gRgw8":["Retry"],"6lGaum":["Seen"],"ASr-r0":["Show older conversations"],"Amai22":["Chat is not available right now."],"E_qvzP":["Enter a valid e-mail address."],"GQVIIl":["You seem to be offline."],"JkW3Ph":["This file type is not accepted."],"JlFcis":["Send"],"KDw4GX":["Try again"],"M62PBt":["Nobody is available right now. Leave your e-mail and we'll send the reply there too."],"N7m8E-":["Attach files"],"NBdIgR":["Comment"],"OEEQKT":["Good"],"Pwqkdw":["Loading…"],"PxYAul":["Typing…"],"RzWUUK":["Write a message…"],"S63MQu":["All conversations"],"SOk0EB":["Thanks for your feedback"],"Sad2tK":["Sending…"],"SdV5Cn":["Send us a message and we will reply here."],"UY1vmE":["Attachment"],"VggdQJ":["Usually replies in ",["duration"]],"XJURKP":["E-mail address"],"YyNOE7":["Conversation"],"ZxJcgC":["Could not save your e-mail address. Try again."],"axQ1h6":["Anything you'd like to add? (optional)"],"eOu9Px":["The file is too large."],"h69WC6":["Sent"],"iGNUZJ":["Thanks! We'll e-mail you at ",["known"]," if you're gone when we reply."],"meAa31":["No conversations yet"],"nhTADq":["We'll reply as soon as we can"],"njBr8W":["you@example.com"],"oXOSPE":["Online"],"t7TeQU":["Messages"],"tHaDPf":[["name"]," is typing…"],"tfDRzk":["Save"],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uA8iBc":["How did we do?"],"upFvcp":["Not sent."],"w61W3L":["Remove ",["0"]],"xDAtGP":["Message"],"ydzYKJ":["You:"],"yz7wBu":["Close"],"zLzEI3":["Sign in to chat with us."]}`);var re=JSON.parse('{"-HY5kX":["Neue Unterhaltung"],"-f5Tkb":["Schlecht"],"09Tv5j":["Verbindung wird wiederhergestellt…"],"0XGLbP":["Ihre Anmeldung ist abgelaufen. Laden Sie die Seite neu und versuchen Sie es erneut."],"1EICzz":["Wir sind gerade nicht da"],"4TqZiz":["Ihre Bewertung konnte nicht gesendet werden. Versuchen Sie es erneut."],"6Uau97":["Überspringen"],"6gRgw8":["Erneut versuchen"],"6lGaum":["Gesehen"],"ASr-r0":["Ältere Unterhaltungen anzeigen"],"Amai22":["Der Chat ist gerade nicht verfügbar."],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"GQVIIl":["Sie scheinen offline zu sein."],"JkW3Ph":["Dieser Dateityp wird nicht akzeptiert."],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"M62PBt":["Gerade ist niemand erreichbar. Hinterlassen Sie Ihre E-Mail-Adresse, dann senden wir die Antwort auch dorthin."],"N7m8E-":["Dateien anhängen"],"NBdIgR":["Kommentar"],"OEEQKT":["Gut"],"Pwqkdw":["Wird geladen…"],"PxYAul":["Schreibt…"],"RzWUUK":["Nachricht schreiben…"],"S63MQu":["Alle Unterhaltungen"],"SOk0EB":["Danke für Ihr Feedback"],"Sad2tK":["Wird gesendet…"],"SdV5Cn":["Schreiben Sie uns, wir antworten hier."],"UY1vmE":["Anhang"],"VggdQJ":["Übliche Antwortzeit: ",["duration"]],"XJURKP":["E-Mail-Adresse"],"YyNOE7":["Unterhaltung"],"ZxJcgC":["Ihre E-Mail-Adresse konnte nicht gespeichert werden. Versuchen Sie es erneut."],"axQ1h6":["Möchten Sie noch etwas ergänzen? (optional)"],"eOu9Px":["Die Datei ist zu groß."],"h69WC6":["Gesendet"],"iGNUZJ":["Danke! Falls Sie nicht mehr da sind, wenn wir antworten, schreiben wir Ihnen an ",["known"],"."],"meAa31":["Noch keine Unterhaltungen"],"nhTADq":["Wir antworten so schnell wie möglich"],"njBr8W":["sie@beispiel.de"],"oXOSPE":["Online"],"t7TeQU":["Nachrichten"],"tHaDPf":[["name"]," schreibt…"],"tfDRzk":["Speichern"],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uA8iBc":["Wie zufrieden waren Sie?"],"upFvcp":["Nicht gesendet."],"w61W3L":[["0"]," entfernen"],"xDAtGP":["Nachricht"],"ydzYKJ":["Sie:"],"yz7wBu":["Schließen"],"zLzEI3":["Melden Sie sich an, um mit uns zu chatten."]}');var oe=JSON.parse('{"-HY5kX":["Yeni konuşma"],"-f5Tkb":["Kötü"],"09Tv5j":["Yeniden bağlanıyor…"],"0XGLbP":["Oturumunuzun süresi doldu. Sayfayı yenileyip tekrar deneyin."],"1EICzz":["Şu anda uzaktayız"],"4TqZiz":["Değerlendirmeniz gönderilemedi. Tekrar deneyin."],"6Uau97":["Geç"],"6gRgw8":["Tekrar dene"],"6lGaum":["Görüldü"],"ASr-r0":["Eski konuşmaları göster"],"Amai22":["Sohbet şu anda kullanılamıyor."],"E_qvzP":["Geçerli bir e-posta adresi girin."],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"JkW3Ph":["Bu dosya türü kabul edilmiyor."],"JlFcis":["Gönder"],"KDw4GX":["Tekrar dene"],"M62PBt":["Şu anda müsait kimse yok. E-posta adresinizi bırakın, yanıtı oraya da gönderelim."],"N7m8E-":["Dosya ekle"],"NBdIgR":["Yorum"],"OEEQKT":["İyi"],"Pwqkdw":["Yükleniyor…"],"PxYAul":["Yazıyor…"],"RzWUUK":["Bir mesaj yazın…"],"S63MQu":["Tüm konuşmalar"],"SOk0EB":["Geri bildiriminiz için teşekkürler"],"Sad2tK":["Gönderiliyor…"],"SdV5Cn":["Bize bir mesaj gönderin, yanıtımız burada görünecek."],"UY1vmE":["Ek"],"VggdQJ":["Genellikle ",["duration"]," içinde yanıt verir"],"XJURKP":["E-posta adresi"],"YyNOE7":["Konuşma"],"ZxJcgC":["E-posta adresiniz kaydedilemedi. Tekrar deneyin."],"axQ1h6":["Eklemek istediğiniz bir şey var mı? (isteğe bağlı)"],"eOu9Px":["Dosya çok büyük."],"h69WC6":["Gönderildi"],"iGNUZJ":["Teşekkürler! Yanıtladığımızda burada değilseniz ",["known"]," adresine e-posta göndereceğiz."],"meAa31":["Henüz konuşma yok"],"nhTADq":["En kısa sürede yanıt vereceğiz"],"njBr8W":["siz@ornek.com"],"oXOSPE":["Çevrimiçi"],"t7TeQU":["Mesajlar"],"tHaDPf":[["name"]," yazıyor…"],"tfDRzk":["Kaydet"],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uA8iBc":["Nasıldık?"],"upFvcp":["Gönderilemedi."],"w61W3L":[["0"]," kaldır"],"xDAtGP":["Mesaj"],"ydzYKJ":["Siz:"],"yz7wBu":["Kapat"],"zLzEI3":["Bizimle sohbet etmek için giriş yapın."]}');function ae(e){return{position:e.chat.launcher_position,color:e.chat.launcher_color??e.branding.color}}function le(e){return`yuva:${e}`}function F(e){try{let t=localStorage.getItem(le(e));return t?JSON.parse(t):{}}catch{return{}}}function ce(e,t){try{localStorage.setItem(le(e),JSON.stringify(t))}catch{}}class f extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function I(e,t,i,{method:n="GET",json:s,body:o,headers:a={},token:l,blob:c}={}){if(a={...a},l)a.Authorization=`Bearer ${l}`;let h=o;if(s!==void 0)a["Content-Type"]="application/json",h=JSON.stringify(s);let p;try{p=await e(t+i,{method:n,headers:a,body:h,credentials:"omit"})}catch{throw new f(0,"network")}if(!p.ok){let u="error";try{u=(await p.json()).code??u}catch{}throw new f(p.status,u)}if(p.status===204)return;return c?await p.blob():await p.json()}function de(e,t,i){return I(e,t,`/client/v1/channels/${encodeURIComponent(i)}/lists`)}function he(e,t,i,n){return I(e,t,`/client/v1/channels/${encodeURIComponent(i)}/subscriptions`,{method:"POST",json:n})}class W{server;socketClass;handlers;#s=null;#m=0;#n=0;#r=null;#y=!0;constructor(e,t,i){this.server=e;this.socketClass=t;this.handlers=i}get connected(){return this.#s?.readyState===1}start(){if(this.#y=!1,!this.#s)this.#a()}stop(){if(this.#y=!0,this.#r)clearTimeout(this.#r);this.#r=null;let e=this.#s;this.#s=null,e?.close(1000)}reset(){this.#m=0}nudge(){if(this.#y||this.#s)return;if(this.#r)clearTimeout(this.#r);this.#r=null,this.#a()}#a(){let e=this.handlers.token();if(!e||this.#y)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#m>0)t.searchParams.set("last_event_id",String(this.#m));let i;try{i=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#u();return}this.#s=i,i.onmessage=(n)=>{let s;try{s=JSON.parse(String(n.data))}catch{return}if(s.type==="ready")this.#n=0,this.#m=Math.max(this.#m,s.last_event_id);else if("id"in s&&typeof s.id==="number")this.#m=Math.max(this.#m,s.id);this.handlers.event(s)},i.onclose=(n)=>{if(this.#s!==i)return;if(this.#s=null,this.#y)return;if(n.code===1008){this.#m=0,this.handlers.sessionEnded();return}this.#u()}}#u(){if(this.#y||this.#r)return;let e=this.#n++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#r=setTimeout(()=>{this.#r=null,this.#a()},t)}}function Ee(e,t,i){let n=new URL("/account/connect",e);return n.searchParams.set("channel",t),n.searchParams.set("origin",i),n.href}function Te(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function ue(e,t,{width:i=460,height:n=640}={}){let s=new URL(e).origin,o=location.origin,a=Math.max(0,(window.screenX??0)+((window.outerWidth??i)-i)/2),l=Math.max(0,(window.screenY??0)+((window.outerHeight??n)-n)/2),c=window.open(Ee(e,t,o),"yuva-reader",`popup=yes,width=${i},height=${n},left=${Math.round(a)},top=${Math.round(l)}`);if(!c)return Promise.reject(new f(0,"popup_blocked"));return new Promise((h,p)=>{let u=!1,y=()=>{u=!0,window.removeEventListener("message",g),clearInterval(_)},g=(b)=>{if(u||b.origin!==s||b.source&&b.source!==c)return;let d=b.data;if(!Te(d)||d.channel_key!==t||d.origin!==o)return;y();try{c.close()}catch{}h({token:d.token,expires_at:d.expires_at,reader:d.reader})},_=setInterval(()=>{let b=!1;try{b=c.closed}catch{}if(!b)return;clearInterval(_),setTimeout(()=>{if(u)return;y(),p(new f(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",g)})}function pe(e){return`yuva:${e}`}function fe(e,t){return`yuva:reader:${e} ${t}`}function M(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function ze(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i.sub==="string"?i.sub:null}catch{return null}}function Re(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,i)=>void e.set(t,i)}}function J(e){let t=new URLSearchParams;for(let[n,s]of Object.entries(e))if(s!==void 0)t.set(n,String(s));let i=t.toString();return i?`?${i}`:""}function De(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function Ie(e,t,i){let n=[];for(let[s,o]of e)n.push(`--${i}\r
9
+ `);if(S(c)&&ee.test(c))return te(c);if(S(c))return c;return Pe(c,this._locale,this._locales)(t,i?.formats)}t=this._.bind(this);date(e,t){return B(this._locales||this._locale,e,t)}number(e,t){return N(this._locales||this._locale,e,t)}}function K(e={}){return new se(e)}var je=K();var Y=JSON.parse(`{"-HY5kX":["New conversation"],"-f5Tkb":["Bad"],"09Tv5j":["Reconnecting…"],"0XGLbP":["Your sign-in has expired. Reload the page and try again."],"1EICzz":["We're away right now"],"4TqZiz":["Could not send your rating. Try again."],"6Uau97":["Skip"],"6gRgw8":["Retry"],"6lGaum":["Seen"],"ASr-r0":["Show older conversations"],"Amai22":["Chat is not available right now."],"E_qvzP":["Enter a valid e-mail address."],"GQVIIl":["You seem to be offline."],"JkW3Ph":["This file type is not accepted."],"JlFcis":["Send"],"KDw4GX":["Try again"],"M62PBt":["Nobody is available right now. Leave your e-mail and we'll send the reply there too."],"N7m8E-":["Attach files"],"NBdIgR":["Comment"],"OEEQKT":["Good"],"Pwqkdw":["Loading…"],"PxYAul":["Typing…"],"RzWUUK":["Write a message…"],"S63MQu":["All conversations"],"SOk0EB":["Thanks for your feedback"],"Sad2tK":["Sending…"],"SdV5Cn":["Send us a message and we will reply here."],"UY1vmE":["Attachment"],"VggdQJ":["Usually replies in ",["duration"]],"XJURKP":["E-mail address"],"YyNOE7":["Conversation"],"ZxJcgC":["Could not save your e-mail address. Try again."],"axQ1h6":["Anything you'd like to add? (optional)"],"eOu9Px":["The file is too large."],"h69WC6":["Sent"],"iGNUZJ":["Thanks! We'll e-mail you at ",["known"]," if you're gone when we reply."],"meAa31":["No conversations yet"],"nhTADq":["We'll reply as soon as we can"],"njBr8W":["you@example.com"],"oXOSPE":["Online"],"t7TeQU":["Messages"],"tHaDPf":[["name"]," is typing…"],"tfDRzk":["Save"],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uA8iBc":["How did we do?"],"upFvcp":["Not sent."],"w61W3L":["Remove ",["0"]],"xDAtGP":["Message"],"ydzYKJ":["You:"],"yz7wBu":["Close"],"zLzEI3":["Sign in to chat with us."]}`);var re=JSON.parse('{"-HY5kX":["Neue Unterhaltung"],"-f5Tkb":["Schlecht"],"09Tv5j":["Verbindung wird wiederhergestellt…"],"0XGLbP":["Ihre Anmeldung ist abgelaufen. Laden Sie die Seite neu und versuchen Sie es erneut."],"1EICzz":["Wir sind gerade nicht da"],"4TqZiz":["Ihre Bewertung konnte nicht gesendet werden. Versuchen Sie es erneut."],"6Uau97":["Überspringen"],"6gRgw8":["Erneut versuchen"],"6lGaum":["Gesehen"],"ASr-r0":["Ältere Unterhaltungen anzeigen"],"Amai22":["Der Chat ist gerade nicht verfügbar."],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"GQVIIl":["Sie scheinen offline zu sein."],"JkW3Ph":["Dieser Dateityp wird nicht akzeptiert."],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"M62PBt":["Gerade ist niemand erreichbar. Hinterlassen Sie Ihre E-Mail-Adresse, dann senden wir die Antwort auch dorthin."],"N7m8E-":["Dateien anhängen"],"NBdIgR":["Kommentar"],"OEEQKT":["Gut"],"Pwqkdw":["Wird geladen…"],"PxYAul":["Schreibt…"],"RzWUUK":["Nachricht schreiben…"],"S63MQu":["Alle Unterhaltungen"],"SOk0EB":["Danke für Ihr Feedback"],"Sad2tK":["Wird gesendet…"],"SdV5Cn":["Schreiben Sie uns, wir antworten hier."],"UY1vmE":["Anhang"],"VggdQJ":["Übliche Antwortzeit: ",["duration"]],"XJURKP":["E-Mail-Adresse"],"YyNOE7":["Unterhaltung"],"ZxJcgC":["Ihre E-Mail-Adresse konnte nicht gespeichert werden. Versuchen Sie es erneut."],"axQ1h6":["Möchten Sie noch etwas ergänzen? (optional)"],"eOu9Px":["Die Datei ist zu groß."],"h69WC6":["Gesendet"],"iGNUZJ":["Danke! Falls Sie nicht mehr da sind, wenn wir antworten, schreiben wir Ihnen an ",["known"],"."],"meAa31":["Noch keine Unterhaltungen"],"nhTADq":["Wir antworten so schnell wie möglich"],"njBr8W":["sie@beispiel.de"],"oXOSPE":["Online"],"t7TeQU":["Nachrichten"],"tHaDPf":[["name"]," schreibt…"],"tfDRzk":["Speichern"],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uA8iBc":["Wie zufrieden waren Sie?"],"upFvcp":["Nicht gesendet."],"w61W3L":[["0"]," entfernen"],"xDAtGP":["Nachricht"],"ydzYKJ":["Sie:"],"yz7wBu":["Schließen"],"zLzEI3":["Melden Sie sich an, um mit uns zu chatten."]}');var oe=JSON.parse('{"-HY5kX":["Yeni konuşma"],"-f5Tkb":["Kötü"],"09Tv5j":["Yeniden bağlanıyor…"],"0XGLbP":["Oturumunuzun süresi doldu. Sayfayı yenileyip tekrar deneyin."],"1EICzz":["Şu anda uzaktayız"],"4TqZiz":["Değerlendirmeniz gönderilemedi. Tekrar deneyin."],"6Uau97":["Geç"],"6gRgw8":["Tekrar dene"],"6lGaum":["Görüldü"],"ASr-r0":["Eski konuşmaları göster"],"Amai22":["Sohbet şu anda kullanılamıyor."],"E_qvzP":["Geçerli bir e-posta adresi girin."],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"JkW3Ph":["Bu dosya türü kabul edilmiyor."],"JlFcis":["Gönder"],"KDw4GX":["Tekrar dene"],"M62PBt":["Şu anda müsait kimse yok. E-posta adresinizi bırakın, yanıtı oraya da gönderelim."],"N7m8E-":["Dosya ekle"],"NBdIgR":["Yorum"],"OEEQKT":["İyi"],"Pwqkdw":["Yükleniyor…"],"PxYAul":["Yazıyor…"],"RzWUUK":["Bir mesaj yazın…"],"S63MQu":["Tüm konuşmalar"],"SOk0EB":["Geri bildiriminiz için teşekkürler"],"Sad2tK":["Gönderiliyor…"],"SdV5Cn":["Bize bir mesaj gönderin, yanıtımız burada görünecek."],"UY1vmE":["Ek"],"VggdQJ":["Genellikle ",["duration"]," içinde yanıt verir"],"XJURKP":["E-posta adresi"],"YyNOE7":["Konuşma"],"ZxJcgC":["E-posta adresiniz kaydedilemedi. Tekrar deneyin."],"axQ1h6":["Eklemek istediğiniz bir şey var mı? (isteğe bağlı)"],"eOu9Px":["Dosya çok büyük."],"h69WC6":["Gönderildi"],"iGNUZJ":["Teşekkürler! Yanıtladığımızda burada değilseniz ",["known"]," adresine e-posta göndereceğiz."],"meAa31":["Henüz konuşma yok"],"nhTADq":["En kısa sürede yanıt vereceğiz"],"njBr8W":["siz@ornek.com"],"oXOSPE":["Çevrimiçi"],"t7TeQU":["Mesajlar"],"tHaDPf":[["name"]," yazıyor…"],"tfDRzk":["Kaydet"],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uA8iBc":["Nasıldık?"],"upFvcp":["Gönderilemedi."],"w61W3L":[["0"]," kaldır"],"xDAtGP":["Mesaj"],"ydzYKJ":["Siz:"],"yz7wBu":["Kapat"],"zLzEI3":["Bizimle sohbet etmek için giriş yapın."]}');function ae(e){return{position:e.chat.launcher_position,color:e.chat.launcher_color??e.branding.color}}function le(e){return`yuva:${e}`}function F(e){try{let t=localStorage.getItem(le(e));return t?JSON.parse(t):{}}catch{return{}}}function ce(e,t){try{localStorage.setItem(le(e),JSON.stringify(t))}catch{}}class f extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function I(e,t,i,{method:n="GET",json:s,body:o,headers:a={},token:l,blob:c}={}){if(a={...a},l)a.Authorization=`Bearer ${l}`;let h=o;if(s!==void 0)a["Content-Type"]="application/json",h=JSON.stringify(s);let p;try{p=await e(t+i,{method:n,headers:a,body:h,credentials:"omit"})}catch{throw new f(0,"network")}if(!p.ok){let u="error";try{u=(await p.json()).code??u}catch{}throw new f(p.status,u)}if(p.status===204)return;return c?await p.blob():await p.json()}function de(e,t,i){return I(e,t,`/client/v1/channels/${encodeURIComponent(i)}/lists`)}function he(e,t,i,n){return I(e,t,`/client/v1/channels/${encodeURIComponent(i)}/subscriptions`,{method:"POST",json:n})}class W{server;socketClass;handlers;#s=null;#m=0;#n=0;#r=null;#y=!0;constructor(e,t,i){this.server=e;this.socketClass=t;this.handlers=i}get connected(){return this.#s?.readyState===1}start(){if(this.#y=!1,!this.#s&&!this.#r)this.#a()}stop(){if(this.#y=!0,this.#r)clearTimeout(this.#r);this.#r=null;let e=this.#s;this.#s=null,e?.close(1000)}reset(){this.#m=0}nudge(){if(this.#y||this.#s)return;if(this.#r)clearTimeout(this.#r);this.#r=null,this.#a()}#a(){let e=this.handlers.token();if(!e||this.#y)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#m>0)t.searchParams.set("last_event_id",String(this.#m));let i;try{i=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#u();return}this.#s=i,i.onmessage=(n)=>{let s;try{s=JSON.parse(String(n.data))}catch{return}if(s.type==="ready")this.#n=0,this.#m=Math.max(this.#m,s.last_event_id);else if("id"in s&&typeof s.id==="number")this.#m=Math.max(this.#m,s.id);this.handlers.event(s)},i.onclose=(n)=>{if(this.#s!==i)return;if(this.#s=null,this.#y)return;if(n.code===1008){this.#m=0,this.handlers.sessionEnded();return}this.#u()}}#u(){if(this.#y||this.#r)return;let e=this.#n++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#r=setTimeout(()=>{this.#r=null,this.#a()},t)}}function Ee(e,t,i){let n=new URL("/account/connect",e);return n.searchParams.set("channel",t),n.searchParams.set("origin",i),n.href}function Te(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function ue(e,t,{width:i=460,height:n=640}={}){let s=new URL(e).origin,o=location.origin,a=Math.max(0,(window.screenX??0)+((window.outerWidth??i)-i)/2),l=Math.max(0,(window.screenY??0)+((window.outerHeight??n)-n)/2),c=window.open(Ee(e,t,o),"yuva-reader",`popup=yes,width=${i},height=${n},left=${Math.round(a)},top=${Math.round(l)}`);if(!c)return Promise.reject(new f(0,"popup_blocked"));return new Promise((h,p)=>{let u=!1,y=()=>{u=!0,window.removeEventListener("message",g),clearInterval(_)},g=(b)=>{if(u||b.origin!==s||b.source&&b.source!==c)return;let d=b.data;if(!Te(d)||d.channel_key!==t||d.origin!==o)return;y();try{c.close()}catch{}h({token:d.token,expires_at:d.expires_at,reader:d.reader})},_=setInterval(()=>{let b=!1;try{b=c.closed}catch{}if(!b)return;clearInterval(_),setTimeout(()=>{if(u)return;y(),p(new f(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",g)})}function pe(e){return`yuva:${e}`}function fe(e,t){return`yuva:reader:${e} ${t}`}function M(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function ze(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i.sub==="string"?i.sub:null}catch{return null}}function Re(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,i)=>void e.set(t,i)}}function J(e){let t=new URLSearchParams;for(let[n,s]of Object.entries(e))if(s!==void 0)t.set(n,String(s));let i=t.toString();return i?`?${i}`:""}function De(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function Ie(e,t,i){let n=[];for(let[s,o]of e)n.push(`--${i}\r
10
10
  Content-Disposition: form-data; name="${s}"\r
11
11
  \r
12
12
  ${o}\r
@@ -16,7 +16,7 @@ Content-Type: ${s.type||"application/octet-stream"}\r
16
16
  \r
17
17
  `,s,`\r
18
18
  `)}return n.push(`--${i}--\r
19
- `),new Blob(n)}class ge{server;channel;#s;#m;#n;#r;#y;#a=null;#u=null;#w=null;#C=null;#t=null;#v;#p=new Map;constructor(e){this.server=e.server.replace(/\/+$/,""),this.channel=e.channel,this.#s=e.fetch??((t,i)=>fetch(t,i)),this.#m=e.WebSocket??globalThis.WebSocket,this.#n=e.storage??Re(),this.#r=e.identityToken??null,this.#y=e.idempotencyKeys??typeof globalThis.document>"u"}get session(){return this.#u}get token(){return this.#a}get connected(){return this.#t?.connected??!1}on(e,t){let i=this.#p.get(e);if(!i)this.#p.set(e,i=new Set);return i.add(t),()=>void i.delete(t)}#c(e,t){for(let i of this.#p.get(e)??[])i(t)}stored(){try{let e=this.#n.getItem(pe(this.channel));return e?JSON.parse(e):{}}catch{return{}}}#k(e){try{this.#n.setItem(pe(this.channel),JSON.stringify(e))}catch{}}channelSettings(){return this.#f(`/client/v1/channels/${encodeURIComponent(this.channel)}`)}ratePage(e){return this.#f(`/client/v1/channels/${encodeURIComponent(this.channel)}/page-ratings`,{method:"POST",json:e})}lists(){return de(this.#s,this.server,this.channel)}subscribe(e){return he(this.#s,this.server,this.channel,e)}subscriptions(){return this.#l("/client/v1/subscriptions")}subscribeList(e,t){return this.#l(`/client/v1/subscriptions/${encodeURIComponent(e)}`,{method:"PUT",json:t})}unsubscribeList(e){return this.#l(`/client/v1/subscriptions/${encodeURIComponent(e)}`,{method:"DELETE"})}setIdentityToken(e){this.#r=e,this.reset()}start(){if(this.#u)return Promise.resolve(this.#u);return this.#w??=this.#I(!1).then((e)=>(this.#c("session",{session:e,renewed:!1}),e)).finally(()=>{this.#w=null}),this.#w}async refresh(){let e=await this.#l("/client/v1/session");return this.#u={...this.#u,...e},this.#c("session",{session:this.#u,renewed:!1}),this.#u}reset(){this.#t?.stop(),this.#t?.reset(),this.#w=null,this.#C=null,this.#a=null,this.#u=null}async signOut(){let e=this.#a;this.reset();let t=this.stored();if(delete t.session,this.#k(t),e)await this.#f("/client/v1/session",{method:"DELETE",token:e}).catch(()=>{return})}async connect(){if(!this.#m)throw Error("Yuva: no WebSocket in this runtime; pass options.WebSocket");if(await this.start(),this.#t??=new W(this.server,this.#m,{token:()=>this.#a,event:(e)=>{if(e.type==="ready")this.#c("connection",{state:"open",attempt:0});this.#c("event",e)},sessionEnded:()=>void this.#D().catch(()=>this.#t?.nudge()),reconnecting:(e)=>{if(this.#c("connection",{state:"reconnecting",attempt:e}),e===2)this.#l("/client/v1/session").catch(()=>{return})}}),!this.#t.connected)this.#c("connection",{state:"connecting",attempt:0});this.#t.start()}disconnect(){this.#t?.stop(),this.#c("connection",{state:"closed",attempt:0})}reconnect(){this.#t?.nudge()}listConversations(e={}){return this.#l(`/client/v1/conversations${J({...e})}`)}getConversation(e){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}`)}startConversation(e){return this.#l("/client/v1/conversations",this.#z(e))}listMessages(e,t={}){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/messages${J({...t})}`)}sendMessage(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/messages`,this.#z(t))}markRead(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/read`,{method:"POST",json:t?{message_id:t}:{}})}rate(e,t,i){let n={rating:t,comment:i?.trim()||void 0};return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/rating`,{method:"POST",json:n})}setTyping(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/typing`,{method:"POST",json:{typing:t}})}setEmail(e){return this.#l("/client/v1/contact/email",{method:"PUT",json:{email:e}})}attachment(e){return this.#l(`/client/v1/attachments/${encodeURIComponent(e)}`,{blob:!0})}sendFeedback(e){let t=e.client_id??M();return this.#l("/client/v1/feedback",{method:"POST",headers:this.#x(t),json:{...e,client_id:t}})}get reader(){if(this.#v===void 0)try{let e=this.#n.getItem(fe(this.server,this.channel));this.#v=e?JSON.parse(e):null}catch{this.#v=null}if(this.#v&&Date.parse(this.#v.expires_at)<=Date.now()+30000)this.#i(null);return this.#v}#i(e){let t=this.#v?.token!==e?.token;this.#v=e;try{this.#n.setItem(fe(this.server,this.channel),e?JSON.stringify(e):"")}catch{}if(t)this.#c("reader",e)}readerSignIn(e){return ue(this.server,this.channel,e).then((t)=>(this.#i(t),t))}setReader(e){this.#i(e)}async readerSignOut(){let e=this.reader?.token;if(this.#i(null),e)await this.#f("/client/v1/reader-token",{method:"DELETE",token:e}).catch(()=>{return})}listDiscussions(e,t={}){return this.#b(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions${J({page:e,...t})}`,{},!1)}getDiscussion(e){return this.#b(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions/${encodeURIComponent(e)}`,{},!1)}startDiscussion(e){return this.#b("/client/v1/discussions",{method:"POST",json:e})}replyToDiscussion(e,t){return this.#b(`/client/v1/discussions/${encodeURIComponent(e)}/posts`,{method:"POST",json:t})}editDiscussionPost(e,t){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"PATCH",json:t})}deleteDiscussionPost(e){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"DELETE"})}voteDiscussionPost(e,t=!0){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}/vote`,{method:t?"PUT":"DELETE"})}followDiscussion(e,t=!0){return this.#b(`/client/v1/discussions/${encodeURIComponent(e)}/follow`,{method:t?"PUT":"DELETE"})}acceptDiscussionAnswer(e,t){let i=`/client/v1/discussions/${encodeURIComponent(e)}/answer`;return this.#b(i,t?{method:"PUT",json:{post_id:t}}:{method:"DELETE"})}async discussionWriter(){if(this.reader)return"reader";if(this.#u)return this.#u.contact.identified?"contact":null;return await this.#r?.()?"contact":null}async#b(e,t,i=!0){let n=this.reader;if(n)try{return await this.#f(e,{...t,token:n.token})}catch(o){if(!(o instanceof f)||o.status!==401||this.#v?.token!==n.token)throw o;if(this.#i(null),i)throw new f(403,"sign_in_required")}if(await this.discussionWriter()==="contact")return this.#l(e,t);if(i)throw new f(403,"sign_in_required");return this.#f(e,t)}#x(e){return this.#y&&/^[\x20-\x7e]{1,255}$/.test(e)?{"Idempotency-Key":e}:{}}#z({body:e,subject:t,files:i=[],client_id:n=M()}){let s=this.#x(n);if(i.length===0)return{method:"POST",headers:s,json:{body:e,subject:t,client_id:n}};let o=[];if(t)o.push(["subject",t]);if(e)o.push(["body",e]);o.push(["client_id",n]);let a=`yuva-${n.replace(/[^\w-]/g,"").slice(0,60)}-${n.length}`;return s["Content-Type"]=`multipart/form-data; boundary=${a}`,{method:"POST",headers:s,body:Ie(o,i,a)}}#f(e,t){return I(this.#s,this.server,e,t)}async#l(e,t={},i=!0){if(!this.#a)await this.start();try{return await this.#f(e,{...t,token:this.#a})}catch(n){if(!i||!(n instanceof f)||n.status!==401)throw n;return await this.#D(),this.#l(e,t,!1)}}#D(){return this.#C??=(async()=>{let e=await this.#I(!0);if(this.#t)this.#t.stop(),this.#t.reset(),this.#t.start();this.#c("session",{session:e,renewed:!0})})().finally(()=>{this.#C=null}),this.#C}async#I(e){let t=this.stored(),i=await this.#r?.()||null,n=i?ze(i):null,s=t.session;if(!e&&s&&s.sub===n&&Date.parse(s.expires_at)>Date.now()+60000)try{let c=await this.#f("/client/v1/session",{token:s.token});return this.#M(c,s.token,n)}catch(c){if(!(c instanceof f)||c.status!==401&&c.status!==403)throw c}let o=await this.#f("/client/v1/session",{method:"POST",json:{channel_key:this.channel,identity_token:i??void 0,visitor_id:t.visitor_id}}),{token:a,...l}=o;return this.#M(l,a,n)}#M(e,t,i){this.#a=t,this.#u=e;let n=this.stored();if(n.session={token:t,expires_at:e.expires_at,sub:i},e.visitor_id)n.visitor_id=e.visitor_id;else if(e.contact.identified)delete n.visitor_id;return this.#k(n),e}}function me(e){return new ge(e)}var ye=`
19
+ `),new Blob(n)}class ge{server;channel;#s;#m;#n;#r;#y;#a=null;#u=null;#w=null;#k=null;#t=null;#v;#p=new Map;constructor(e){this.server=e.server.replace(/\/+$/,""),this.channel=e.channel,this.#s=e.fetch??((t,i)=>fetch(t,i)),this.#m=e.WebSocket??globalThis.WebSocket,this.#n=e.storage??Re(),this.#r=e.identityToken??null,this.#y=e.idempotencyKeys??typeof globalThis.document>"u"}get session(){return this.#u}get token(){return this.#a}get connected(){return this.#t?.connected??!1}on(e,t){let i=this.#p.get(e);if(!i)this.#p.set(e,i=new Set);return i.add(t),()=>void i.delete(t)}#c(e,t){for(let i of this.#p.get(e)??[])i(t)}stored(){try{let e=this.#n.getItem(pe(this.channel));return e?JSON.parse(e):{}}catch{return{}}}#C(e){try{this.#n.setItem(pe(this.channel),JSON.stringify(e))}catch{}}channelSettings(){return this.#f(`/client/v1/channels/${encodeURIComponent(this.channel)}`)}ratePage(e){return this.#f(`/client/v1/channels/${encodeURIComponent(this.channel)}/page-ratings`,{method:"POST",json:e})}lists(){return de(this.#s,this.server,this.channel)}subscribe(e){return he(this.#s,this.server,this.channel,e)}subscriptions(){return this.#l("/client/v1/subscriptions")}subscribeList(e,t){return this.#l(`/client/v1/subscriptions/${encodeURIComponent(e)}`,{method:"PUT",json:t})}unsubscribeList(e){return this.#l(`/client/v1/subscriptions/${encodeURIComponent(e)}`,{method:"DELETE"})}setIdentityToken(e){this.#r=e,this.reset()}start(){if(this.#u)return Promise.resolve(this.#u);return this.#w??=this.#I(!1).then((e)=>(this.#c("session",{session:e,renewed:!1}),e)).finally(()=>{this.#w=null}),this.#w}async refresh(){let e=await this.#l("/client/v1/session");return this.#u={...this.#u,...e},this.#c("session",{session:this.#u,renewed:!1}),this.#u}reset(){this.#t?.stop(),this.#t?.reset(),this.#w=null,this.#k=null,this.#a=null,this.#u=null}async signOut(){let e=this.#a;this.reset();let t=this.stored();if(delete t.session,this.#C(t),e)await this.#f("/client/v1/session",{method:"DELETE",token:e}).catch(()=>{return})}async connect(){if(!this.#m)throw Error("Yuva: no WebSocket in this runtime; pass options.WebSocket");if(await this.start(),this.#t??=new W(this.server,this.#m,{token:()=>this.#a,event:(e)=>{if(e.type==="ready")this.#c("connection",{state:"open",attempt:0});this.#c("event",e)},sessionEnded:()=>void this.#D().catch(()=>this.#t?.nudge()),reconnecting:(e)=>{if(this.#c("connection",{state:"reconnecting",attempt:e}),e===2)this.#l("/client/v1/session").catch(()=>{return})}}),!this.#t.connected)this.#c("connection",{state:"connecting",attempt:0});this.#t.start()}disconnect(){this.#t?.stop(),this.#c("connection",{state:"closed",attempt:0})}reconnect(){this.#t?.nudge()}listConversations(e={}){return this.#l(`/client/v1/conversations${J({...e})}`)}getConversation(e){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}`)}startConversation(e){return this.#l("/client/v1/conversations",this.#z(e))}listMessages(e,t={}){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/messages${J({...t})}`)}sendMessage(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/messages`,this.#z(t))}markRead(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/read`,{method:"POST",json:t?{message_id:t}:{}})}rate(e,t,i){let n={rating:t,comment:i?.trim()||void 0};return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/rating`,{method:"POST",json:n})}setTyping(e,t){return this.#l(`/client/v1/conversations/${encodeURIComponent(e)}/typing`,{method:"POST",json:{typing:t}})}setEmail(e){return this.#l("/client/v1/contact/email",{method:"PUT",json:{email:e}})}attachment(e){return this.#l(`/client/v1/attachments/${encodeURIComponent(e)}`,{blob:!0})}sendFeedback(e){let t=e.client_id??M();return this.#l("/client/v1/feedback",{method:"POST",headers:this.#x(t),json:{...e,client_id:t}})}get reader(){if(this.#v===void 0)try{let e=this.#n.getItem(fe(this.server,this.channel));this.#v=e?JSON.parse(e):null}catch{this.#v=null}if(this.#v&&Date.parse(this.#v.expires_at)<=Date.now()+30000)this.#i(null);return this.#v}#i(e){let t=this.#v?.token!==e?.token;this.#v=e;try{this.#n.setItem(fe(this.server,this.channel),e?JSON.stringify(e):"")}catch{}if(t)this.#c("reader",e)}readerSignIn(e){return ue(this.server,this.channel,e).then((t)=>(this.#i(t),t))}setReader(e){this.#i(e)}async readerSignOut(){let e=this.reader?.token;if(this.#i(null),e)await this.#f("/client/v1/reader-token",{method:"DELETE",token:e}).catch(()=>{return})}listDiscussions(e,t={}){return this.#b(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions${J({page:e,...t})}`,{},!1)}getDiscussion(e){return this.#b(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions/${encodeURIComponent(e)}`,{},!1)}startDiscussion(e){return this.#b("/client/v1/discussions",{method:"POST",json:e})}replyToDiscussion(e,t){return this.#b(`/client/v1/discussions/${encodeURIComponent(e)}/posts`,{method:"POST",json:t})}editDiscussionPost(e,t){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"PATCH",json:t})}deleteDiscussionPost(e){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"DELETE"})}voteDiscussionPost(e,t=!0){return this.#b(`/client/v1/discussion-posts/${encodeURIComponent(e)}/vote`,{method:t?"PUT":"DELETE"})}followDiscussion(e,t=!0){return this.#b(`/client/v1/discussions/${encodeURIComponent(e)}/follow`,{method:t?"PUT":"DELETE"})}acceptDiscussionAnswer(e,t){let i=`/client/v1/discussions/${encodeURIComponent(e)}/answer`;return this.#b(i,t?{method:"PUT",json:{post_id:t}}:{method:"DELETE"})}async discussionWriter(){if(this.reader)return"reader";if(this.#u)return this.#u.contact.identified?"contact":null;return await this.#r?.()?"contact":null}async#b(e,t,i=!0){let n=this.reader;if(n)try{return await this.#f(e,{...t,token:n.token})}catch(o){if(!(o instanceof f)||o.status!==401||this.#v?.token!==n.token)throw o;if(this.#i(null),i)throw new f(403,"sign_in_required")}if(await this.discussionWriter()==="contact")return this.#l(e,t);if(i)throw new f(403,"sign_in_required");return this.#f(e,t)}#x(e){return this.#y&&/^[\x20-\x7e]{1,255}$/.test(e)?{"Idempotency-Key":e}:{}}#z({body:e,subject:t,files:i=[],client_id:n=M()}){let s=this.#x(n);if(i.length===0)return{method:"POST",headers:s,json:{body:e,subject:t,client_id:n}};let o=[];if(t)o.push(["subject",t]);if(e)o.push(["body",e]);o.push(["client_id",n]);let a=`yuva-${n.replace(/[^\w-]/g,"").slice(0,60)}-${n.length}`;return s["Content-Type"]=`multipart/form-data; boundary=${a}`,{method:"POST",headers:s,body:Ie(o,i,a)}}#f(e,t){return I(this.#s,this.server,e,t)}async#l(e,t={},i=!0){if(!this.#a)await this.start();try{return await this.#f(e,{...t,token:this.#a})}catch(n){if(!i||!(n instanceof f)||n.status!==401)throw n;return await this.#D(),this.#l(e,t,!1)}}#D(){return this.#k??=(async()=>{let e=await this.#I(!0);if(this.#t)this.#t.stop(),this.#t.reset(),this.#t.start();this.#c("session",{session:e,renewed:!0})})().finally(()=>{this.#k=null}),this.#k}async#I(e){let t=this.stored(),i=await this.#r?.()||null,n=i?ze(i):null,s=t.session;if(!e&&s&&s.sub===n&&Date.parse(s.expires_at)>Date.now()+60000)try{let c=await this.#f("/client/v1/session",{token:s.token});return this.#M(c,s.token,n)}catch(c){if(!(c instanceof f)||c.status!==401&&c.status!==403)throw c}let o=await this.#f("/client/v1/session",{method:"POST",json:{channel_key:this.channel,identity_token:i??void 0,visitor_id:t.visitor_id}}),{token:a,...l}=o;return this.#M(l,a,n)}#M(e,t,i){this.#a=t,this.#u=e;let n=this.stored();if(n.session={token:t,expires_at:e.expires_at,sub:i},e.visitor_id)n.visitor_id=e.visitor_id;else if(e.contact.identified)delete n.visitor_id;return this.#C(n),e}}function me(e){return new ge(e)}var ye=`
20
20
  [hidden] { display: none !important; }
21
21
  .header {
22
22
  display: flex;
@@ -210,4 +210,4 @@ Content-Type: ${s.type||"application/octet-stream"}\r
210
210
  .sr { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
211
211
  `;var Me=/(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(\*[^*\s][^*\n]*\*|_[^_\s][^_\n]*_)|((?:https?:\/\/|www\.)[^\s<>"]*[^\s<>".,:;'!?)\]])/g;function Le(e,t){let i=document.createElement("a");return i.href=e,i.textContent=t,i.target="_blank",i.rel="noopener noreferrer nofollow ugc",i}function G(e,t){let i=document.createElement(e);return i.append(...t),i}function q(e){let t=[],i=0;for(let n of e.matchAll(Me)){let s=n.index??0;if(s>i)t.push(document.createTextNode(e.slice(i,s)));let[o,a,l,c,h]=n;if(a)t.push(G("code",[document.createTextNode(a.slice(1,-1))]));else if(l)t.push(G("strong",q(l.slice(2,-2))));else if(c)t.push(G("em",q(c.slice(1,-1))));else if(h){let p=h.startsWith("www.")?`https://${h}`:h;try{let u=new URL(p);t.push(u.protocol==="http:"||u.protocol==="https:"?Le(u.href,h):document.createTextNode(h))}catch{t.push(document.createTextNode(h))}}i=s+o.length}if(i<e.length)t.push(document.createTextNode(e.slice(i)));return t}function L(e){let t=document.createDocumentFragment(),i=e.trim().replace(/\r\n?/g,`
212
212
  `).split(/^```[^\n]*\n([\s\S]*?)^```[ \t]*$/m);return i.forEach((n,s)=>{if(s%2===1){let a=document.createElement("pre");a.textContent=n.replace(/\n$/,""),t.append(a);return}(i.length>1?n.replace(/^\n|\n$/g,""):n).split(`
213
- `).forEach((a,l)=>{if(l>0)t.append(document.createElement("br"));t.append(...q(a))})}),t}var Ae={en:Y,tr:oe,de:re},Oe=10,ve=300000,P={close:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',back:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>',attach:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 11.5l-8.3 8.3a5 5 0 01-7-7L13 4.5a3.3 3.3 0 014.7 4.7l-8.3 8.3a1.7 1.7 0 01-2.4-2.4L14.5 7.6"/></svg>',send:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M3.4 20.4l17.5-7.5a1 1 0 000-1.8L3.4 3.6a1 1 0 00-1.4 1.2L4.5 12l-2.5 7.2a1 1 0 001.4 1.2zM4.5 12h7"/></svg>',file:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M14 3H6v18h12V7z M14 3v4h4"/></svg>'};function r(e,t,i){let n=document.createElement(e);if(t)n.className=t;if(i!==void 0)n.textContent=i;return n}function z(e,t,i,n="icon"){let s=r("button",n);return s.type="button",s.innerHTML=e,s.setAttribute("aria-label",t),s.title=t,s.addEventListener("click",i),s}var x=(e)=>Date.parse(e),be=(e,t)=>x(e.created_at)-x(t.created_at),Ue=(e,t)=>x(t.last_message_at??t.created_at)-x(e.last_message_at??e.created_at),A=(e)=>e.author.type==="contact"?"contact":`${e.author.type}:${e.author.name??""}`,$e=(e)=>/^image\/(png|jpeg|gif|webp)$/.test(e.content_type);class xe{#s;#m;#n;#r=null;#y=null;#a="loading";#u="";#w=null;#C=null;#t=new Map;#v;#p=new Map;#c=[];#k=new Map;#i=null;#b=!1;#x=[];#z=0;#f=null;#l=new Map;#D=new Map;#I=new Map;#M=!1;#S="";#H=!1;#_=new Map;#ke=r("div","card rate");#g=r("textarea");#Q="";#re=null;#V=r("header","header");#X=r("div","banner");#U=r("div","body");#d=r("div","scroll");#P=r("div","card");#E=r("input");#oe=r("div","composer");#Z=r("div","chips");#h=r("textarea");#T=r("input");#$;#K;#ee=r("div","sr");#Y;#L=!0;constructor(e){this.#s=e;let{server:t,channel:i}=e.config();this.#n=me({server:t,channel:i??"",identityToken:()=>e.identityToken()}),this.#n.on("event",(s)=>this.#_e(s)),this.#n.on("connection",({state:s,attempt:o})=>{if(s!=="reconnecting")return;this.#b=o>0,this.#ne()}),this.#n.on("session",({session:s,renewed:o})=>{if(this.#W(s.inbox),this.#y=s.contact,o)this.#pe()}),this.#le(),this.#ee.setAttribute("aria-live","polite"),this.#d.addEventListener("scroll",()=>{if(this.#L=this.#d.scrollHeight-this.#d.scrollTop-this.#d.clientHeight<48,this.#d.scrollTop<60&&this.#i?.kind==="thread"&&this.#i.id)this.#G(this.#i.id,!0)}),this.#h.rows=1,this.#h.addEventListener("keydown",(s)=>{if(s.key==="Enter"&&!s.shiftKey&&!s.isComposing)s.preventDefault(),this.#ie()}),this.#h.addEventListener("input",()=>{this.#ge(),this.#B(),this.#Te()}),this.#h.addEventListener("paste",(s)=>{let o=Array.from(s.clipboardData?.files??[]);if(o.length===0)return;s.preventDefault(),this.#fe(o)}),this.#T.type="file",this.#T.multiple=!0,this.#T.hidden=!0,this.#T.addEventListener("change",()=>{this.#fe(Array.from(this.#T.files??[])),this.#T.value=""}),this.#K=z(P.attach,"",()=>this.#T.click()),this.#$=z(P.send,"",()=>void this.#ie(),"icon send");let n=r("form");n.addEventListener("submit",(s)=>{s.preventDefault(),this.#ie()}),n.append(this.#K,this.#h,this.#$,this.#T),this.#oe.append(this.#Z,n),this.#E.type="email",this.#E.required=!0,this.#E.autocomplete="email",this.#g.rows=2,this.#g.maxLength=2000,this.#g.dir="auto",document.addEventListener("visibilitychange",this.#F),window.addEventListener("online",this.#F),this.#we(),this.#N()}update(){this.#le(),this.#we()}opened(){if(this.#a==="error"){this.#w=null,this.#N();return}if(this.#a==="ready")this.#n.token?this.#Se():this.#ce().then(()=>this.#o()).catch(()=>{return});if(this.#o(),this.#R(),this.#j(),this.#s.config().layout==="launcher")this.#h.focus({preventScroll:!0})}closed(){this.#O()}identityChanged(){this.#ae(),this.#N()}async signOut(){let e=this.#n.signOut();if(this.#ae(),await e,this.#s.isOpen())this.#N();else this.#o()}destroy(){this.#n.reset(),this.#O(),document.removeEventListener("visibilitychange",this.#F),window.removeEventListener("online",this.#F);for(let e of this.#l.values())URL.revokeObjectURL(e)}#ae(){this.#n.reset(),this.#w=null,this.#C=null,this.#r=null,this.#y=null,this.#a="loading",this.#t.clear(),this.#p.clear(),this.#c=[],this.#_.clear(),this.#Q="",this.#i=null,this.#H=!1,this.#s.setUnread(0)}#F=()=>{if(document.visibilityState!=="visible")return;this.#n.reconnect(),this.#j(),this.#he()};#le(){let{locale:e}=this.#s.config();this.#m=K({locale:e,messages:{[e]:Ae[e]??Y}})}#e(e){return this.#m._(e)}#N(){return this.#w??=(async()=>{this.#a="loading",this.#o();let{channel:e}=this.#s.config();if(!e)throw new f(0,"not_configured");if(await this.#s.identityToken()||F(e).session)await this.#Ce();else if(await this.#ce(),!this.#r?.chat.allow_anonymous)throw new f(403,"anonymous_not_allowed");if(this.#a="ready",!this.#i){let t=this.#xe();if(this.#i=t.length>1?{kind:"list"}:{kind:"thread",id:t[0]?.id??null},this.#i.kind==="thread"&&this.#i.id)await this.#G(this.#i.id)}this.#o(),this.#R(),this.#j()})().catch((e)=>{if(this.#w=null,this.#ue(e))return;this.#a="error",this.#u=e instanceof f?e.code:"error",this.#o()}),this.#w}async#ce(){let e=await this.#de();if(!this.#n.token)this.#W(e)}#de(){if(!this.#s.config().channel)throw new f(0,"not_configured");return this.#n.channelSettings()}#W(e){let{channel:t}=this.#s.config();this.#r=e;let i=ae(e);if(this.#s.setLauncher(i),t)ce(t,{...F(t),launcher:i})}async#he(){if(this.#a!=="ready")return;try{this.#W(await this.#de()),this.#o()}catch(e){this.#ue(e,!0)}}#ue(e,t=!this.#n.token){let i=e instanceof f&&(e.code==="origin_not_allowed"||e.status===404&&t);if(i)this.#s.refused();return i}#Ce(){return this.#C??=(async()=>{await this.#n.start(),await this.#J(),await this.#n.connect()})().finally(()=>{this.#C=null}),this.#C}async#Se(){try{await this.#n.refresh(),this.#o()}catch{}}async#J(e=!1){let t=await this.#n.listConversations({limit:50,cursor:e?this.#v:void 0});if(!e)this.#t.clear();for(let i of t.items)this.#t.set(i.id,i);this.#v=t.next_cursor,this.#A()}async#pe(){await this.#J();let e=this.#i?.kind==="thread"?this.#i.id:null;for(let t of this.#p.keys())if(t!==e)this.#p.delete(t);if(e)this.#p.delete(e),await this.#G(e);this.#o()}async#G(e,t=!1){let i=this.#p.get(e);if(!i)i={messages:[],complete:!1,loading:!1},this.#p.set(e,i);if(i.loading||t&&(i.complete||!i.cursor))return;i.loading=!0;let n=this.#d.scrollHeight-this.#d.scrollTop;try{let s=await this.#n.listMessages(e,{order:"desc",limit:30,cursor:t?i.cursor:void 0}),o=new Set(i.messages.map((a)=>a.id));i.messages=[...i.messages,...s.items.filter((a)=>!o.has(a.id))].sort(be),i.cursor=s.next_cursor,i.complete=!s.next_cursor}finally{i.loading=!1}if(t)this.#o(),this.#d.scrollTop=this.#d.scrollHeight-n}#_e(e){switch(e.type){case"ready":if(this.#b=!1,this.#ne(),this.#H)this.#he();this.#H=!0;return;case"inbox.updated":{let t=this.#r?.ask_for_rating;if(this.#W(e.data),t!==void 0&&t!==e.data.ask_for_rating)this.#J().then(()=>this.#o()).catch(()=>{return});break}case"resync_required":this.#pe();return;case"presence":if(this.#r)this.#r={...this.#r,presence:e.data};break;case"conversation.created":if(!this.#t.has(e.data.id))this.#t.set(e.data.id,e.data);if(this.#i?.kind==="thread"&&this.#i.id===null&&this.#t.size>1)this.#i=this.#c.some((t)=>t.conversation===null)?this.#i:{kind:"list"};this.#A();break;case"conversation.updated":{let t=this.#t.get(e.data.id),{status:i,can_rate:n,rating:s}=e.data;if(t)this.#t.set(t.id,{...t,status:i,can_rate:n,rating:s});if(!n)this.#_.delete(e.data.id);break}case"message.created":case"message.updated":this.#te(e.data,e.type==="message.created");break;case"read":{let t=this.#t.get(e.data.conversation_id),i=t?.last_read_by_member_at;if(t&&(!i||x(e.data.read_at)>x(i)))this.#t.set(t.id,{...t,last_read_by_member_at:e.data.read_at});break}case"typing":{let t=e.data.conversation_id,i=this.#k.get(t);if(i)clearTimeout(i.timer);if(e.data.typing){let n=e.data.author.name??"";this.#k.set(t,{name:n,timer:setTimeout(()=>this.#k.delete(t)&&this.#o(),8000)})}else this.#k.delete(t);break}}this.#o()}#te(e,t){let i=e.conversation_id,n=this.#p.get(i);if(n){let o=n.messages.findIndex((a)=>a.id===e.id);if(o>=0)n.messages[o]=e;else n.messages=[...n.messages,e].sort(be)}if(e.client_id)this.#c=this.#c.filter((o)=>o.client_id!==e.client_id);let s=this.#t.get(i);if(!s){this.#n.getConversation(i).then((o)=>{this.#t.set(o.id,o),this.#A(),this.#o()}).catch(()=>{return});return}if(t){let o=e.body.replace(/\s+/g," ").trim();if(this.#t.set(i,{...s,last_message:{id:e.id,author_type:e.author.type,text:o.length>140?`${o.slice(0,139)}…`:o,created_at:e.created_at},last_message_at:e.created_at,unread:s.unread||e.author.type!=="contact"}),e.author.type!=="contact"){let a=this.#k.get(i);if(a)clearTimeout(a.timer);this.#k.delete(i),this.#Pe(e)}}this.#A(),this.#j()}#Pe(e){this.#ee.textContent=`${e.author.name||this.#r?.name||""}: ${e.body.slice(0,200)}`}#A(){let e=0;for(let t of this.#t.values())if(t.unread)e++;this.#s.setUnread(e)}#Ee(){if(!this.#s.isOpen()||document.visibilityState!=="visible")return null;return this.#i?.kind==="thread"?this.#i.id:null}#j(){let e=this.#Ee(),t=e?this.#t.get(e):void 0;if(!e||!t?.unread)return;this.#t.set(e,{...t,unread:!1}),this.#A(),this.#n.markRead(e).catch(()=>{let i=this.#t.get(e);if(i)this.#t.set(e,{...i,unread:!0});this.#A()})}#fe(e){this.#x=[...this.#x,...e].slice(0,Oe),this.#q(),this.#B(),this.#h.focus()}#ge(){if(this.#h.style.blockSize="",this.#h.value==="")return;this.#h.style.blockSize="auto",this.#h.style.blockSize=`${Math.max(38,Math.min(this.#h.scrollHeight,140))}px`}#B(){this.#$.disabled=this.#h.value.trim()===""&&this.#x.length===0}#Te(){let e=this.#i?.kind==="thread"?this.#i.id:null;if(!e||this.#h.value.trim()===""){this.#O();return}if(Date.now()-this.#z>3000)this.#z=Date.now(),this.#n.setTyping(e,!0).catch(()=>{return});if(this.#f)clearTimeout(this.#f);this.#f=setTimeout(()=>this.#O(),4000)}#O(){if(this.#f)clearTimeout(this.#f);if(this.#f=null,this.#z===0)return;this.#z=0;let e=this.#i?.kind==="thread"?this.#i.id:null;if(e)this.#n.setTyping(e,!1).catch(()=>{return})}async#ie(){if(this.#a!=="ready"||this.#i?.kind!=="thread")return;let e=this.#h.value.trim(),t=this.#x;if(!e&&t.length===0)return;if(this.#i.id===null&&this.#c.some((n)=>n.conversation===null))return;this.#O(),this.#h.value="",this.#x=[],this.#ge(),this.#q(),this.#B();let i={client_id:M(),conversation:this.#i.id,body:e,files:t,state:"sending"};this.#c.push(i),this.#o(),this.#R(),await this.#me(i)}async#me(e){e.state="sending",this.#o();let t={body:e.body,files:e.files,client_id:e.client_id};try{if(e.conversation===null){let i=await this.#n.startConversation(t),n=i.conversation.id;if(!this.#t.has(n))this.#t.set(n,i.conversation);if(!this.#p.has(n))this.#p.set(n,{messages:[],complete:!0,loading:!1});if(this.#i?.kind==="thread"&&this.#i.id===null)this.#i={kind:"thread",id:n};this.#te(i.message,!1)}else{let i=await this.#n.sendMessage(e.conversation,t);this.#te(i,!0)}this.#c=this.#c.filter((i)=>i!==e)}catch(i){let n=i instanceof f?i.status:0;e.state=n===413||n===415?"refused":"failed",e.status=n}this.#o(),this.#R()}async rate(e,t,i){try{let n=await this.#n.rate(e,t,i);return this.#t.set(n.id,n),this.#_.delete(e),this.#o(),n}catch(n){if(n instanceof f&&n.status===409){let s=await this.#n.getConversation(e).catch(()=>null);if(s)this.#t.set(s.id,s);this.#_.delete(e),this.#o()}throw n}}#ze(e,t){if(this.#_.get(e)?.state==="sending")return;if(this.#_.set(e,{choice:t,state:"choosing"}),this.#o(),this.#g.focus({preventScroll:!0}),this.#L)this.#R()}async#ye(e,t){let i=this.#_.get(e);if(!i||i.state==="sending")return;i.state="sending",this.#o();try{await this.rate(e,i.choice,t?this.#g.value:void 0),this.#g.value=""}catch(n){if(n instanceof f&&n.status===409)return;i.state="failed",this.#o()}}async#Re(){let e=this.#E.value.trim();if(!e||!this.#E.checkValidity()){this.#S=this.#e({id:"E_qvzP"}),this.#se();return}try{this.#y=await this.#n.setEmail(e),this.#M=!0,this.#S=""}catch{this.#S=this.#e({id:"ZxJcgC"})}this.#se()}#ve(e){let t=this.#l.get(e.id);if(t)return Promise.resolve(t);let i=this.#D.get(e.id);if(!i)i=this.#n.attachment(e.id).then((n)=>{let s=URL.createObjectURL(n);return this.#l.set(e.id,s),s}),i.catch(()=>this.#D.delete(e.id)),this.#D.set(e.id,i);return i}async#be(e){let t=await this.#ve(e),i=r("a");i.href=t,i.download=e.filename,i.rel="noopener",i.click()}#xe(){return[...this.#t.values()].sort(Ue)}#De(){let e=this.#r;if(!e)return!1;return!e.open_now||e.mode==="async"||!e.presence?.available}#R(){this.#L=!0,this.#d.scrollTop=this.#d.scrollHeight,requestAnimationFrame(()=>{if(this.#L)this.#d.scrollTop=this.#d.scrollHeight})}#we(){this.#h.placeholder=this.#e({id:"RzWUUK"}),this.#h.setAttribute("aria-label",this.#e({id:"xDAtGP"})),this.#K.setAttribute("aria-label",this.#e({id:"N7m8E-"})),this.#K.title=this.#e({id:"N7m8E-"}),this.#$.setAttribute("aria-label",this.#e({id:"JlFcis"})),this.#$.title=this.#e({id:"JlFcis"}),this.#E.placeholder=this.#e({id:"njBr8W"}),this.#E.setAttribute("aria-label",this.#e({id:"XJURKP"})),this.#B(),this.#q(),this.#o()}#o(){let e=this.#s.panel;if(e.childElementCount===0){let t=r("style");t.textContent=ye,e.append(t,this.#V,this.#X,this.#U,this.#ee),this.#V.id="yuva-title",e.setAttribute("aria-labelledby","yuva-title")}if(this.#Me(),this.#ne(),this.#a!=="ready"){this.#Y=void 0;let t=r("div","center");if(this.#a==="loading")t.append(r("p","hint",this.#e({id:"Pwqkdw"})));else{t.append(r("p","empty",this.#Ie()));let i=r("button","primary",this.#e({id:"KDw4GX"}));i.type="button",i.addEventListener("click",()=>{this.#w=null,this.#N()}),t.append(i)}this.#U.replaceChildren(t);return}if(this.#i?.kind==="list")this.#Ae();else this.#$e()}#Ie(){switch(this.#u){case"anonymous_not_allowed":return this.#e({id:"zLzEI3"});case"invalid_identity_token":return this.#e({id:"0XGLbP"});case"rate_limited":return this.#e({id:"tzsBOP"});case"network":return this.#e({id:"GQVIIl"});default:return this.#e({id:"Amai22"})}}#Me(){let{layout:e}=this.#s.config(),t=this.#r,i=[],n=this.#i;if(this.#a==="ready"&&n?.kind==="thread"&&(this.#t.size>1||n.id===null&&this.#t.size>0))i.push(z(P.back,this.#e({id:"S63MQu"}),()=>{this.#O(),this.#i={kind:"list"},this.#o()}));let s=r("div","heading");if(s.append(r("h2","title",t?.name||this.#e({id:"t7TeQU"}))),t){let o=r("div","status");if(t.mode==="live"&&t.open_now&&t.presence?.available){let l=r("div","avatars");for(let c of t.presence?.members.slice(0,3)??[]){let h=r("span","avatar",c.initials||"•");h.title=c.name,l.append(h)}o.append(l,r("span","dot"),r("span","",this.#e({id:"oXOSPE"})))}else if(!t.open_now||t.mode==="live")o.append(r("span","dot away"),r("span","",this.#e({id:"1EICzz"})));else o.append(r("span","",this.#Le(t.expected_reply_minutes)));s.append(o)}if(i.push(s),e==="launcher")i.push(z(P.close,this.#e({id:"yz7wBu"}),()=>this.#s.close()));this.#V.replaceChildren(...i)}#Le(e){if(!e)return this.#e({id:"nhTADq"});let{locale:t}=this.#s.config(),[i,n]=e<60?[e,"minute"]:e<1440?[Math.round(e/60),"hour"]:[Math.round(e/1440),"day"],s=new Intl.NumberFormat(t,{style:"unit",unit:n,unitDisplay:"long"}).format(i);return this.#e({id:"VggdQJ",values:{duration:s}})}#ne(){this.#X.hidden=!this.#b,this.#X.textContent=this.#e({id:"09Tv5j"})}#Ae(){this.#Y=void 0;let{locale:e}=this.#s.config(),t=r("ul","list"),i=new Date().toDateString();for(let s of this.#xe()){let o=r("button",s.unread?"item unread":"item");o.type="button";let a=r("div","item-main"),l=r("div","item-top");l.append(r("span","item-subject",s.subject||this.#r?.name||this.#e({id:"YyNOE7"})));let c=new Date(s.last_message_at??s.created_at);l.append(r("span","item-time",new Intl.DateTimeFormat(e,c.toDateString()===i?{timeStyle:"short"}:{month:"short",day:"numeric"}).format(c)));let h=s.last_message?`${s.last_message.author_type==="contact"?this.#e({id:"ydzYKJ"})+" ":""}${s.last_message.text||this.#e({id:"UY1vmE"})}`:"",p=r("div","item-preview",h.replace(/\*\*|`/g,""));if(p.dir="auto",a.append(l,p),o.append(a),s.unread)o.append(r("span","unread-dot"));o.addEventListener("click",()=>void this.#Oe(s.id));let u=r("li");u.append(o),t.append(u)}if(this.#v){let s=r("button","link",this.#e({id:"ASr-r0"}));s.type="button",s.style.margin="8px auto",s.style.display="block",s.addEventListener("click",()=>void this.#J(!0).then(()=>this.#o())),t.append(s)}let n=r("button","primary",this.#e({id:"-HY5kX"}));n.type="button",n.addEventListener("click",()=>{this.#i={kind:"thread",id:null},this.#o(),this.#h.focus()}),this.#U.replaceChildren(t,n)}async#Oe(e){if(this.#i={kind:"thread",id:e},this.#o(),!this.#p.get(e)?.complete&&!this.#p.get(e)?.messages.length)await this.#G(e).catch(()=>{return});this.#o(),this.#R(),this.#j()}#Ue(e){let t=r("span","avatar",e.initials||""),i=e.avatar_url,n=i?this.#I.get(i):!1;if(!i||n===!1)return t;let s=r("img");if(s.alt="",s.referrerPolicy="no-referrer",n)return s.src=i,t.replaceChildren(s),t;return s.addEventListener("load",()=>{if(this.#I.set(i,!0),t.isConnected)t.replaceChildren(s)}),s.addEventListener("error",()=>this.#I.set(i,!1)),s.src=i,t}#$e(){let e=this.#i;if(e?.kind!=="thread")return;let t=e.id,i=this.#Y===t,n=this.#L,s=t?this.#p.get(t):void 0,o=s?.messages??[],a=this.#c.filter((d)=>d.conversation===t),l=[],c=this.#r?.chat.greeting;if(!s||s.complete){if(c){let d=r("div","bubble greeting");d.append(L(c)),l.push(d)}else if(o.length===0&&a.length===0){let d=r("div","center");d.append(r("p","empty",this.#e({id:"meAa31"})),r("p","hint",this.#e({id:"SdV5Cn"}))),l.push(d)}}else if(s.loading)l.push(r("p","hint",this.#e({id:"Pwqkdw"})));o.forEach((d,v)=>{let k=o[v-1],w=o[v+1]??(a.length>0?null:void 0),m=d.author.type==="contact",C=!k||A(k)!==A(d)||x(d.created_at)-x(k.created_at)>ve,H=w===void 0||(w===null?!m:A(w)!==A(d)||x(w.created_at)-x(d.created_at)>ve);if(!m&&C&&d.author.name)l.push(r("div","author",d.author.name));let O=r("div",`row ${m?"mine":"theirs"}${C&&v>0?" group-gap":""}`);if(!m){let T=this.#Ue(d.author);if(!H)T.style.visibility="hidden";O.append(T)}let E=r("div","bubble");if(E.dir="auto",E.title=new Date(d.created_at).toLocaleString(this.#s.config().locale),d.body.trim())E.append(L(d.body));if(d.attachments.length>0)E.append(this.#je(d.attachments));if(O.append(E),l.push(O),H){let T=this.#Be(d.created_at);if(m&&v===o.length-1&&a.length===0){let Q=t?this.#t.get(t)?.last_read_by_member_at:void 0,we=Q&&x(Q)>=x(d.created_at);T+=` · ${we?this.#e({id:"6lGaum"}):this.#e({id:"h69WC6"})}`}let U=r("div","meta",T);if(!m)U.style.alignSelf="flex-start";if(!m)U.style.marginInlineStart="36px";l.push(U)}});let h=t?this.#t.get(t):void 0,p=h?this.#Ne(h):null;if(p)l.push(p);a.forEach((d,v)=>{let k=r("div",`row mine${v===0&&o.length>0&&o[o.length-1]?.author.type!=="contact"?" group-gap":""}`),w=r("div","bubble");if(w.dir="auto",d.body)w.append(L(d.body));if(d.files.length>0){let m=r("div","files");for(let C of d.files)m.append(r("span","file",C.name||"image"));w.append(m)}if(k.append(w),l.push(k),d.state==="failed"){let m=r("div","meta failed",`${this.#e({id:"upFvcp"})} `),C=r("button","link",this.#e({id:"6gRgw8"}));C.type="button",C.addEventListener("click",()=>void this.#me(d)),m.append(C),l.push(m)}else if(d.state==="refused"){let m=d.status===413?this.#e({id:"eOu9Px"}):this.#e({id:"JkW3Ph"});l.push(r("div","meta failed",`${this.#e({id:"upFvcp"})} ${m}`))}else if(v===a.length-1)l.push(r("div","meta",this.#e({id:"Sad2tK"})))});let u=t?this.#k.get(t):void 0;if(u){let d=r("div","typing");d.append(r("i"),r("i"),r("i"));let v=u.name;d.append(r("span","",v?this.#e({id:"tHaDPf",values:{name:v}}):this.#e({id:"PxYAul"}))),l.push(d)}let g=this.#d.getRootNode().activeElement===this.#g,{selectionStart:_,selectionEnd:b}=this.#g;if(this.#d.replaceChildren(...l),g&&this.#g.isConnected)this.#g.focus({preventScroll:!0}),this.#g.setSelectionRange(_,b);if(this.#se(),this.#U.firstChild!==this.#d)this.#U.replaceChildren(this.#d,this.#P,this.#oe);if(this.#Y=t,!i||n)this.#R()}#Ne(e){let t=e.status==="closed"?e.rating:void 0,i=e.can_rate&&this.#r?.ask_for_rating?this.#_.get(e.id):void 0;if(!t&&!(e.can_rate&&this.#r?.ask_for_rating))return null;let n=this.#ke,s=[e.id,t,i?.choice,i?.state,this.#s.config().locale].join(":");if(s===this.#Q)return n;if(this.#Q=s,this.#re!==e.id)this.#re=e.id,this.#g.value="";let o=this.#e({id:"uA8iBc"});n.setAttribute("role","group"),n.setAttribute("aria-label",o);let a=r("div","choices");for(let u of["good","bad"]){if(t&&t!==u)continue;let y=r("button","choice",u==="good"?"\uD83D\uDC4D":"\uD83D\uDC4E");y.type="button";let g=u==="good"?this.#e({id:"OEEQKT"}):this.#e({id:"-f5Tkb"});y.setAttribute("aria-label",g),y.title=g,y.setAttribute("aria-pressed",String((t??i?.choice)===u)),y.disabled=!!t||i?.state==="sending",y.addEventListener("click",()=>this.#ze(e.id,u)),a.append(y)}if(t)return n.replaceChildren(a,r("p","",this.#e({id:"SOk0EB"}))),n;if(n.replaceChildren(r("p","",o),a),!i)return n;this.#g.placeholder=this.#e({id:"axQ1h6"}),this.#g.setAttribute("aria-label",this.#e({id:"NBdIgR"})),this.#g.disabled=i.state==="sending";let l=r("form");l.addEventListener("submit",(u)=>{u.preventDefault(),this.#ye(e.id,!0)});let c=r("button","link",this.#e({id:"6Uau97"}));c.type="button",c.disabled=i.state==="sending",c.addEventListener("click",()=>void this.#ye(e.id,!1));let h=r("button","",i.state==="sending"?this.#e({id:"Sad2tK"}):this.#e({id:"JlFcis"}));h.type="submit",h.disabled=i.state==="sending";let p=r("div","actions");if(p.append(c,h),l.append(this.#g,p),n.append(l),i.state==="failed")n.append(r("p","error",this.#e({id:"4TqZiz"})));return n}#je(e){let t=r("div","files");for(let i of e)if($e(i)){let n=r("img");n.alt=i.filename;let s=this.#l.get(i.id);if(s)n.src=s;else this.#ve(i).then((o)=>{n.src=o}).catch(()=>{return});n.addEventListener("load",()=>{if(this.#L)this.#d.scrollTop=this.#d.scrollHeight}),n.addEventListener("click",()=>void this.#be(i)),t.append(n)}else{let n=r("button","file");n.type="button",n.innerHTML=P.file,n.append(r("span","",i.filename)),n.addEventListener("click",()=>void this.#be(i)),t.append(n)}return t}#Be(e){return new Intl.DateTimeFormat(this.#s.config().locale,{timeStyle:"short"}).format(new Date(e))}#se(){let e=this.#y,t=this.#r?.chat,n=(this.#i?.kind==="thread"?this.#i.id:null)!==null||this.#c.length>0,s=e?.email||e?.typed_email,o=!!t?.ask_email_offline&&this.#De()&&n&&(!s||this.#M);if(this.#P.hidden=!o,!o)return;if(s&&this.#M){this.#P.replaceChildren(r("p","",this.#e({id:"iGNUZJ",values:{known:s}})));return}if(this.#P.querySelector("form")){let c=this.#P.querySelector(".error");if(c)c.textContent=this.#S;else if(this.#S)this.#P.append(r("p","error",this.#S));return}let a=r("form");a.noValidate=!0,a.addEventListener("submit",(c)=>{c.preventDefault(),this.#Re()});let l=r("button","",this.#e({id:"tfDRzk"}));if(l.type="submit",a.append(this.#E,l),this.#P.replaceChildren(r("p","",this.#e({id:"M62PBt"})),a),this.#S)this.#P.append(r("p","error",this.#S))}#q(){this.#Z.hidden=this.#x.length===0,this.#Z.replaceChildren(...this.#x.map((e,t)=>{let i=r("span","chip");return i.append(r("span","",e.name||"image"),z(P.close,this.#e({id:"w61W3L",values:{0:e.name}}),()=>{this.#x=this.#x.filter((n,s)=>s!==t),this.#q(),this.#B()})),i}))}}function Ne(e){return new xe(e)}export{Ne as mount};
213
+ `).forEach((a,l)=>{if(l>0)t.append(document.createElement("br"));t.append(...q(a))})}),t}var Ae={en:Y,tr:oe,de:re},Oe=10,ve=300000,P={close:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',back:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>',attach:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 11.5l-8.3 8.3a5 5 0 01-7-7L13 4.5a3.3 3.3 0 014.7 4.7l-8.3 8.3a1.7 1.7 0 01-2.4-2.4L14.5 7.6"/></svg>',send:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M3.4 20.4l17.5-7.5a1 1 0 000-1.8L3.4 3.6a1 1 0 00-1.4 1.2L4.5 12l-2.5 7.2a1 1 0 001.4 1.2zM4.5 12h7"/></svg>',file:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M14 3H6v18h12V7z M14 3v4h4"/></svg>'};function r(e,t,i){let n=document.createElement(e);if(t)n.className=t;if(i!==void 0)n.textContent=i;return n}function z(e,t,i,n="icon"){let s=r("button",n);return s.type="button",s.innerHTML=e,s.setAttribute("aria-label",t),s.title=t,s.addEventListener("click",i),s}var x=(e)=>Date.parse(e),be=(e,t)=>x(e.created_at)-x(t.created_at),Ue=(e,t)=>x(t.last_message_at??t.created_at)-x(e.last_message_at??e.created_at),A=(e)=>e.author.type==="contact"?"contact":`${e.author.type}:${e.author.name??""}`,$e=(e)=>/^image\/(png|jpeg|gif|webp)$/.test(e.content_type);class xe{#s;#m;#n;#r=null;#y=null;#a="loading";#u="";#w=null;#k=null;#t=new Map;#v;#p=new Map;#c=[];#C=new Map;#i=null;#b=!1;#x=[];#z=0;#f=null;#l=new Map;#D=new Map;#I=new Map;#M=!1;#S="";#H=!1;#_=new Map;#ke=r("div","card rate");#g=r("textarea");#Q="";#re=null;#V=r("header","header");#X=r("div","banner");#U=r("div","body");#d=r("div","scroll");#P=r("div","card");#E=r("input");#oe=r("div","composer");#Z=r("div","chips");#h=r("textarea");#T=r("input");#$;#K;#ee=r("div","sr");#Y;#L=!0;constructor(e){this.#s=e;let{server:t,channel:i}=e.config();this.#n=me({server:t,channel:i??"",identityToken:()=>e.identityToken()}),this.#n.on("event",(s)=>this.#_e(s)),this.#n.on("connection",({state:s,attempt:o})=>{if(s!=="reconnecting")return;this.#b=o>0,this.#ne()}),this.#n.on("session",({session:s,renewed:o})=>{if(this.#W(s.inbox),this.#y=s.contact,o)this.#pe();else if(!this.#k)this.#n.connect().catch(()=>{return})}),this.#le(),this.#ee.setAttribute("aria-live","polite"),this.#d.addEventListener("scroll",()=>{if(this.#L=this.#d.scrollHeight-this.#d.scrollTop-this.#d.clientHeight<48,this.#d.scrollTop<60&&this.#i?.kind==="thread"&&this.#i.id)this.#G(this.#i.id,!0)}),this.#h.rows=1,this.#h.addEventListener("keydown",(s)=>{if(s.key==="Enter"&&!s.shiftKey&&!s.isComposing)s.preventDefault(),this.#ie()}),this.#h.addEventListener("input",()=>{this.#ge(),this.#B(),this.#Te()}),this.#h.addEventListener("paste",(s)=>{let o=Array.from(s.clipboardData?.files??[]);if(o.length===0)return;s.preventDefault(),this.#fe(o)}),this.#T.type="file",this.#T.multiple=!0,this.#T.hidden=!0,this.#T.addEventListener("change",()=>{this.#fe(Array.from(this.#T.files??[])),this.#T.value=""}),this.#K=z(P.attach,"",()=>this.#T.click()),this.#$=z(P.send,"",()=>void this.#ie(),"icon send");let n=r("form");n.addEventListener("submit",(s)=>{s.preventDefault(),this.#ie()}),n.append(this.#K,this.#h,this.#$,this.#T),this.#oe.append(this.#Z,n),this.#E.type="email",this.#E.required=!0,this.#E.autocomplete="email",this.#g.rows=2,this.#g.maxLength=2000,this.#g.dir="auto",document.addEventListener("visibilitychange",this.#F),window.addEventListener("online",this.#F),this.#we(),this.#N()}update(){this.#le(),this.#we()}opened(){if(this.#a==="error"){this.#w=null,this.#N();return}if(this.#a==="ready")this.#n.token?this.#Se():this.#ce().then(()=>this.#o()).catch(()=>{return});if(this.#o(),this.#R(),this.#j(),this.#s.config().layout==="launcher")this.#h.focus({preventScroll:!0})}closed(){this.#O()}identityChanged(){this.#ae(),this.#N()}async signOut(){let e=this.#n.signOut();if(this.#ae(),await e,this.#s.isOpen())this.#N();else this.#o()}destroy(){this.#n.reset(),this.#O(),document.removeEventListener("visibilitychange",this.#F),window.removeEventListener("online",this.#F);for(let e of this.#l.values())URL.revokeObjectURL(e)}#ae(){this.#n.reset(),this.#w=null,this.#k=null,this.#r=null,this.#y=null,this.#a="loading",this.#t.clear(),this.#p.clear(),this.#c=[],this.#_.clear(),this.#Q="",this.#i=null,this.#H=!1,this.#s.setUnread(0)}#F=()=>{if(document.visibilityState!=="visible")return;this.#n.reconnect(),this.#j(),this.#he()};#le(){let{locale:e}=this.#s.config();this.#m=K({locale:e,messages:{[e]:Ae[e]??Y}})}#e(e){return this.#m._(e)}#N(){return this.#w??=(async()=>{this.#a="loading",this.#o();let{channel:e}=this.#s.config();if(!e)throw new f(0,"not_configured");if(await this.#s.identityToken()||F(e).session)await this.#Ce();else if(await this.#ce(),!this.#r?.chat.allow_anonymous)throw new f(403,"anonymous_not_allowed");if(this.#a="ready",!this.#i){let t=this.#xe();if(this.#i=t.length>1?{kind:"list"}:{kind:"thread",id:t[0]?.id??null},this.#i.kind==="thread"&&this.#i.id)await this.#G(this.#i.id)}this.#o(),this.#R(),this.#j()})().catch((e)=>{if(this.#w=null,this.#ue(e))return;this.#a="error",this.#u=e instanceof f?e.code:"error",this.#o()}),this.#w}async#ce(){let e=await this.#de();if(!this.#n.token)this.#W(e)}#de(){if(!this.#s.config().channel)throw new f(0,"not_configured");return this.#n.channelSettings()}#W(e){let{channel:t}=this.#s.config();this.#r=e;let i=ae(e);if(this.#s.setLauncher(i),t)ce(t,{...F(t),launcher:i})}async#he(){if(this.#a!=="ready")return;try{this.#W(await this.#de()),this.#o()}catch(e){this.#ue(e,!0)}}#ue(e,t=!this.#n.token){let i=e instanceof f&&(e.code==="origin_not_allowed"||e.status===404&&t);if(i)this.#s.refused();return i}#Ce(){return this.#k??=(async()=>{await this.#n.start(),await this.#J(),await this.#n.connect()})().finally(()=>{this.#k=null}),this.#k}async#Se(){try{await this.#n.refresh(),this.#o()}catch{}}async#J(e=!1){let t=await this.#n.listConversations({limit:50,cursor:e?this.#v:void 0});if(!e)this.#t.clear();for(let i of t.items)this.#t.set(i.id,i);this.#v=t.next_cursor,this.#A()}async#pe(){await this.#J();let e=this.#i?.kind==="thread"?this.#i.id:null;for(let t of this.#p.keys())if(t!==e)this.#p.delete(t);if(e)this.#p.delete(e),await this.#G(e);this.#o()}async#G(e,t=!1){let i=this.#p.get(e);if(!i)i={messages:[],complete:!1,loading:!1},this.#p.set(e,i);if(i.loading||t&&(i.complete||!i.cursor))return;i.loading=!0;let n=this.#d.scrollHeight-this.#d.scrollTop;try{let s=await this.#n.listMessages(e,{order:"desc",limit:30,cursor:t?i.cursor:void 0}),o=new Set(i.messages.map((a)=>a.id));i.messages=[...i.messages,...s.items.filter((a)=>!o.has(a.id))].sort(be),i.cursor=s.next_cursor,i.complete=!s.next_cursor}finally{i.loading=!1}if(t)this.#o(),this.#d.scrollTop=this.#d.scrollHeight-n}#_e(e){switch(e.type){case"ready":if(this.#b=!1,this.#ne(),this.#H)this.#he();this.#H=!0;return;case"inbox.updated":{let t=this.#r?.ask_for_rating;if(this.#W(e.data),t!==void 0&&t!==e.data.ask_for_rating)this.#J().then(()=>this.#o()).catch(()=>{return});break}case"resync_required":this.#pe();return;case"presence":if(this.#r)this.#r={...this.#r,presence:e.data};break;case"conversation.created":if(!this.#t.has(e.data.id))this.#t.set(e.data.id,e.data);if(this.#i?.kind==="thread"&&this.#i.id===null&&this.#t.size>1)this.#i=this.#c.some((t)=>t.conversation===null)?this.#i:{kind:"list"};this.#A();break;case"conversation.updated":{let t=this.#t.get(e.data.id),{status:i,can_rate:n,rating:s}=e.data;if(t)this.#t.set(t.id,{...t,status:i,can_rate:n,rating:s});if(!n)this.#_.delete(e.data.id);break}case"message.created":case"message.updated":this.#te(e.data,e.type==="message.created");break;case"read":{let t=this.#t.get(e.data.conversation_id),i=t?.last_read_by_member_at;if(t&&(!i||x(e.data.read_at)>x(i)))this.#t.set(t.id,{...t,last_read_by_member_at:e.data.read_at});break}case"typing":{let t=e.data.conversation_id,i=this.#C.get(t);if(i)clearTimeout(i.timer);if(e.data.typing){let n=e.data.author.name??"";this.#C.set(t,{name:n,timer:setTimeout(()=>this.#C.delete(t)&&this.#o(),8000)})}else this.#C.delete(t);break}}this.#o()}#te(e,t){let i=e.conversation_id,n=this.#p.get(i);if(n){let o=n.messages.findIndex((a)=>a.id===e.id);if(o>=0)n.messages[o]=e;else n.messages=[...n.messages,e].sort(be)}if(e.client_id)this.#c=this.#c.filter((o)=>o.client_id!==e.client_id);let s=this.#t.get(i);if(!s){this.#n.getConversation(i).then((o)=>{this.#t.set(o.id,o),this.#A(),this.#o()}).catch(()=>{return});return}if(t){let o=e.body.replace(/\s+/g," ").trim();if(this.#t.set(i,{...s,last_message:{id:e.id,author_type:e.author.type,text:o.length>140?`${o.slice(0,139)}…`:o,created_at:e.created_at},last_message_at:e.created_at,unread:s.unread||e.author.type!=="contact"}),e.author.type!=="contact"){let a=this.#C.get(i);if(a)clearTimeout(a.timer);this.#C.delete(i),this.#Pe(e)}}this.#A(),this.#j()}#Pe(e){this.#ee.textContent=`${e.author.name||this.#r?.name||""}: ${e.body.slice(0,200)}`}#A(){let e=0;for(let t of this.#t.values())if(t.unread)e++;this.#s.setUnread(e)}#Ee(){if(!this.#s.isOpen()||document.visibilityState!=="visible")return null;return this.#i?.kind==="thread"?this.#i.id:null}#j(){let e=this.#Ee(),t=e?this.#t.get(e):void 0;if(!e||!t?.unread)return;this.#t.set(e,{...t,unread:!1}),this.#A(),this.#n.markRead(e).catch(()=>{let i=this.#t.get(e);if(i)this.#t.set(e,{...i,unread:!0});this.#A()})}#fe(e){this.#x=[...this.#x,...e].slice(0,Oe),this.#q(),this.#B(),this.#h.focus()}#ge(){if(this.#h.style.blockSize="",this.#h.value==="")return;this.#h.style.blockSize="auto",this.#h.style.blockSize=`${Math.max(38,Math.min(this.#h.scrollHeight,140))}px`}#B(){this.#$.disabled=this.#h.value.trim()===""&&this.#x.length===0}#Te(){let e=this.#i?.kind==="thread"?this.#i.id:null;if(!e||this.#h.value.trim()===""){this.#O();return}if(Date.now()-this.#z>3000)this.#z=Date.now(),this.#n.setTyping(e,!0).catch(()=>{return});if(this.#f)clearTimeout(this.#f);this.#f=setTimeout(()=>this.#O(),4000)}#O(){if(this.#f)clearTimeout(this.#f);if(this.#f=null,this.#z===0)return;this.#z=0;let e=this.#i?.kind==="thread"?this.#i.id:null;if(e)this.#n.setTyping(e,!1).catch(()=>{return})}async#ie(){if(this.#a!=="ready"||this.#i?.kind!=="thread")return;let e=this.#h.value.trim(),t=this.#x;if(!e&&t.length===0)return;if(this.#i.id===null&&this.#c.some((n)=>n.conversation===null))return;this.#O(),this.#h.value="",this.#x=[],this.#ge(),this.#q(),this.#B();let i={client_id:M(),conversation:this.#i.id,body:e,files:t,state:"sending"};this.#c.push(i),this.#o(),this.#R(),await this.#me(i)}async#me(e){e.state="sending",this.#o();let t={body:e.body,files:e.files,client_id:e.client_id};try{if(e.conversation===null){let i=await this.#n.startConversation(t),n=i.conversation.id;if(!this.#t.has(n))this.#t.set(n,i.conversation);if(!this.#p.has(n))this.#p.set(n,{messages:[],complete:!0,loading:!1});if(this.#i?.kind==="thread"&&this.#i.id===null)this.#i={kind:"thread",id:n};this.#te(i.message,!1)}else{let i=await this.#n.sendMessage(e.conversation,t);this.#te(i,!0)}this.#c=this.#c.filter((i)=>i!==e)}catch(i){let n=i instanceof f?i.status:0;e.state=n===413||n===415?"refused":"failed",e.status=n}this.#o(),this.#R()}async rate(e,t,i){try{let n=await this.#n.rate(e,t,i);return this.#t.set(n.id,n),this.#_.delete(e),this.#o(),n}catch(n){if(n instanceof f&&n.status===409){let s=await this.#n.getConversation(e).catch(()=>null);if(s)this.#t.set(s.id,s);this.#_.delete(e),this.#o()}throw n}}#ze(e,t){if(this.#_.get(e)?.state==="sending")return;if(this.#_.set(e,{choice:t,state:"choosing"}),this.#o(),this.#g.focus({preventScroll:!0}),this.#L)this.#R()}async#ye(e,t){let i=this.#_.get(e);if(!i||i.state==="sending")return;i.state="sending",this.#o();try{await this.rate(e,i.choice,t?this.#g.value:void 0),this.#g.value=""}catch(n){if(n instanceof f&&n.status===409)return;i.state="failed",this.#o()}}async#Re(){let e=this.#E.value.trim();if(!e||!this.#E.checkValidity()){this.#S=this.#e({id:"E_qvzP"}),this.#se();return}try{this.#y=await this.#n.setEmail(e),this.#M=!0,this.#S=""}catch{this.#S=this.#e({id:"ZxJcgC"})}this.#se()}#ve(e){let t=this.#l.get(e.id);if(t)return Promise.resolve(t);let i=this.#D.get(e.id);if(!i)i=this.#n.attachment(e.id).then((n)=>{let s=URL.createObjectURL(n);return this.#l.set(e.id,s),s}),i.catch(()=>this.#D.delete(e.id)),this.#D.set(e.id,i);return i}async#be(e){let t=await this.#ve(e),i=r("a");i.href=t,i.download=e.filename,i.rel="noopener",i.click()}#xe(){return[...this.#t.values()].sort(Ue)}#De(){let e=this.#r;if(!e)return!1;return!e.open_now||e.mode==="async"||!e.presence?.available}#R(){this.#L=!0,this.#d.scrollTop=this.#d.scrollHeight,requestAnimationFrame(()=>{if(this.#L)this.#d.scrollTop=this.#d.scrollHeight})}#we(){this.#h.placeholder=this.#e({id:"RzWUUK"}),this.#h.setAttribute("aria-label",this.#e({id:"xDAtGP"})),this.#K.setAttribute("aria-label",this.#e({id:"N7m8E-"})),this.#K.title=this.#e({id:"N7m8E-"}),this.#$.setAttribute("aria-label",this.#e({id:"JlFcis"})),this.#$.title=this.#e({id:"JlFcis"}),this.#E.placeholder=this.#e({id:"njBr8W"}),this.#E.setAttribute("aria-label",this.#e({id:"XJURKP"})),this.#B(),this.#q(),this.#o()}#o(){let e=this.#s.panel;if(e.childElementCount===0){let t=r("style");t.textContent=ye,e.append(t,this.#V,this.#X,this.#U,this.#ee),this.#V.id="yuva-title",e.setAttribute("aria-labelledby","yuva-title")}if(this.#Me(),this.#ne(),this.#a!=="ready"){this.#Y=void 0;let t=r("div","center");if(this.#a==="loading")t.append(r("p","hint",this.#e({id:"Pwqkdw"})));else{t.append(r("p","empty",this.#Ie()));let i=r("button","primary",this.#e({id:"KDw4GX"}));i.type="button",i.addEventListener("click",()=>{this.#w=null,this.#N()}),t.append(i)}this.#U.replaceChildren(t);return}if(this.#i?.kind==="list")this.#Ae();else this.#$e()}#Ie(){switch(this.#u){case"anonymous_not_allowed":return this.#e({id:"zLzEI3"});case"invalid_identity_token":return this.#e({id:"0XGLbP"});case"rate_limited":return this.#e({id:"tzsBOP"});case"network":return this.#e({id:"GQVIIl"});default:return this.#e({id:"Amai22"})}}#Me(){let{layout:e}=this.#s.config(),t=this.#r,i=[],n=this.#i;if(this.#a==="ready"&&n?.kind==="thread"&&(this.#t.size>1||n.id===null&&this.#t.size>0))i.push(z(P.back,this.#e({id:"S63MQu"}),()=>{this.#O(),this.#i={kind:"list"},this.#o()}));let s=r("div","heading");if(s.append(r("h2","title",t?.name||this.#e({id:"t7TeQU"}))),t){let o=r("div","status");if(t.mode==="live"&&t.open_now&&t.presence?.available){let l=r("div","avatars");for(let c of t.presence?.members.slice(0,3)??[]){let h=r("span","avatar",c.initials||"•");h.title=c.name,l.append(h)}o.append(l,r("span","dot"),r("span","",this.#e({id:"oXOSPE"})))}else if(!t.open_now||t.mode==="live")o.append(r("span","dot away"),r("span","",this.#e({id:"1EICzz"})));else o.append(r("span","",this.#Le(t.expected_reply_minutes)));s.append(o)}if(i.push(s),e==="launcher")i.push(z(P.close,this.#e({id:"yz7wBu"}),()=>this.#s.close()));this.#V.replaceChildren(...i)}#Le(e){if(!e)return this.#e({id:"nhTADq"});let{locale:t}=this.#s.config(),[i,n]=e<60?[e,"minute"]:e<1440?[Math.round(e/60),"hour"]:[Math.round(e/1440),"day"],s=new Intl.NumberFormat(t,{style:"unit",unit:n,unitDisplay:"long"}).format(i);return this.#e({id:"VggdQJ",values:{duration:s}})}#ne(){this.#X.hidden=!this.#b,this.#X.textContent=this.#e({id:"09Tv5j"})}#Ae(){this.#Y=void 0;let{locale:e}=this.#s.config(),t=r("ul","list"),i=new Date().toDateString();for(let s of this.#xe()){let o=r("button",s.unread?"item unread":"item");o.type="button";let a=r("div","item-main"),l=r("div","item-top");l.append(r("span","item-subject",s.subject||this.#r?.name||this.#e({id:"YyNOE7"})));let c=new Date(s.last_message_at??s.created_at);l.append(r("span","item-time",new Intl.DateTimeFormat(e,c.toDateString()===i?{timeStyle:"short"}:{month:"short",day:"numeric"}).format(c)));let h=s.last_message?`${s.last_message.author_type==="contact"?this.#e({id:"ydzYKJ"})+" ":""}${s.last_message.text||this.#e({id:"UY1vmE"})}`:"",p=r("div","item-preview",h.replace(/\*\*|`/g,""));if(p.dir="auto",a.append(l,p),o.append(a),s.unread)o.append(r("span","unread-dot"));o.addEventListener("click",()=>void this.#Oe(s.id));let u=r("li");u.append(o),t.append(u)}if(this.#v){let s=r("button","link",this.#e({id:"ASr-r0"}));s.type="button",s.style.margin="8px auto",s.style.display="block",s.addEventListener("click",()=>void this.#J(!0).then(()=>this.#o())),t.append(s)}let n=r("button","primary",this.#e({id:"-HY5kX"}));n.type="button",n.addEventListener("click",()=>{this.#i={kind:"thread",id:null},this.#o(),this.#h.focus()}),this.#U.replaceChildren(t,n)}async#Oe(e){if(this.#i={kind:"thread",id:e},this.#o(),!this.#p.get(e)?.complete&&!this.#p.get(e)?.messages.length)await this.#G(e).catch(()=>{return});this.#o(),this.#R(),this.#j()}#Ue(e){let t=r("span","avatar",e.initials||""),i=e.avatar_url,n=i?this.#I.get(i):!1;if(!i||n===!1)return t;let s=r("img");if(s.alt="",s.referrerPolicy="no-referrer",n)return s.src=i,t.replaceChildren(s),t;return s.addEventListener("load",()=>{if(this.#I.set(i,!0),t.isConnected)t.replaceChildren(s)}),s.addEventListener("error",()=>this.#I.set(i,!1)),s.src=i,t}#$e(){let e=this.#i;if(e?.kind!=="thread")return;let t=e.id,i=this.#Y===t,n=this.#L,s=t?this.#p.get(t):void 0,o=s?.messages??[],a=this.#c.filter((d)=>d.conversation===t),l=[],c=this.#r?.chat.greeting;if(!s||s.complete){if(c){let d=r("div","bubble greeting");d.append(L(c)),l.push(d)}else if(o.length===0&&a.length===0){let d=r("div","center");d.append(r("p","empty",this.#e({id:"meAa31"})),r("p","hint",this.#e({id:"SdV5Cn"}))),l.push(d)}}else if(s.loading)l.push(r("p","hint",this.#e({id:"Pwqkdw"})));o.forEach((d,v)=>{let k=o[v-1],w=o[v+1]??(a.length>0?null:void 0),m=d.author.type==="contact",C=!k||A(k)!==A(d)||x(d.created_at)-x(k.created_at)>ve,H=w===void 0||(w===null?!m:A(w)!==A(d)||x(w.created_at)-x(d.created_at)>ve);if(!m&&C&&d.author.name)l.push(r("div","author",d.author.name));let O=r("div",`row ${m?"mine":"theirs"}${C&&v>0?" group-gap":""}`);if(!m){let T=this.#Ue(d.author);if(!H)T.style.visibility="hidden";O.append(T)}let E=r("div","bubble");if(E.dir="auto",E.title=new Date(d.created_at).toLocaleString(this.#s.config().locale),d.body.trim())E.append(L(d.body));if(d.attachments.length>0)E.append(this.#je(d.attachments));if(O.append(E),l.push(O),H){let T=this.#Be(d.created_at);if(m&&v===o.length-1&&a.length===0){let Q=t?this.#t.get(t)?.last_read_by_member_at:void 0,we=Q&&x(Q)>=x(d.created_at);T+=` · ${we?this.#e({id:"6lGaum"}):this.#e({id:"h69WC6"})}`}let U=r("div","meta",T);if(!m)U.style.alignSelf="flex-start";if(!m)U.style.marginInlineStart="36px";l.push(U)}});let h=t?this.#t.get(t):void 0,p=h?this.#Ne(h):null;if(p)l.push(p);a.forEach((d,v)=>{let k=r("div",`row mine${v===0&&o.length>0&&o[o.length-1]?.author.type!=="contact"?" group-gap":""}`),w=r("div","bubble");if(w.dir="auto",d.body)w.append(L(d.body));if(d.files.length>0){let m=r("div","files");for(let C of d.files)m.append(r("span","file",C.name||"image"));w.append(m)}if(k.append(w),l.push(k),d.state==="failed"){let m=r("div","meta failed",`${this.#e({id:"upFvcp"})} `),C=r("button","link",this.#e({id:"6gRgw8"}));C.type="button",C.addEventListener("click",()=>void this.#me(d)),m.append(C),l.push(m)}else if(d.state==="refused"){let m=d.status===413?this.#e({id:"eOu9Px"}):this.#e({id:"JkW3Ph"});l.push(r("div","meta failed",`${this.#e({id:"upFvcp"})} ${m}`))}else if(v===a.length-1)l.push(r("div","meta",this.#e({id:"Sad2tK"})))});let u=t?this.#C.get(t):void 0;if(u){let d=r("div","typing");d.append(r("i"),r("i"),r("i"));let v=u.name;d.append(r("span","",v?this.#e({id:"tHaDPf",values:{name:v}}):this.#e({id:"PxYAul"}))),l.push(d)}let g=this.#d.getRootNode().activeElement===this.#g,{selectionStart:_,selectionEnd:b}=this.#g;if(this.#d.replaceChildren(...l),g&&this.#g.isConnected)this.#g.focus({preventScroll:!0}),this.#g.setSelectionRange(_,b);if(this.#se(),this.#U.firstChild!==this.#d)this.#U.replaceChildren(this.#d,this.#P,this.#oe);if(this.#Y=t,!i||n)this.#R()}#Ne(e){let t=e.status==="closed"?e.rating:void 0,i=e.can_rate&&this.#r?.ask_for_rating?this.#_.get(e.id):void 0;if(!t&&!(e.can_rate&&this.#r?.ask_for_rating))return null;let n=this.#ke,s=[e.id,t,i?.choice,i?.state,this.#s.config().locale].join(":");if(s===this.#Q)return n;if(this.#Q=s,this.#re!==e.id)this.#re=e.id,this.#g.value="";let o=this.#e({id:"uA8iBc"});n.setAttribute("role","group"),n.setAttribute("aria-label",o);let a=r("div","choices");for(let u of["good","bad"]){if(t&&t!==u)continue;let y=r("button","choice",u==="good"?"\uD83D\uDC4D":"\uD83D\uDC4E");y.type="button";let g=u==="good"?this.#e({id:"OEEQKT"}):this.#e({id:"-f5Tkb"});y.setAttribute("aria-label",g),y.title=g,y.setAttribute("aria-pressed",String((t??i?.choice)===u)),y.disabled=!!t||i?.state==="sending",y.addEventListener("click",()=>this.#ze(e.id,u)),a.append(y)}if(t)return n.replaceChildren(a,r("p","",this.#e({id:"SOk0EB"}))),n;if(n.replaceChildren(r("p","",o),a),!i)return n;this.#g.placeholder=this.#e({id:"axQ1h6"}),this.#g.setAttribute("aria-label",this.#e({id:"NBdIgR"})),this.#g.disabled=i.state==="sending";let l=r("form");l.addEventListener("submit",(u)=>{u.preventDefault(),this.#ye(e.id,!0)});let c=r("button","link",this.#e({id:"6Uau97"}));c.type="button",c.disabled=i.state==="sending",c.addEventListener("click",()=>void this.#ye(e.id,!1));let h=r("button","",i.state==="sending"?this.#e({id:"Sad2tK"}):this.#e({id:"JlFcis"}));h.type="submit",h.disabled=i.state==="sending";let p=r("div","actions");if(p.append(c,h),l.append(this.#g,p),n.append(l),i.state==="failed")n.append(r("p","error",this.#e({id:"4TqZiz"})));return n}#je(e){let t=r("div","files");for(let i of e)if($e(i)){let n=r("img");n.alt=i.filename;let s=this.#l.get(i.id);if(s)n.src=s;else this.#ve(i).then((o)=>{n.src=o}).catch(()=>{return});n.addEventListener("load",()=>{if(this.#L)this.#d.scrollTop=this.#d.scrollHeight}),n.addEventListener("click",()=>void this.#be(i)),t.append(n)}else{let n=r("button","file");n.type="button",n.innerHTML=P.file,n.append(r("span","",i.filename)),n.addEventListener("click",()=>void this.#be(i)),t.append(n)}return t}#Be(e){return new Intl.DateTimeFormat(this.#s.config().locale,{timeStyle:"short"}).format(new Date(e))}#se(){let e=this.#y,t=this.#r?.chat,n=(this.#i?.kind==="thread"?this.#i.id:null)!==null||this.#c.length>0,s=e?.email||e?.typed_email,o=!!t?.ask_email_offline&&this.#De()&&n&&(!s||this.#M);if(this.#P.hidden=!o,!o)return;if(s&&this.#M){this.#P.replaceChildren(r("p","",this.#e({id:"iGNUZJ",values:{known:s}})));return}if(this.#P.querySelector("form")){let c=this.#P.querySelector(".error");if(c)c.textContent=this.#S;else if(this.#S)this.#P.append(r("p","error",this.#S));return}let a=r("form");a.noValidate=!0,a.addEventListener("submit",(c)=>{c.preventDefault(),this.#Re()});let l=r("button","",this.#e({id:"tfDRzk"}));if(l.type="submit",a.append(this.#E,l),this.#P.replaceChildren(r("p","",this.#e({id:"M62PBt"})),a),this.#S)this.#P.append(r("p","error",this.#S))}#q(){this.#Z.hidden=this.#x.length===0,this.#Z.replaceChildren(...this.#x.map((e,t)=>{let i=r("span","chip");return i.append(r("span","",e.name||"image"),z(P.close,this.#e({id:"w61W3L",values:{0:e.name}}),()=>{this.#x=this.#x.filter((n,s)=>s!==t),this.#q(),this.#B()})),i}))}}function Ne(e){return new xe(e)}export{Ne as mount};
package/dist/yuva-docs.js CHANGED
@@ -1,4 +1,4 @@
1
- (()=>{class d extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function P(e,t,i,{method:s="GET",json:n,body:o,headers:r={},token:l,blob:c}={}){if(r={...r},l)r.Authorization=`Bearer ${l}`;let h=o;if(n!==void 0)r["Content-Type"]="application/json",h=JSON.stringify(n);let p;try{p=await e(t+i,{method:s,headers:r,body:h,credentials:"omit"})}catch{throw new d(0,"network")}if(!p.ok){let u="error";try{u=(await p.json()).code??u}catch{}throw new d(p.status,u)}if(p.status===204)return;return c?await p.blob():await p.json()}function z(e,t,i){return P(e,t,`/client/v1/channels/${encodeURIComponent(i)}/lists`)}function O(e,t,i,s){return P(e,t,`/client/v1/channels/${encodeURIComponent(i)}/subscriptions`,{method:"POST",json:s})}class R{server;socketClass;handlers;#e=null;#i=0;#n=0;#t=null;#r=!0;constructor(e,t,i){this.server=e;this.socketClass=t;this.handlers=i}get connected(){return this.#e?.readyState===1}start(){if(this.#r=!1,!this.#e)this.#o()}stop(){if(this.#r=!0,this.#t)clearTimeout(this.#t);this.#t=null;let e=this.#e;this.#e=null,e?.close(1000)}reset(){this.#i=0}nudge(){if(this.#r||this.#e)return;if(this.#t)clearTimeout(this.#t);this.#t=null,this.#o()}#o(){let e=this.handlers.token();if(!e||this.#r)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#i>0)t.searchParams.set("last_event_id",String(this.#i));let i;try{i=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#s();return}this.#e=i,i.onmessage=(s)=>{let n;try{n=JSON.parse(String(s.data))}catch{return}if(n.type==="ready")this.#n=0,this.#i=Math.max(this.#i,n.last_event_id);else if("id"in n&&typeof n.id==="number")this.#i=Math.max(this.#i,n.id);this.handlers.event(n)},i.onclose=(s)=>{if(this.#e!==i)return;if(this.#e=null,this.#r)return;if(s.code===1008){this.#i=0,this.handlers.sessionEnded();return}this.#s()}}#s(){if(this.#r||this.#t)return;let e=this.#n++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#t=setTimeout(()=>{this.#t=null,this.#o()},t)}}function ce(e,t,i){let s=new URL("/account/connect",e);return s.searchParams.set("channel",t),s.searchParams.set("origin",i),s.href}function de(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function W(e,t,{width:i=460,height:s=640}={}){let n=new URL(e).origin,o=location.origin,r=Math.max(0,(window.screenX??0)+((window.outerWidth??i)-i)/2),l=Math.max(0,(window.screenY??0)+((window.outerHeight??s)-s)/2),c=window.open(ce(e,t,o),"yuva-reader",`popup=yes,width=${i},height=${s},left=${Math.round(r)},top=${Math.round(l)}`);if(!c)return Promise.reject(new d(0,"popup_blocked"));return new Promise((h,p)=>{let u=!1,y=()=>{u=!0,window.removeEventListener("message",f),clearInterval(m)},f=(g)=>{if(u||g.origin!==n||g.source&&g.source!==c)return;let b=g.data;if(!de(b)||b.channel_key!==t||b.origin!==o)return;y();try{c.close()}catch{}h({token:b.token,expires_at:b.expires_at,reader:b.reader})},m=setInterval(()=>{let g=!1;try{g=c.closed}catch{}if(!g)return;clearInterval(m),setTimeout(()=>{if(u)return;y(),p(new d(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",f)})}function q(e){return`yuva:${e}`}function K(e,t){return`yuva:reader:${e} ${t}`}function j(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function he(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i.sub==="string"?i.sub:null}catch{return null}}function ue(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,i)=>void e.set(t,i)}}function M(e){let t=new URLSearchParams;for(let[s,n]of Object.entries(e))if(n!==void 0)t.set(s,String(n));let i=t.toString();return i?`?${i}`:""}function pe(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function fe(e,t,i){let s=[];for(let[n,o]of e)s.push(`--${i}\r
1
+ (()=>{class d extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function P(e,t,i,{method:s="GET",json:n,body:o,headers:r={},token:l,blob:c}={}){if(r={...r},l)r.Authorization=`Bearer ${l}`;let h=o;if(n!==void 0)r["Content-Type"]="application/json",h=JSON.stringify(n);let p;try{p=await e(t+i,{method:s,headers:r,body:h,credentials:"omit"})}catch{throw new d(0,"network")}if(!p.ok){let u="error";try{u=(await p.json()).code??u}catch{}throw new d(p.status,u)}if(p.status===204)return;return c?await p.blob():await p.json()}function z(e,t,i){return P(e,t,`/client/v1/channels/${encodeURIComponent(i)}/lists`)}function O(e,t,i,s){return P(e,t,`/client/v1/channels/${encodeURIComponent(i)}/subscriptions`,{method:"POST",json:s})}class R{server;socketClass;handlers;#e=null;#i=0;#n=0;#t=null;#r=!0;constructor(e,t,i){this.server=e;this.socketClass=t;this.handlers=i}get connected(){return this.#e?.readyState===1}start(){if(this.#r=!1,!this.#e&&!this.#t)this.#o()}stop(){if(this.#r=!0,this.#t)clearTimeout(this.#t);this.#t=null;let e=this.#e;this.#e=null,e?.close(1000)}reset(){this.#i=0}nudge(){if(this.#r||this.#e)return;if(this.#t)clearTimeout(this.#t);this.#t=null,this.#o()}#o(){let e=this.handlers.token();if(!e||this.#r)return;let t=new URL(`${this.server}/client/v1/realtime`,globalThis.location?.href);if(t.protocol=t.protocol==="https:"?"wss:":"ws:",this.#i>0)t.searchParams.set("last_event_id",String(this.#i));let i;try{i=new this.socketClass(t,["yuva",`yuva.token.${e}`])}catch{this.#s();return}this.#e=i,i.onmessage=(s)=>{let n;try{n=JSON.parse(String(s.data))}catch{return}if(n.type==="ready")this.#n=0,this.#i=Math.max(this.#i,n.last_event_id);else if("id"in n&&typeof n.id==="number")this.#i=Math.max(this.#i,n.id);this.handlers.event(n)},i.onclose=(s)=>{if(this.#e!==i)return;if(this.#e=null,this.#r)return;if(s.code===1008){this.#i=0,this.handlers.sessionEnded();return}this.#s()}}#s(){if(this.#r||this.#t)return;let e=this.#n++;this.handlers.reconnecting(e);let t=Math.min(30000,1000*2**e)*(0.75+Math.random()*0.5);this.#t=setTimeout(()=>{this.#t=null,this.#o()},t)}}function ce(e,t,i){let s=new URL("/account/connect",e);return s.searchParams.set("channel",t),s.searchParams.set("origin",i),s.href}function de(e){let t=e;return!!t&&typeof t.token==="string"&&t.token.startsWith("yuva_rd_")&&typeof t.expires_at==="string"&&!Number.isNaN(Date.parse(t.expires_at))&&typeof t.channel_key==="string"&&typeof t.origin==="string"&&!!t.reader&&typeof t.reader.initials==="string"}function W(e,t,{width:i=460,height:s=640}={}){let n=new URL(e).origin,o=location.origin,r=Math.max(0,(window.screenX??0)+((window.outerWidth??i)-i)/2),l=Math.max(0,(window.screenY??0)+((window.outerHeight??s)-s)/2),c=window.open(ce(e,t,o),"yuva-reader",`popup=yes,width=${i},height=${s},left=${Math.round(r)},top=${Math.round(l)}`);if(!c)return Promise.reject(new d(0,"popup_blocked"));return new Promise((h,p)=>{let u=!1,y=()=>{u=!0,window.removeEventListener("message",f),clearInterval(m)},f=(g)=>{if(u||g.origin!==n||g.source&&g.source!==c)return;let b=g.data;if(!de(b)||b.channel_key!==t||b.origin!==o)return;y();try{c.close()}catch{}h({token:b.token,expires_at:b.expires_at,reader:b.reader})},m=setInterval(()=>{let g=!1;try{g=c.closed}catch{}if(!g)return;clearInterval(m),setTimeout(()=>{if(u)return;y(),p(new d(0,"sign_in_cancelled"))},300)},500);window.addEventListener("message",f)})}function q(e){return`yuva:${e}`}function K(e,t){return`yuva:reader:${e} ${t}`}function j(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();return Array.from(crypto.getRandomValues(new Uint8Array(16)),(e)=>e.toString(16).padStart(2,"0")).join("")}function he(e){try{let t=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),i=JSON.parse(atob(t));return typeof i.sub==="string"?i.sub:null}catch{return null}}function ue(){try{let t=globalThis.localStorage;if(t)return t}catch{}let e=new Map;return{getItem:(t)=>e.get(t)??null,setItem:(t,i)=>void e.set(t,i)}}function M(e){let t=new URLSearchParams;for(let[s,n]of Object.entries(e))if(n!==void 0)t.set(s,String(n));let i=t.toString();return i?`?${i}`:""}function pe(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function fe(e,t,i){let s=[];for(let[n,o]of e)s.push(`--${i}\r
2
2
  Content-Disposition: form-data; name="${n}"\r
3
3
  \r
4
4
  ${o}\r
@@ -30,4 +30,4 @@ legend{padding:0;margin-block-end:4px;font-weight:600}
30
30
  .error{color:var(--d)}
31
31
  .trap{position:absolute;inset-inline-start:-1e4px;inline-size:1px;overflow:hidden}
32
32
  @media (max-width:480px){input{font-size:16px}}
33
- `;class f extends _{static observedAttributes=["channel","server","locale","dir","lists","layout","name","button-text","consent","privacy-url","identity-token"];static loadClient=null;#l;#L=g;#g=!1;#a=0;#i="loading";#C=!1;#b=null;#c=[];#h=new Set;#v="";#k=0;#w=!1;#r="";#u="";#y="";#d="";#x=null;#p=null;#S=new Set;#t=c("input");#n=c("input");#m=c("input");#o=c("input");#f=c("p");constructor(){super();this.#l=this.attachShadow({mode:"open"}),this.#t.type="email",this.#t.autocomplete="email",this.#t.required=!0,this.#t.maxLength=320,this.#t.id="email",this.#n.autocomplete="name",this.#n.maxLength=200,this.#n.id="name",this.#m.name="website",this.#m.tabIndex=-1,this.#m.autocomplete="off",this.#o.type="checkbox",this.#o.id="consent",this.#o.addEventListener("change",()=>{this.#d="",this.#s()});for(let e of[this.#t,this.#n])e.setAttribute("part","field"),e.dir="auto";this.#f.setAttribute("part","status"),this.#f.setAttribute("role","status"),this.#f.setAttribute("aria-live","polite")}get channel(){return this.getAttribute("channel")}set channel(e){this.#A("channel",e)}get server(){return(this.getAttribute("server")||(x?new URL(x).origin:location.origin)).replace(/\/+$/,"")}set server(e){this.#A("server",e)}get locale(){return E(L,[this.getAttribute("locale"),navigator.language])}set locale(e){this.#A("locale",e)}get lists(){return this.#c.map((e)=>e.list)}setIdentityToken(e){if(this.#x=e,this.#g)this.#P()}connectedCallback(){this.#g=!0,this.#P()}disconnectedCallback(){this.#g=!1}attributeChangedCallback(e,t,i){if(!this.#g||t===i)return;if(["channel","server","lists","identity-token"].includes(e))return void this.#P();this.#s()}#A(e,t){if(t===null||t===void 0||t==="")this.removeAttribute(e);else this.setAttribute(e,t)}#e(e){return P(this.#L,e,g)}get#q(){return!!this.#x||this.hasAttribute("identity-token")}async#T(){return this.#x?await this.#x()??null:this.getAttribute("identity-token")}#I(e){let t=(this.getAttribute("lists")??"").split(",").map((n)=>n.trim()).filter((n)=>n&&n!=="all");if(t.length===0)return e;let i=t.map((n)=>e.find((s)=>s.id===n)).filter((n)=>!!n);if(i.length<t.length)console.warn(`Yuva: some lists in "${t.join(",")}" are not public lists`);return i}async#P(){let e=++this.#a,t=this.channel;if(this.#C=!1,this.#i="loading",this.#c=[],this.#r="",this.#p=null,this.#s(),!t)return;let i=this.server;try{let n=b(y,i,`/client/v1/channels/${encodeURIComponent(t)}`),s=null;if(this.#q&&f.loadClient&&await this.#T()){let{createYuvaClient:r}=await f.loadClient(),o=r({server:i,channel:t,identityToken:()=>this.#T()});try{let{items:a}=await o.subscriptions(),l=new Set(this.#I(a.map((h)=>h.list)));s=a.filter((h)=>l.has(h.list)),this.#p=o}catch(a){if(!(a instanceof p)||a.code!=="identity_required")throw a}}if(!s){let{lists:r,form_token:o}=await C(y,i,t);s=this.#I(r).map((a)=>({list:a})),this.#v=o,this.#k=Date.now()}if(this.#b=await n,e!==this.#a)return;if(this.#c=s,this.#h=new Set(s.length===1?[s[0].list.id]:[]),this.#i="idle",s.length===0)console.warn(`Yuva: channel ${t} has no public mailing lists to offer`)}catch(n){if(e!==this.#a)return;if(this.#R(n))return;this.#i="idle",this.#r=this.#E(n)}this.#s()}#R(e){let t=e instanceof p&&(e.status===404||e.code==="origin_not_allowed"||e.code==="page_origin");if(t)this.#C=!0,console.warn(`Yuva: channel ${this.channel} is unknown, offers no such list or does not allow ${location.origin}`),this.#s();return t}#E(e){let t=e instanceof p?e.code:"";if(t==="rate_limited")return this.#e({id:"tzsBOP"});if(t==="network")return this.#e({id:"GQVIIl"});if(t==="no_email")return this.#e({id:"eku1-t"});return this.#e({id:"jWgNnM"})}#M(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#D(e){this.#M("yuva-subscribe-error",{code:e instanceof p?e.code:"error"})}consentText(e=this.#_()){let t=this.getAttribute("consent")?.trim();if(t)return t;let i=(e.length?e:this.lists).map((r)=>r.name),n=new Intl.ListFormat(this.locale,{type:"conjunction"}).format(i),s=this.#b?.name??"";return this.#e({id:"dMJfG5",values:{list:n,inbox:s}})}#_(){return this.lists.filter((e)=>this.#h.has(e.id))}async#N(){if(this.#i!=="idle"||!this.channel)return;let e=this.#_(),t=this.#t.value.trim(),i=this.#n.value.trim(),n=this.getAttribute("name");if(this.#r=e.length===0?this.#e({id:"-g5O6h"}):"",this.#u=this.#t.checkValidity()&&t?"":this.#e({id:"E_qvzP"}),this.#y=n==="required"&&!i?this.#e({id:"E_LjOR"}):"",this.#d=this.#o.checked?"":this.#e({id:"lDEbTy"}),this.#r||this.#u||this.#y||this.#d){this.#s();let l=[this.#u&&this.#t,this.#y&&this.#n,this.#d&&this.#o];for(let h of l)if(h)return h.focus();return}let s=this.channel,r=this.#a,o=this.consentText(e);this.#i="submitting",this.#s();let a=async(l)=>{let h=this.#k+D-Date.now();if(h>0)await new Promise((u)=>setTimeout(u,h));try{let{confirmation:u}=await k(y,this.server,s,{email:t,name:n==="optional"||n==="required"?i||void 0:void 0,list_ids:e.map((d)=>d.id),locale:this.locale,page_url:location.href.split("#")[0].slice(0,2000),consent_text:o,form_token:this.#v,website:this.#m.value||void 0});return this.#w=u,!0}catch(u){if(l&&u instanceof p&&u.code==="form_token"){let d=await C(y,this.server,s);return this.#v=d.form_token,this.#k=Date.now(),a(!1)}throw u}};try{await a(!0)}catch(l){if(r!==this.#a)return;if(this.#D(l),this.#i="idle",this.#R(l))return;if(l instanceof p&&l.code==="invalid_email")return this.#u=this.#e({id:"E_qvzP"}),this.#s(),this.#t.focus();return this.#r=this.#E(l),this.#s()}if(r!==this.#a)return;this.#i="done",this.#M("yuva-subscribe",{lists:e.map((l)=>l.id),confirmation:this.#w}),this.#s()}async#j(e,t){let i=this.#p;if(!i||this.#S.has(e.list.id))return;this.#S.add(e.list.id),this.#r="",this.#s();try{if(t){let{state:n}=await i.subscribeList(e.list.id,{consent_text:this.consentText([e.list]),page_url:location.href.split("#")[0].slice(0,2000)});e.state=n,this.#M("yuva-subscribe",{lists:[e.list.id],confirmation:n==="pending"})}else await i.unsubscribeList(e.list.id),e.state="unsubscribed"}catch(n){this.#D(n),this.#r=this.#E(n)}if(this.#S.delete(e.list.id),i===this.#p)this.#s()}#z(e,t){if(e.setAttribute("aria-invalid",String(!!t)),!t)return e.removeAttribute("aria-describedby"),null;let i=`${e.id}-error`;e.setAttribute("aria-describedby",i);let n=c("p","error",t);return n.id=i,n}#U(e,t,i,n){let s=c("label","check"),r=c("input");r.type="checkbox",r.checked=t,r.dataset.key=n,r.addEventListener("change",()=>i(r.checked));let o=c("span","text");return o.append(...e),s.append(r,o),s}#O(e){if(!e&&this.#c.length<2)return null;let t=c("fieldset");t.append(c("legend","",this.#e({id:"h16FyT"})));for(let i of this.#c){let n=[c("span","",i.list.name)];if(i.list.description)n.push(c("span","muted",i.list.description));if(e){if(n.push(c("span","muted consent",this.consentText([i.list]))),i.state==="pending")n.push(c("span","muted",this.#e({id:"x6dU53"})))}let s=e?i.state==="subscribed"||i.state==="pending":this.#h.has(i.list.id),r=this.#U(n,s,(a)=>{if(e)return void this.#j(i,a);if(a)this.#h.add(i.list.id);else this.#h.delete(i.list.id);this.#r="",this.#s()},i.list.id),o=r.querySelector("input");if(e)o.setAttribute("role","switch"),o.setAttribute("aria-checked",String(o.checked)),o.addEventListener("keydown",(a)=>{if(a.key!=="Enter")return;a.preventDefault(),o.click()}),o.disabled=this.#S.has(i.list.id);else o.disabled=this.#i==="submitting";t.append(r)}return t}#J(){let e=c("form",this.getAttribute("layout")==="inline"?"inline":"");e.noValidate=!0,e.addEventListener("submit",(m)=>{m.preventDefault(),this.#N()});let t=this.#i==="submitting",i=this.#O(!1);if(i)e.append(i);let n=c("div","row"),s=[],r=this.getAttribute("name");if(r==="optional"||r==="required"){this.#n.placeholder=r==="required"?this.#e({id:"q8yluz"}):this.#e({id:"YnOaHp"}),this.#n.setAttribute("aria-label",this.#n.placeholder),this.#n.required=r==="required",this.#n.disabled=t,n.append(this.#n);let m=this.#z(this.#n,this.#y);if(m)s.push(m)}this.#t.placeholder=this.#e({id:"XJURKP"}),this.#t.setAttribute("aria-label",this.#t.placeholder),this.#t.disabled=t,n.append(this.#t);let o=this.#z(this.#t,this.#u);if(o)s.push(o);let a=c("button","",t?this.#e({id:"1w51t9"}):this.getAttribute("button-text")||this.#e({id:"EDl9kS"}));a.type="submit",a.disabled=t,a.setAttribute("part","button"),n.append(a);let l=c("div","trap");l.setAttribute("aria-hidden","true"),l.append(this.#m);let h=c("span","",this.consentText()),u=c("label","check consent");u.setAttribute("part","consent"),this.#o.disabled=t;let d=c("span");d.append(h);let S=this.getAttribute("privacy-url");if(S&&/^https?:\/\//i.test(S)){let m=c("a","",this.#e({id:"ScJ9fj"}));m.href=S,m.target="_blank",m.rel="noopener noreferrer",d.append(" ",m)}u.append(this.#o,d);let v=this.#z(this.#o,this.#d);if(e.append(n,...s,u),v)e.append(v);return e.append(l),e}#s(){if(this.#C||!this.channel||this.#i!=="loading"&&this.#c.length===0&&!this.#r){this.#l.replaceChildren();return}let e=this.locale;this.#L=L[e]??g;let t=this.getAttribute("dir"),i=c("div","frame");i.dir=t==="rtl"||t==="ltr"?t:M(e),i.lang=e;let n=this.#b?.chat.launcher_color??this.#b?.branding.color;if(n&&/^#[0-9a-f]{6}$/i.test(n))i.style.setProperty("--brand",n),i.style.setProperty("--brand-on",z(n));let s="";if(this.#i==="done")s=this.#w?this.#e({id:"y3k2zM"}):this.#e({id:"rgySXy"});if(this.#f.textContent=s,this.#i==="idle"||this.#i==="submitting"){let h=this.#p?this.#O(!0):this.#J();if(h)i.append(h)}if(i.append(this.#f),this.#r){let h=c("p","error",this.#r);h.setAttribute("role","alert"),i.append(h)}let r,o=null;try{o=this.#l.activeElement}catch{}if(o instanceof HTMLInputElement)r=o.dataset.key;let a=c("style");a.textContent=O,this.#l.replaceChildren(a,i);let l=r?this.#l.querySelector(`[data-key="${r}"]`):o;if(l instanceof HTMLElement&&l.isConnected)l.focus({preventScroll:!0})}}function T(){if(typeof customElements>"u")return;if(!customElements.get("yuva-subscribe"))customElements.define("yuva-subscribe",f)}f.loadClient=()=>import(new URL("widget/yuva-subscribe-client-s3cx942g.js",x||location.href).href);T();})();
33
+ `;class f extends _{static observedAttributes=["channel","server","locale","dir","lists","layout","name","button-text","consent","privacy-url","identity-token"];static loadClient=null;#l;#L=g;#g=!1;#a=0;#i="loading";#C=!1;#b=null;#c=[];#h=new Set;#v="";#k=0;#w=!1;#r="";#u="";#y="";#d="";#x=null;#p=null;#S=new Set;#t=c("input");#n=c("input");#m=c("input");#o=c("input");#f=c("p");constructor(){super();this.#l=this.attachShadow({mode:"open"}),this.#t.type="email",this.#t.autocomplete="email",this.#t.required=!0,this.#t.maxLength=320,this.#t.id="email",this.#n.autocomplete="name",this.#n.maxLength=200,this.#n.id="name",this.#m.name="website",this.#m.tabIndex=-1,this.#m.autocomplete="off",this.#o.type="checkbox",this.#o.id="consent",this.#o.addEventListener("change",()=>{this.#d="",this.#s()});for(let e of[this.#t,this.#n])e.setAttribute("part","field"),e.dir="auto";this.#f.setAttribute("part","status"),this.#f.setAttribute("role","status"),this.#f.setAttribute("aria-live","polite")}get channel(){return this.getAttribute("channel")}set channel(e){this.#A("channel",e)}get server(){return(this.getAttribute("server")||(x?new URL(x).origin:location.origin)).replace(/\/+$/,"")}set server(e){this.#A("server",e)}get locale(){return E(L,[this.getAttribute("locale"),navigator.language])}set locale(e){this.#A("locale",e)}get lists(){return this.#c.map((e)=>e.list)}setIdentityToken(e){if(this.#x=e,this.#g)this.#P()}connectedCallback(){this.#g=!0,this.#P()}disconnectedCallback(){this.#g=!1}attributeChangedCallback(e,t,i){if(!this.#g||t===i)return;if(["channel","server","lists","identity-token"].includes(e))return void this.#P();this.#s()}#A(e,t){if(t===null||t===void 0||t==="")this.removeAttribute(e);else this.setAttribute(e,t)}#e(e){return P(this.#L,e,g)}get#q(){return!!this.#x||this.hasAttribute("identity-token")}async#T(){return this.#x?await this.#x()??null:this.getAttribute("identity-token")}#I(e){let t=(this.getAttribute("lists")??"").split(",").map((n)=>n.trim()).filter((n)=>n&&n!=="all");if(t.length===0)return e;let i=t.map((n)=>e.find((s)=>s.id===n)).filter((n)=>!!n);if(i.length<t.length)console.warn(`Yuva: some lists in "${t.join(",")}" are not public lists`);return i}async#P(){let e=++this.#a,t=this.channel;if(this.#C=!1,this.#i="loading",this.#c=[],this.#r="",this.#p=null,this.#s(),!t)return;let i=this.server;try{let n=b(y,i,`/client/v1/channels/${encodeURIComponent(t)}`),s=null;if(this.#q&&f.loadClient&&await this.#T()){let{createYuvaClient:r}=await f.loadClient(),o=r({server:i,channel:t,identityToken:()=>this.#T()});try{let{items:a}=await o.subscriptions(),l=new Set(this.#I(a.map((h)=>h.list)));s=a.filter((h)=>l.has(h.list)),this.#p=o}catch(a){if(!(a instanceof p)||a.code!=="identity_required")throw a}}if(!s){let{lists:r,form_token:o}=await C(y,i,t);s=this.#I(r).map((a)=>({list:a})),this.#v=o,this.#k=Date.now()}if(this.#b=await n,e!==this.#a)return;if(this.#c=s,this.#h=new Set(s.length===1?[s[0].list.id]:[]),this.#i="idle",s.length===0)console.warn(`Yuva: channel ${t} has no public mailing lists to offer`)}catch(n){if(e!==this.#a)return;if(this.#R(n))return;this.#i="idle",this.#r=this.#E(n)}this.#s()}#R(e){let t=e instanceof p&&(e.status===404||e.code==="origin_not_allowed"||e.code==="page_origin");if(t)this.#C=!0,console.warn(`Yuva: channel ${this.channel} is unknown, offers no such list or does not allow ${location.origin}`),this.#s();return t}#E(e){let t=e instanceof p?e.code:"";if(t==="rate_limited")return this.#e({id:"tzsBOP"});if(t==="network")return this.#e({id:"GQVIIl"});if(t==="no_email")return this.#e({id:"eku1-t"});return this.#e({id:"jWgNnM"})}#M(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}#D(e){this.#M("yuva-subscribe-error",{code:e instanceof p?e.code:"error"})}consentText(e=this.#_()){let t=this.getAttribute("consent")?.trim();if(t)return t;let i=(e.length?e:this.lists).map((r)=>r.name),n=new Intl.ListFormat(this.locale,{type:"conjunction"}).format(i),s=this.#b?.name??"";return this.#e({id:"dMJfG5",values:{list:n,inbox:s}})}#_(){return this.lists.filter((e)=>this.#h.has(e.id))}async#N(){if(this.#i!=="idle"||!this.channel)return;let e=this.#_(),t=this.#t.value.trim(),i=this.#n.value.trim(),n=this.getAttribute("name");if(this.#r=e.length===0?this.#e({id:"-g5O6h"}):"",this.#u=this.#t.checkValidity()&&t?"":this.#e({id:"E_qvzP"}),this.#y=n==="required"&&!i?this.#e({id:"E_LjOR"}):"",this.#d=this.#o.checked?"":this.#e({id:"lDEbTy"}),this.#r||this.#u||this.#y||this.#d){this.#s();let l=[this.#u&&this.#t,this.#y&&this.#n,this.#d&&this.#o];for(let h of l)if(h)return h.focus();return}let s=this.channel,r=this.#a,o=this.consentText(e);this.#i="submitting",this.#s();let a=async(l)=>{let h=this.#k+D-Date.now();if(h>0)await new Promise((u)=>setTimeout(u,h));try{let{confirmation:u}=await k(y,this.server,s,{email:t,name:n==="optional"||n==="required"?i||void 0:void 0,list_ids:e.map((d)=>d.id),locale:this.locale,page_url:location.href.split("#")[0].slice(0,2000),consent_text:o,form_token:this.#v,website:this.#m.value||void 0});return this.#w=u,!0}catch(u){if(l&&u instanceof p&&u.code==="form_token"){let d=await C(y,this.server,s);return this.#v=d.form_token,this.#k=Date.now(),a(!1)}throw u}};try{await a(!0)}catch(l){if(r!==this.#a)return;if(this.#D(l),this.#i="idle",this.#R(l))return;if(l instanceof p&&l.code==="invalid_email")return this.#u=this.#e({id:"E_qvzP"}),this.#s(),this.#t.focus();return this.#r=this.#E(l),this.#s()}if(r!==this.#a)return;this.#i="done",this.#M("yuva-subscribe",{lists:e.map((l)=>l.id),confirmation:this.#w}),this.#s()}async#j(e,t){let i=this.#p;if(!i||this.#S.has(e.list.id))return;this.#S.add(e.list.id),this.#r="",this.#s();try{if(t){let{state:n}=await i.subscribeList(e.list.id,{consent_text:this.consentText([e.list]),page_url:location.href.split("#")[0].slice(0,2000)});e.state=n,this.#M("yuva-subscribe",{lists:[e.list.id],confirmation:n==="pending"})}else await i.unsubscribeList(e.list.id),e.state="unsubscribed"}catch(n){this.#D(n),this.#r=this.#E(n)}if(this.#S.delete(e.list.id),i===this.#p)this.#s()}#z(e,t){if(e.setAttribute("aria-invalid",String(!!t)),!t)return e.removeAttribute("aria-describedby"),null;let i=`${e.id}-error`;e.setAttribute("aria-describedby",i);let n=c("p","error",t);return n.id=i,n}#U(e,t,i,n){let s=c("label","check"),r=c("input");r.type="checkbox",r.checked=t,r.dataset.key=n,r.addEventListener("change",()=>i(r.checked));let o=c("span","text");return o.append(...e),s.append(r,o),s}#O(e){if(!e&&this.#c.length<2)return null;let t=c("fieldset");t.append(c("legend","",this.#e({id:"h16FyT"})));for(let i of this.#c){let n=[c("span","",i.list.name)];if(i.list.description)n.push(c("span","muted",i.list.description));if(e){if(n.push(c("span","muted consent",this.consentText([i.list]))),i.state==="pending")n.push(c("span","muted",this.#e({id:"x6dU53"})))}let s=e?i.state==="subscribed"||i.state==="pending":this.#h.has(i.list.id),r=this.#U(n,s,(a)=>{if(e)return void this.#j(i,a);if(a)this.#h.add(i.list.id);else this.#h.delete(i.list.id);this.#r="",this.#s()},i.list.id),o=r.querySelector("input");if(e)o.setAttribute("role","switch"),o.setAttribute("aria-checked",String(o.checked)),o.addEventListener("keydown",(a)=>{if(a.key!=="Enter")return;a.preventDefault(),o.click()}),o.disabled=this.#S.has(i.list.id);else o.disabled=this.#i==="submitting";t.append(r)}return t}#J(){let e=c("form",this.getAttribute("layout")==="inline"?"inline":"");e.noValidate=!0,e.addEventListener("submit",(m)=>{m.preventDefault(),this.#N()});let t=this.#i==="submitting",i=this.#O(!1);if(i)e.append(i);let n=c("div","row"),s=[],r=this.getAttribute("name");if(r==="optional"||r==="required"){this.#n.placeholder=r==="required"?this.#e({id:"q8yluz"}):this.#e({id:"YnOaHp"}),this.#n.setAttribute("aria-label",this.#n.placeholder),this.#n.required=r==="required",this.#n.disabled=t,n.append(this.#n);let m=this.#z(this.#n,this.#y);if(m)s.push(m)}this.#t.placeholder=this.#e({id:"XJURKP"}),this.#t.setAttribute("aria-label",this.#t.placeholder),this.#t.disabled=t,n.append(this.#t);let o=this.#z(this.#t,this.#u);if(o)s.push(o);let a=c("button","",t?this.#e({id:"1w51t9"}):this.getAttribute("button-text")||this.#e({id:"EDl9kS"}));a.type="submit",a.disabled=t,a.setAttribute("part","button"),n.append(a);let l=c("div","trap");l.setAttribute("aria-hidden","true"),l.append(this.#m);let h=c("span","",this.consentText()),u=c("label","check consent");u.setAttribute("part","consent"),this.#o.disabled=t;let d=c("span");d.append(h);let S=this.getAttribute("privacy-url");if(S&&/^https?:\/\//i.test(S)){let m=c("a","",this.#e({id:"ScJ9fj"}));m.href=S,m.target="_blank",m.rel="noopener noreferrer",d.append(" ",m)}u.append(this.#o,d);let v=this.#z(this.#o,this.#d);if(e.append(n,...s,u),v)e.append(v);return e.append(l),e}#s(){if(this.#C||!this.channel||this.#i!=="loading"&&this.#c.length===0&&!this.#r){this.#l.replaceChildren();return}let e=this.locale;this.#L=L[e]??g;let t=this.getAttribute("dir"),i=c("div","frame");i.dir=t==="rtl"||t==="ltr"?t:M(e),i.lang=e;let n=this.#b?.chat.launcher_color??this.#b?.branding.color;if(n&&/^#[0-9a-f]{6}$/i.test(n))i.style.setProperty("--brand",n),i.style.setProperty("--brand-on",z(n));let s="";if(this.#i==="done")s=this.#w?this.#e({id:"y3k2zM"}):this.#e({id:"rgySXy"});if(this.#f.textContent=s,this.#i==="idle"||this.#i==="submitting"){let h=this.#p?this.#O(!0):this.#J();if(h)i.append(h)}if(i.append(this.#f),this.#r){let h=c("p","error",this.#r);h.setAttribute("role","alert"),i.append(h)}let r,o=null;try{o=this.#l.activeElement}catch{}if(o instanceof HTMLInputElement)r=o.dataset.key;let a=c("style");a.textContent=O,this.#l.replaceChildren(a,i);let l=r?this.#l.querySelector(`[data-key="${r}"]`):o;if(l instanceof HTMLElement&&l.isConnected)l.focus({preventScroll:!0})}}function T(){if(typeof customElements>"u")return;if(!customElements.get("yuva-subscribe"))customElements.define("yuva-subscribe",f)}f.loadClient=()=>import(new URL("widget/yuva-subscribe-client-jya732vb.js",x||location.href).href);T();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "useyuva",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "Yuva for the web: a headless client for contacts, the <yuva-chat> element, documentation page feedback and discussions, the <yuva-subscribe> mailing list form, cookieless web analytics, React hooks, a Nuxt module and a typed /v1 client.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,193 +0,0 @@
1
- import{randomId2,createYuvaClient2}from"./index-8hzbxjv3.js";import{richText}from"./index-jdxce2se.js";import{ApiError2}from"./index-gk84nm8f.js";import{launcherOf,readStored,writeStored}from"./index-98r96a7e.js";import{setupI18n}from"@lingui/core";var messages=JSON.parse(`{"-HY5kX":["New conversation"],"-f5Tkb":["Bad"],"09Tv5j":["Reconnecting…"],"0XGLbP":["Your sign-in has expired. Reload the page and try again."],"1EICzz":["We're away right now"],"4TqZiz":["Could not send your rating. Try again."],"6Uau97":["Skip"],"6gRgw8":["Retry"],"6lGaum":["Seen"],"ASr-r0":["Show older conversations"],"Amai22":["Chat is not available right now."],"E_qvzP":["Enter a valid e-mail address."],"GQVIIl":["You seem to be offline."],"JkW3Ph":["This file type is not accepted."],"JlFcis":["Send"],"KDw4GX":["Try again"],"M62PBt":["Nobody is available right now. Leave your e-mail and we'll send the reply there too."],"N7m8E-":["Attach files"],"NBdIgR":["Comment"],"OEEQKT":["Good"],"Pwqkdw":["Loading…"],"PxYAul":["Typing…"],"RzWUUK":["Write a message…"],"S63MQu":["All conversations"],"SOk0EB":["Thanks for your feedback"],"Sad2tK":["Sending…"],"SdV5Cn":["Send us a message and we will reply here."],"UY1vmE":["Attachment"],"VggdQJ":["Usually replies in ",["duration"]],"XJURKP":["E-mail address"],"YyNOE7":["Conversation"],"ZxJcgC":["Could not save your e-mail address. Try again."],"axQ1h6":["Anything you'd like to add? (optional)"],"eOu9Px":["The file is too large."],"h69WC6":["Sent"],"iGNUZJ":["Thanks! We'll e-mail you at ",["known"]," if you're gone when we reply."],"meAa31":["No conversations yet"],"nhTADq":["We'll reply as soon as we can"],"njBr8W":["you@example.com"],"oXOSPE":["Online"],"t7TeQU":["Messages"],"tHaDPf":[["name"]," is typing…"],"tfDRzk":["Save"],"tzsBOP":["Too many attempts. Wait a moment and try again."],"uA8iBc":["How did we do?"],"upFvcp":["Not sent."],"w61W3L":["Remove ",["0"]],"xDAtGP":["Message"],"ydzYKJ":["You:"],"yz7wBu":["Close"],"zLzEI3":["Sign in to chat with us."]}`);var messages2=JSON.parse('{"-HY5kX":["Neue Unterhaltung"],"-f5Tkb":["Schlecht"],"09Tv5j":["Verbindung wird wiederhergestellt…"],"0XGLbP":["Ihre Anmeldung ist abgelaufen. Laden Sie die Seite neu und versuchen Sie es erneut."],"1EICzz":["Wir sind gerade nicht da"],"4TqZiz":["Ihre Bewertung konnte nicht gesendet werden. Versuchen Sie es erneut."],"6Uau97":["Überspringen"],"6gRgw8":["Erneut versuchen"],"6lGaum":["Gesehen"],"ASr-r0":["Ältere Unterhaltungen anzeigen"],"Amai22":["Der Chat ist gerade nicht verfügbar."],"E_qvzP":["Geben Sie eine gültige E-Mail-Adresse ein."],"GQVIIl":["Sie scheinen offline zu sein."],"JkW3Ph":["Dieser Dateityp wird nicht akzeptiert."],"JlFcis":["Senden"],"KDw4GX":["Erneut versuchen"],"M62PBt":["Gerade ist niemand erreichbar. Hinterlassen Sie Ihre E-Mail-Adresse, dann senden wir die Antwort auch dorthin."],"N7m8E-":["Dateien anhängen"],"NBdIgR":["Kommentar"],"OEEQKT":["Gut"],"Pwqkdw":["Wird geladen…"],"PxYAul":["Schreibt…"],"RzWUUK":["Nachricht schreiben…"],"S63MQu":["Alle Unterhaltungen"],"SOk0EB":["Danke für Ihr Feedback"],"Sad2tK":["Wird gesendet…"],"SdV5Cn":["Schreiben Sie uns, wir antworten hier."],"UY1vmE":["Anhang"],"VggdQJ":["Übliche Antwortzeit: ",["duration"]],"XJURKP":["E-Mail-Adresse"],"YyNOE7":["Unterhaltung"],"ZxJcgC":["Ihre E-Mail-Adresse konnte nicht gespeichert werden. Versuchen Sie es erneut."],"axQ1h6":["Möchten Sie noch etwas ergänzen? (optional)"],"eOu9Px":["Die Datei ist zu groß."],"h69WC6":["Gesendet"],"iGNUZJ":["Danke! Falls Sie nicht mehr da sind, wenn wir antworten, schreiben wir Ihnen an ",["known"],"."],"meAa31":["Noch keine Unterhaltungen"],"nhTADq":["Wir antworten so schnell wie möglich"],"njBr8W":["sie@beispiel.de"],"oXOSPE":["Online"],"t7TeQU":["Nachrichten"],"tHaDPf":[["name"]," schreibt…"],"tfDRzk":["Speichern"],"tzsBOP":["Zu viele Versuche. Warten Sie einen Moment und versuchen Sie es erneut."],"uA8iBc":["Wie zufrieden waren Sie?"],"upFvcp":["Nicht gesendet."],"w61W3L":[["0"]," entfernen"],"xDAtGP":["Nachricht"],"ydzYKJ":["Sie:"],"yz7wBu":["Schließen"],"zLzEI3":["Melden Sie sich an, um mit uns zu chatten."]}');var messages3=JSON.parse('{"-HY5kX":["Yeni konuşma"],"-f5Tkb":["Kötü"],"09Tv5j":["Yeniden bağlanıyor…"],"0XGLbP":["Oturumunuzun süresi doldu. Sayfayı yenileyip tekrar deneyin."],"1EICzz":["Şu anda uzaktayız"],"4TqZiz":["Değerlendirmeniz gönderilemedi. Tekrar deneyin."],"6Uau97":["Geç"],"6gRgw8":["Tekrar dene"],"6lGaum":["Görüldü"],"ASr-r0":["Eski konuşmaları göster"],"Amai22":["Sohbet şu anda kullanılamıyor."],"E_qvzP":["Geçerli bir e-posta adresi girin."],"GQVIIl":["Çevrimdışı görünüyorsunuz."],"JkW3Ph":["Bu dosya türü kabul edilmiyor."],"JlFcis":["Gönder"],"KDw4GX":["Tekrar dene"],"M62PBt":["Şu anda müsait kimse yok. E-posta adresinizi bırakın, yanıtı oraya da gönderelim."],"N7m8E-":["Dosya ekle"],"NBdIgR":["Yorum"],"OEEQKT":["İyi"],"Pwqkdw":["Yükleniyor…"],"PxYAul":["Yazıyor…"],"RzWUUK":["Bir mesaj yazın…"],"S63MQu":["Tüm konuşmalar"],"SOk0EB":["Geri bildiriminiz için teşekkürler"],"Sad2tK":["Gönderiliyor…"],"SdV5Cn":["Bize bir mesaj gönderin, yanıtımız burada görünecek."],"UY1vmE":["Ek"],"VggdQJ":["Genellikle ",["duration"]," içinde yanıt verir"],"XJURKP":["E-posta adresi"],"YyNOE7":["Konuşma"],"ZxJcgC":["E-posta adresiniz kaydedilemedi. Tekrar deneyin."],"axQ1h6":["Eklemek istediğiniz bir şey var mı? (isteğe bağlı)"],"eOu9Px":["Dosya çok büyük."],"h69WC6":["Gönderildi"],"iGNUZJ":["Teşekkürler! Yanıtladığımızda burada değilseniz ",["known"]," adresine e-posta göndereceğiz."],"meAa31":["Henüz konuşma yok"],"nhTADq":["En kısa sürede yanıt vereceğiz"],"njBr8W":["siz@ornek.com"],"oXOSPE":["Çevrimiçi"],"t7TeQU":["Mesajlar"],"tHaDPf":[["name"]," yazıyor…"],"tfDRzk":["Kaydet"],"tzsBOP":["Çok fazla deneme. Biraz bekleyip tekrar deneyin."],"uA8iBc":["Nasıldık?"],"upFvcp":["Gönderilemedi."],"w61W3L":[["0"]," kaldır"],"xDAtGP":["Mesaj"],"ydzYKJ":["Siz:"],"yz7wBu":["Kapat"],"zLzEI3":["Bizimle sohbet etmek için giriş yapın."]}');var styles=`
2
- [hidden] { display: none !important; }
3
- .header {
4
- display: flex;
5
- align-items: center;
6
- gap: 10px;
7
- padding-block: 12px;
8
- padding-inline: 14px 10px;
9
- background: var(--yuva-accent);
10
- color: var(--yuva-on-accent);
11
- }
12
- .heading { flex: 1; min-inline-size: 0; }
13
- .title {
14
- margin: 0;
15
- font-size: 16px;
16
- font-weight: 600;
17
- overflow: hidden;
18
- text-overflow: ellipsis;
19
- white-space: nowrap;
20
- }
21
- .status { display: flex; align-items: center; gap: 6px; font-size: 13px; opacity: 0.9; }
22
- .dot { inline-size: 8px; block-size: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 0 2px rgb(255 255 255 / 0.6); }
23
- .dot.away { background: #9ca3af; }
24
- .avatars { display: flex; }
25
- .avatars .avatar { margin-inline-start: -8px; box-shadow: 0 0 0 2px var(--yuva-accent); }
26
- .avatars .avatar:first-child { margin-inline-start: 0; }
27
- .avatar {
28
- display: grid;
29
- place-items: center;
30
- flex: none;
31
- inline-size: 28px;
32
- block-size: 28px;
33
- border-radius: 50%;
34
- background: var(--yuva-soft);
35
- color: var(--yuva-fg);
36
- font-size: 11px;
37
- font-weight: 700;
38
- text-transform: uppercase;
39
- }
40
- .icon {
41
- display: grid;
42
- place-items: center;
43
- flex: none;
44
- inline-size: 32px;
45
- block-size: 32px;
46
- padding: 0;
47
- border: 0;
48
- border-radius: 8px;
49
- background: transparent;
50
- color: inherit;
51
- cursor: pointer;
52
- }
53
- .icon:hover { background: rgb(127 127 127 / 0.18); }
54
- .icon:focus-visible { outline: 2px solid currentColor; outline-offset: -4px; }
55
- [dir="rtl"] .flip { transform: scaleX(-1); }
56
- .body { position: relative; flex: 1; min-block-size: 0; display: flex; flex-direction: column; }
57
- .scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; padding: 14px; display: flex; flex-direction: column; gap: 4px; }
58
- .center { flex: 1; display: grid; place-content: center; gap: 6px; padding: 24px; text-align: center; }
59
- .empty { margin: 0; font-weight: 600; }
60
- .hint { margin: 0; color: var(--yuva-muted); font-size: 14px; }
61
- .list { list-style: none; margin: 0; padding: 6px; overflow-y: auto; flex: 1; }
62
- .item {
63
- display: flex;
64
- gap: 10px;
65
- align-items: center;
66
- inline-size: 100%;
67
- padding: 10px;
68
- border: 0;
69
- border-radius: 10px;
70
- background: transparent;
71
- color: inherit;
72
- font: inherit;
73
- text-align: start;
74
- cursor: pointer;
75
- }
76
- .item:hover, .item:focus-visible { background: var(--yuva-soft); outline: none; }
77
- .item-main { flex: 1; min-inline-size: 0; }
78
- .item-top { display: flex; gap: 8px; justify-content: space-between; }
79
- .item-subject, .item-preview { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
80
- .item-subject { font-weight: 600; }
81
- .item-preview { color: var(--yuva-muted); font-size: 14px; }
82
- .item.unread .item-preview { color: var(--yuva-fg); font-weight: 600; }
83
- .item-time { flex: none; color: var(--yuva-muted); font-size: 12px; }
84
- .unread-dot { flex: none; inline-size: 9px; block-size: 9px; border-radius: 50%; background: var(--yuva-accent); }
85
- .primary {
86
- margin: 10px;
87
- padding: 10px 14px;
88
- border: 0;
89
- border-radius: 10px;
90
- background: var(--yuva-accent);
91
- color: var(--yuva-on-accent);
92
- font: inherit;
93
- font-weight: 600;
94
- cursor: pointer;
95
- }
96
- .row { display: flex; gap: 8px; align-items: flex-end; max-inline-size: 85%; }
97
- .row.mine { align-self: flex-end; }
98
- .row.theirs .avatar { margin-block-end: 2px; }
99
- .avatar img { inline-size: 100%; block-size: 100%; border-radius: 50%; object-fit: cover; }
100
- .group-gap { margin-block-start: 8px; }
101
- .author { margin: 6px 0 2px; margin-inline-start: 36px; color: var(--yuva-muted); font-size: 12px; }
102
- .bubble {
103
- padding: 8px 12px;
104
- border-radius: 16px;
105
- background: var(--yuva-soft);
106
- overflow-wrap: anywhere;
107
- white-space: normal;
108
- }
109
- .mine .bubble { background: var(--yuva-accent); color: var(--yuva-on-accent); border-end-end-radius: 4px; }
110
- .theirs .bubble { border-end-start-radius: 4px; }
111
- .bubble a { color: inherit; text-decoration: underline; }
112
- .bubble code { font-family: ui-monospace, Menlo, monospace; font-size: 13px; padding: 1px 4px; border-radius: 4px; background: rgb(127 127 127 / 0.2); }
113
- .bubble pre { margin: 4px 0; padding: 8px; border-radius: 8px; background: rgb(127 127 127 / 0.2); font-family: ui-monospace, Menlo, monospace; font-size: 13px; white-space: pre-wrap; }
114
- .greeting { align-self: flex-start; max-inline-size: 85%; }
115
- .files { display: flex; flex-direction: column; gap: 4px; margin-block-start: 4px; }
116
- .files img { display: block; max-inline-size: 100%; max-block-size: 220px; border-radius: 10px; cursor: zoom-in; }
117
- .file {
118
- display: inline-flex;
119
- gap: 6px;
120
- align-items: center;
121
- padding: 6px 10px;
122
- border: 1px solid currentColor;
123
- border-radius: 8px;
124
- background: transparent;
125
- color: inherit;
126
- font: inherit;
127
- font-size: 13px;
128
- cursor: pointer;
129
- }
130
- .meta { align-self: flex-end; color: var(--yuva-muted); font-size: 12px; margin-block-start: 2px; }
131
- .meta.failed { color: var(--yuva-danger); }
132
- .link { padding: 0; border: 0; background: none; color: inherit; font: inherit; text-decoration: underline; cursor: pointer; }
133
- .typing { display: flex; gap: 6px; align-items: center; color: var(--yuva-muted); font-size: 13px; margin-block-start: 6px; }
134
- .typing i { display: inline-block; inline-size: 6px; block-size: 6px; border-radius: 50%; background: currentColor; animation: blink 1.2s infinite both; }
135
- .typing i:nth-child(2) { animation-delay: 0.2s; }
136
- .typing i:nth-child(3) { animation-delay: 0.4s; }
137
- @keyframes blink { 0%, 80%, 100% { opacity: 0.25; } 40% { opacity: 1; } }
138
- @media (prefers-reduced-motion: reduce) { .typing i { animation: none; } }
139
- .card { margin-block-start: 10px; padding: 12px; border: 1px solid var(--yuva-border); border-radius: 12px; font-size: 14px; }
140
- .card p { margin: 0 0 8px; }
141
- .card form { display: flex; gap: 6px; }
142
- .card input {
143
- flex: 1;
144
- min-inline-size: 0;
145
- padding: 8px 10px;
146
- border: 1px solid var(--yuva-border);
147
- border-radius: 8px;
148
- background: var(--yuva-bg);
149
- color: inherit;
150
- font: inherit;
151
- }
152
- .card button { padding: 8px 12px; border: 0; border-radius: 8px; background: var(--yuva-accent); color: var(--yuva-on-accent); font: inherit; font-weight: 600; cursor: pointer; }
153
- .card .error { margin: 6px 0 0; color: var(--yuva-danger); }
154
- .card button:disabled { opacity: 0.6; cursor: default; }
155
- .rate { text-align: center; }
156
- .choices { display: flex; justify-content: center; gap: 10px; }
157
- .card .choice { inline-size: 44px; block-size: 44px; padding: 0; border: 1px solid var(--yuva-border); border-radius: 50%; background: var(--yuva-bg); font-size: 20px; line-height: 1; }
158
- .card .choice:hover:not(:disabled), .card .choice[aria-pressed="true"] { border-color: var(--yuva-accent); box-shadow: 0 0 0 1px var(--yuva-accent); }
159
- .card .choice:disabled { opacity: 1; }
160
- .card .choice:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
161
- .rate .choices + p { margin: 8px 0 0; }
162
- .rate form { flex-direction: column; margin-block-start: 10px; }
163
- .rate textarea { box-sizing: border-box; inline-size: 100%; padding: 8px 10px; border: 1px solid var(--yuva-border); border-radius: 8px; background: var(--yuva-bg); color: inherit; font: inherit; resize: vertical; }
164
- .rate .actions { display: flex; justify-content: flex-end; align-items: center; gap: 14px; }
165
- .card .link { padding: 0; background: none; color: var(--yuva-muted); font-weight: 400; }
166
- .composer { border-block-start: 1px solid var(--yuva-border); padding: 8px; }
167
- .composer form { display: flex; gap: 4px; align-items: flex-end; }
168
- .composer textarea {
169
- flex: 1;
170
- min-inline-size: 0;
171
- box-sizing: border-box;
172
- block-size: 38px;
173
- max-block-size: 140px;
174
- padding: 8px 10px;
175
- border: 0;
176
- border-radius: 10px;
177
- background: transparent;
178
- color: inherit;
179
- font: inherit;
180
- resize: none;
181
- outline: none;
182
- }
183
- .composer .icon { color: var(--yuva-muted); }
184
- .composer .send { color: var(--yuva-accent); }
185
- .composer .send:disabled { opacity: 0.4; cursor: default; }
186
- .chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 6px 6px; }
187
- .chip { display: inline-flex; gap: 4px; align-items: center; max-inline-size: 100%; padding: 2px 4px 2px 10px; border-radius: 999px; background: var(--yuva-soft); font-size: 13px; }
188
- .chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-inline-size: 180px; }
189
- .chip .icon { inline-size: 22px; block-size: 22px; }
190
- .banner { padding: 6px 12px; background: var(--yuva-soft); color: var(--yuva-muted); font-size: 13px; text-align: center; }
191
- @media (max-width: 480px) { .composer textarea, .card input, .card textarea { font-size: 16px; } }
192
- .sr { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
193
- `;var catalogs={en:messages,tr:messages3,de:messages2},maxFiles=10,groupGap=300000,icons={close:'<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',back:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg>',attach:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 11.5l-8.3 8.3a5 5 0 01-7-7L13 4.5a3.3 3.3 0 014.7 4.7l-8.3 8.3a1.7 1.7 0 01-2.4-2.4L14.5 7.6"/></svg>',send:'<svg class="flip" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M3.4 20.4l17.5-7.5a1 1 0 000-1.8L3.4 3.6a1 1 0 00-1.4 1.2L4.5 12l-2.5 7.2a1 1 0 001.4 1.2zM4.5 12h7"/></svg>',file:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M14 3H6v18h12V7z M14 3v4h4"/></svg>'};function el(tag,className,text){let element=document.createElement(tag);if(className)element.className=className;if(text!==void 0)element.textContent=text;return element}function iconButton(icon,label,onClick,className="icon"){let button=el("button",className);return button.type="button",button.innerHTML=icon,button.setAttribute("aria-label",label),button.title=label,button.addEventListener("click",onClick),button}var time=(value)=>Date.parse(value),byCreated=(a,b)=>time(a.created_at)-time(b.created_at),byActivity=(a,b)=>time(b.last_message_at??b.created_at)-time(a.last_message_at??a.created_at),authorKey=(m)=>m.author.type==="contact"?"contact":`${m.author.type}:${m.author.name??""}`,isImage=(a)=>/^image\/(png|jpeg|gif|webp)$/.test(a.content_type);class Chat{#host;#i18n;#client;#inbox=null;#contact=null;#phase="loading";#error="";#starting=null;#beginning=null;#conversations=new Map;#conversationCursor;#threads=new Map;#pending=[];#typing=new Map;#view=null;#reconnecting=!1;#files=[];#typingSentAt=0;#typingIdle=null;#blobs=new Map;#blobLoads=new Map;#avatars=new Map;#emailSaved=!1;#emailError="";#connectedBefore=!1;#ratings=new Map;#rateCard=el("div","card rate");#rateComment=el("textarea");#rateKey="";#rateFor=null;#header=el("header","header");#banner=el("div","banner");#body=el("div","body");#scroll=el("div","scroll");#email=el("div","card");#emailInput=el("input");#composer=el("div","composer");#chips=el("div","chips");#textarea=el("textarea");#fileInput=el("input");#sendButton;#attachButton;#live=el("div","sr");#scrollThread;#atEnd=!0;constructor(host){this.#host=host;let{server,channel}=host.config();this.#client=createYuvaClient2({server,channel:channel??"",identityToken:()=>host.identityToken()}),this.#client.on("event",(message)=>this.#event(message)),this.#client.on("connection",({state,attempt})=>{if(state!=="reconnecting")return;this.#reconnecting=attempt>0,this.#renderBanner()}),this.#client.on("session",({session,renewed})=>{if(this.#setInbox(session.inbox),this.#contact=session.contact,renewed)this.#reload()}),this.#setLocale(),this.#live.setAttribute("aria-live","polite"),this.#scroll.addEventListener("scroll",()=>{if(this.#atEnd=this.#scroll.scrollHeight-this.#scroll.scrollTop-this.#scroll.clientHeight<48,this.#scroll.scrollTop<60&&this.#view?.kind==="thread"&&this.#view.id)this.#loadMessages(this.#view.id,!0)}),this.#textarea.rows=1,this.#textarea.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&!event.shiftKey&&!event.isComposing)event.preventDefault(),this.#send()}),this.#textarea.addEventListener("input",()=>{this.#autosize(),this.#syncSend(),this.#typingInput()}),this.#textarea.addEventListener("paste",(event)=>{let files=Array.from(event.clipboardData?.files??[]);if(files.length===0)return;event.preventDefault(),this.#addFiles(files)}),this.#fileInput.type="file",this.#fileInput.multiple=!0,this.#fileInput.hidden=!0,this.#fileInput.addEventListener("change",()=>{this.#addFiles(Array.from(this.#fileInput.files??[])),this.#fileInput.value=""}),this.#attachButton=iconButton(icons.attach,"",()=>this.#fileInput.click()),this.#sendButton=iconButton(icons.send,"",()=>void this.#send(),"icon send");let form=el("form");form.addEventListener("submit",(event)=>{event.preventDefault(),this.#send()}),form.append(this.#attachButton,this.#textarea,this.#sendButton,this.#fileInput),this.#composer.append(this.#chips,form),this.#emailInput.type="email",this.#emailInput.required=!0,this.#emailInput.autocomplete="email",this.#rateComment.rows=2,this.#rateComment.maxLength=2000,this.#rateComment.dir="auto",document.addEventListener("visibilitychange",this.#onVisible),window.addEventListener("online",this.#onVisible),this.#renderAll(),this.#start()}update(){this.#setLocale(),this.#renderAll()}opened(){if(this.#phase==="error"){this.#starting=null,this.#start();return}if(this.#phase==="ready")this.#client.token?this.#refreshSession():this.#preview().then(()=>this.#render()).catch(()=>{return});if(this.#render(),this.#scrollToEnd(),this.#markRead(),this.#host.config().layout==="launcher")this.#textarea.focus({preventScroll:!0})}closed(){this.#stopTyping()}identityChanged(){this.#reset(),this.#start()}async signOut(){let signingOut=this.#client.signOut();if(this.#reset(),await signingOut,this.#host.isOpen())this.#start();else this.#render()}destroy(){this.#client.reset(),this.#stopTyping(),document.removeEventListener("visibilitychange",this.#onVisible),window.removeEventListener("online",this.#onVisible);for(let url of this.#blobs.values())URL.revokeObjectURL(url)}#reset(){this.#client.reset(),this.#starting=null,this.#beginning=null,this.#inbox=null,this.#contact=null,this.#phase="loading",this.#conversations.clear(),this.#threads.clear(),this.#pending=[],this.#ratings.clear(),this.#rateKey="",this.#view=null,this.#connectedBefore=!1,this.#host.setUnread(0)}#onVisible=()=>{if(document.visibilityState!=="visible")return;this.#client.reconnect(),this.#markRead(),this.#refreshInbox()};#setLocale(){let{locale}=this.#host.config();this.#i18n=setupI18n({locale,messages:{[locale]:catalogs[locale]??messages}})}#t(descriptor){return this.#i18n._(descriptor)}#start(){return this.#starting??=(async()=>{this.#phase="loading",this.#render();let{channel}=this.#host.config();if(!channel)throw new ApiError2(0,"not_configured");if(await this.#host.identityToken()||readStored(channel).session)await this.#begin();else if(await this.#preview(),!this.#inbox?.chat.allow_anonymous)throw new ApiError2(403,"anonymous_not_allowed");if(this.#phase="ready",!this.#view){let list=this.#sorted();if(this.#view=list.length>1?{kind:"list"}:{kind:"thread",id:list[0]?.id??null},this.#view.kind==="thread"&&this.#view.id)await this.#loadMessages(this.#view.id)}this.#render(),this.#scrollToEnd(),this.#markRead()})().catch((error)=>{if(this.#starting=null,this.#refusal(error))return;this.#phase="error",this.#error=error instanceof ApiError2?error.code:"error",this.#render()}),this.#starting}async#preview(){let inbox=await this.#fetchInbox();if(!this.#client.token)this.#setInbox(inbox)}#fetchInbox(){if(!this.#host.config().channel)throw new ApiError2(0,"not_configured");return this.#client.channelSettings()}#setInbox(inbox){let{channel}=this.#host.config();this.#inbox=inbox;let launcher=launcherOf(inbox);if(this.#host.setLauncher(launcher),channel)writeStored(channel,{...readStored(channel),launcher})}async#refreshInbox(){if(this.#phase!=="ready")return;try{this.#setInbox(await this.#fetchInbox()),this.#render()}catch(error){this.#refusal(error,!0)}}#refusal(error,channelRequest=!this.#client.token){let refused=error instanceof ApiError2&&(error.code==="origin_not_allowed"||error.status===404&&channelRequest);if(refused)this.#host.refused();return refused}#begin(){return this.#beginning??=(async()=>{await this.#client.start(),await this.#loadConversations(),await this.#client.connect()})().finally(()=>{this.#beginning=null}),this.#beginning}async#refreshSession(){try{await this.#client.refresh(),this.#render()}catch{}}async#loadConversations(more=!1){let page=await this.#client.listConversations({limit:50,cursor:more?this.#conversationCursor:void 0});if(!more)this.#conversations.clear();for(let conversation of page.items)this.#conversations.set(conversation.id,conversation);this.#conversationCursor=page.next_cursor,this.#syncUnread()}async#reload(){await this.#loadConversations();let current=this.#view?.kind==="thread"?this.#view.id:null;for(let id of this.#threads.keys())if(id!==current)this.#threads.delete(id);if(current)this.#threads.delete(current),await this.#loadMessages(current);this.#render()}async#loadMessages(id,older=!1){let thread=this.#threads.get(id);if(!thread)thread={messages:[],complete:!1,loading:!1},this.#threads.set(id,thread);if(thread.loading||older&&(thread.complete||!thread.cursor))return;thread.loading=!0;let before=this.#scroll.scrollHeight-this.#scroll.scrollTop;try{let page=await this.#client.listMessages(id,{order:"desc",limit:30,cursor:older?thread.cursor:void 0}),known=new Set(thread.messages.map((m)=>m.id));thread.messages=[...thread.messages,...page.items.filter((m)=>!known.has(m.id))].sort(byCreated),thread.cursor=page.next_cursor,thread.complete=!page.next_cursor}finally{thread.loading=!1}if(older)this.#render(),this.#scroll.scrollTop=this.#scroll.scrollHeight-before}#event(message){switch(message.type){case"ready":if(this.#reconnecting=!1,this.#renderBanner(),this.#connectedBefore)this.#refreshInbox();this.#connectedBefore=!0;return;case"inbox.updated":{let asked=this.#inbox?.ask_for_rating;if(this.#setInbox(message.data),asked!==void 0&&asked!==message.data.ask_for_rating)this.#loadConversations().then(()=>this.#render()).catch(()=>{return});break}case"resync_required":this.#reload();return;case"presence":if(this.#inbox)this.#inbox={...this.#inbox,presence:message.data};break;case"conversation.created":if(!this.#conversations.has(message.data.id))this.#conversations.set(message.data.id,message.data);if(this.#view?.kind==="thread"&&this.#view.id===null&&this.#conversations.size>1)this.#view=this.#pending.some((p)=>p.conversation===null)?this.#view:{kind:"list"};this.#syncUnread();break;case"conversation.updated":{let conversation=this.#conversations.get(message.data.id),{status,can_rate,rating}=message.data;if(conversation)this.#conversations.set(conversation.id,{...conversation,status,can_rate,rating});if(!can_rate)this.#ratings.delete(message.data.id);break}case"message.created":case"message.updated":this.#upsertMessage(message.data,message.type==="message.created");break;case"read":{let conversation=this.#conversations.get(message.data.conversation_id),previous=conversation?.last_read_by_member_at;if(conversation&&(!previous||time(message.data.read_at)>time(previous)))this.#conversations.set(conversation.id,{...conversation,last_read_by_member_at:message.data.read_at});break}case"typing":{let id=message.data.conversation_id,previous=this.#typing.get(id);if(previous)clearTimeout(previous.timer);if(message.data.typing){let name=message.data.author.name??"";this.#typing.set(id,{name,timer:setTimeout(()=>this.#typing.delete(id)&&this.#render(),8000)})}else this.#typing.delete(id);break}}this.#render()}#upsertMessage(message,created){let id=message.conversation_id,thread=this.#threads.get(id);if(thread){let index=thread.messages.findIndex((m)=>m.id===message.id);if(index>=0)thread.messages[index]=message;else thread.messages=[...thread.messages,message].sort(byCreated)}if(message.client_id)this.#pending=this.#pending.filter((p)=>p.client_id!==message.client_id);let conversation=this.#conversations.get(id);if(!conversation){this.#client.getConversation(id).then((c)=>{this.#conversations.set(c.id,c),this.#syncUnread(),this.#render()}).catch(()=>{return});return}if(created){let text=message.body.replace(/\s+/g," ").trim();if(this.#conversations.set(id,{...conversation,last_message:{id:message.id,author_type:message.author.type,text:text.length>140?`${text.slice(0,139)}…`:text,created_at:message.created_at},last_message_at:message.created_at,unread:conversation.unread||message.author.type!=="contact"}),message.author.type!=="contact"){let typing=this.#typing.get(id);if(typing)clearTimeout(typing.timer);this.#typing.delete(id),this.#announce(message)}}this.#syncUnread(),this.#markRead()}#announce(message){this.#live.textContent=`${message.author.name||this.#inbox?.name||""}: ${message.body.slice(0,200)}`}#syncUnread(){let count=0;for(let conversation of this.#conversations.values())if(conversation.unread)count++;this.#host.setUnread(count)}#visibleThread(){if(!this.#host.isOpen()||document.visibilityState!=="visible")return null;return this.#view?.kind==="thread"?this.#view.id:null}#markRead(){let id=this.#visibleThread(),conversation=id?this.#conversations.get(id):void 0;if(!id||!conversation?.unread)return;this.#conversations.set(id,{...conversation,unread:!1}),this.#syncUnread(),this.#client.markRead(id).catch(()=>{let current=this.#conversations.get(id);if(current)this.#conversations.set(id,{...current,unread:!0});this.#syncUnread()})}#addFiles(files){this.#files=[...this.#files,...files].slice(0,maxFiles),this.#renderChips(),this.#syncSend(),this.#textarea.focus()}#autosize(){if(this.#textarea.style.blockSize="",this.#textarea.value==="")return;this.#textarea.style.blockSize="auto",this.#textarea.style.blockSize=`${Math.max(38,Math.min(this.#textarea.scrollHeight,140))}px`}#syncSend(){this.#sendButton.disabled=this.#textarea.value.trim()===""&&this.#files.length===0}#typingInput(){let id=this.#view?.kind==="thread"?this.#view.id:null;if(!id||this.#textarea.value.trim()===""){this.#stopTyping();return}if(Date.now()-this.#typingSentAt>3000)this.#typingSentAt=Date.now(),this.#client.setTyping(id,!0).catch(()=>{return});if(this.#typingIdle)clearTimeout(this.#typingIdle);this.#typingIdle=setTimeout(()=>this.#stopTyping(),4000)}#stopTyping(){if(this.#typingIdle)clearTimeout(this.#typingIdle);if(this.#typingIdle=null,this.#typingSentAt===0)return;this.#typingSentAt=0;let id=this.#view?.kind==="thread"?this.#view.id:null;if(id)this.#client.setTyping(id,!1).catch(()=>{return})}async#send(){if(this.#phase!=="ready"||this.#view?.kind!=="thread")return;let body=this.#textarea.value.trim(),files=this.#files;if(!body&&files.length===0)return;if(this.#view.id===null&&this.#pending.some((p)=>p.conversation===null))return;this.#stopTyping(),this.#textarea.value="",this.#files=[],this.#autosize(),this.#renderChips(),this.#syncSend();let pending={client_id:randomId2(),conversation:this.#view.id,body,files,state:"sending"};this.#pending.push(pending),this.#render(),this.#scrollToEnd(),await this.#deliver(pending)}async#deliver(pending){pending.state="sending",this.#render();let input={body:pending.body,files:pending.files,client_id:pending.client_id};try{if(pending.conversation===null){let created=await this.#client.startConversation(input),id=created.conversation.id;if(!this.#conversations.has(id))this.#conversations.set(id,created.conversation);if(!this.#threads.has(id))this.#threads.set(id,{messages:[],complete:!0,loading:!1});if(this.#view?.kind==="thread"&&this.#view.id===null)this.#view={kind:"thread",id};this.#upsertMessage(created.message,!1)}else{let message=await this.#client.sendMessage(pending.conversation,input);this.#upsertMessage(message,!0)}this.#pending=this.#pending.filter((p)=>p!==pending)}catch(error){let status=error instanceof ApiError2?error.status:0;pending.state=status===413||status===415?"refused":"failed",pending.status=status}this.#render(),this.#scrollToEnd()}async rate(id,rating,comment){try{let conversation=await this.#client.rate(id,rating,comment);return this.#conversations.set(conversation.id,conversation),this.#ratings.delete(id),this.#render(),conversation}catch(error){if(error instanceof ApiError2&&error.status===409){let current=await this.#client.getConversation(id).catch(()=>null);if(current)this.#conversations.set(current.id,current);this.#ratings.delete(id),this.#render()}throw error}}#choose(id,choice){if(this.#ratings.get(id)?.state==="sending")return;if(this.#ratings.set(id,{choice,state:"choosing"}),this.#render(),this.#rateComment.focus({preventScroll:!0}),this.#atEnd)this.#scrollToEnd()}async#submitRating(id,withComment){let draft=this.#ratings.get(id);if(!draft||draft.state==="sending")return;draft.state="sending",this.#render();try{await this.rate(id,draft.choice,withComment?this.#rateComment.value:void 0),this.#rateComment.value=""}catch(error){if(error instanceof ApiError2&&error.status===409)return;draft.state="failed",this.#render()}}async#saveEmail(){let email=this.#emailInput.value.trim();if(!email||!this.#emailInput.checkValidity()){this.#emailError=this.#t({id:"E_qvzP"}),this.#renderEmail();return}try{this.#contact=await this.#client.setEmail(email),this.#emailSaved=!0,this.#emailError=""}catch{this.#emailError=this.#t({id:"ZxJcgC"})}this.#renderEmail()}#attachmentUrl(attachment){let cached=this.#blobs.get(attachment.id);if(cached)return Promise.resolve(cached);let load=this.#blobLoads.get(attachment.id);if(!load)load=this.#client.attachment(attachment.id).then((blob)=>{let url=URL.createObjectURL(blob);return this.#blobs.set(attachment.id,url),url}),load.catch(()=>this.#blobLoads.delete(attachment.id)),this.#blobLoads.set(attachment.id,load);return load}async#download(attachment){let url=await this.#attachmentUrl(attachment),a=el("a");a.href=url,a.download=attachment.filename,a.rel="noopener",a.click()}#sorted(){return[...this.#conversations.values()].sort(byActivity)}#nobodyAvailable(){let inbox=this.#inbox;if(!inbox)return!1;return!inbox.open_now||inbox.mode==="async"||!inbox.presence?.available}#scrollToEnd(){this.#atEnd=!0,this.#scroll.scrollTop=this.#scroll.scrollHeight,requestAnimationFrame(()=>{if(this.#atEnd)this.#scroll.scrollTop=this.#scroll.scrollHeight})}#renderAll(){this.#textarea.placeholder=this.#t({id:"RzWUUK"}),this.#textarea.setAttribute("aria-label",this.#t({id:"xDAtGP"})),this.#attachButton.setAttribute("aria-label",this.#t({id:"N7m8E-"})),this.#attachButton.title=this.#t({id:"N7m8E-"}),this.#sendButton.setAttribute("aria-label",this.#t({id:"JlFcis"})),this.#sendButton.title=this.#t({id:"JlFcis"}),this.#emailInput.placeholder=this.#t({id:"njBr8W"}),this.#emailInput.setAttribute("aria-label",this.#t({id:"XJURKP"})),this.#syncSend(),this.#renderChips(),this.#render()}#render(){let panel=this.#host.panel;if(panel.childElementCount===0){let style=el("style");style.textContent=styles,panel.append(style,this.#header,this.#banner,this.#body,this.#live),this.#header.id="yuva-title",panel.setAttribute("aria-labelledby","yuva-title")}if(this.#renderHeader(),this.#renderBanner(),this.#phase!=="ready"){this.#scrollThread=void 0;let center=el("div","center");if(this.#phase==="loading")center.append(el("p","hint",this.#t({id:"Pwqkdw"})));else{center.append(el("p","empty",this.#errorText()));let retry=el("button","primary",this.#t({id:"KDw4GX"}));retry.type="button",retry.addEventListener("click",()=>{this.#starting=null,this.#start()}),center.append(retry)}this.#body.replaceChildren(center);return}if(this.#view?.kind==="list")this.#renderList();else this.#renderThread()}#errorText(){switch(this.#error){case"anonymous_not_allowed":return this.#t({id:"zLzEI3"});case"invalid_identity_token":return this.#t({id:"0XGLbP"});case"rate_limited":return this.#t({id:"tzsBOP"});case"network":return this.#t({id:"GQVIIl"});default:return this.#t({id:"Amai22"})}}#renderHeader(){let{layout}=this.#host.config(),inbox=this.#inbox,children=[],view=this.#view;if(this.#phase==="ready"&&view?.kind==="thread"&&(this.#conversations.size>1||view.id===null&&this.#conversations.size>0))children.push(iconButton(icons.back,this.#t({id:"S63MQu"}),()=>{this.#stopTyping(),this.#view={kind:"list"},this.#render()}));let heading=el("div","heading");if(heading.append(el("h2","title",inbox?.name||this.#t({id:"t7TeQU"}))),inbox){let status=el("div","status");if(inbox.mode==="live"&&inbox.open_now&&inbox.presence?.available){let avatars=el("div","avatars");for(let member of inbox.presence?.members.slice(0,3)??[]){let avatar=el("span","avatar",member.initials||"•");avatar.title=member.name,avatars.append(avatar)}status.append(avatars,el("span","dot"),el("span","",this.#t({id:"oXOSPE"})))}else if(!inbox.open_now||inbox.mode==="live")status.append(el("span","dot away"),el("span","",this.#t({id:"1EICzz"})));else status.append(el("span","",this.#replyTime(inbox.expected_reply_minutes)));heading.append(status)}if(children.push(heading),layout==="launcher")children.push(iconButton(icons.close,this.#t({id:"yz7wBu"}),()=>this.#host.close()));this.#header.replaceChildren(...children)}#replyTime(minutes){if(!minutes)return this.#t({id:"nhTADq"});let{locale}=this.#host.config(),[value,unit]=minutes<60?[minutes,"minute"]:minutes<1440?[Math.round(minutes/60),"hour"]:[Math.round(minutes/1440),"day"],duration=new Intl.NumberFormat(locale,{style:"unit",unit,unitDisplay:"long"}).format(value);return this.#t({id:"VggdQJ",values:{duration}})}#renderBanner(){this.#banner.hidden=!this.#reconnecting,this.#banner.textContent=this.#t({id:"09Tv5j"})}#renderList(){this.#scrollThread=void 0;let{locale}=this.#host.config(),list=el("ul","list"),today=new Date().toDateString();for(let conversation of this.#sorted()){let button=el("button",conversation.unread?"item unread":"item");button.type="button";let main=el("div","item-main"),top=el("div","item-top");top.append(el("span","item-subject",conversation.subject||this.#inbox?.name||this.#t({id:"YyNOE7"})));let at=new Date(conversation.last_message_at??conversation.created_at);top.append(el("span","item-time",new Intl.DateTimeFormat(locale,at.toDateString()===today?{timeStyle:"short"}:{month:"short",day:"numeric"}).format(at)));let preview=conversation.last_message?`${conversation.last_message.author_type==="contact"?this.#t({id:"ydzYKJ"})+" ":""}${conversation.last_message.text||this.#t({id:"UY1vmE"})}`:"",previewLine=el("div","item-preview",preview.replace(/\*\*|`/g,""));if(previewLine.dir="auto",main.append(top,previewLine),button.append(main),conversation.unread)button.append(el("span","unread-dot"));button.addEventListener("click",()=>void this.#openThread(conversation.id));let item=el("li");item.append(button),list.append(item)}if(this.#conversationCursor){let more=el("button","link",this.#t({id:"ASr-r0"}));more.type="button",more.style.margin="8px auto",more.style.display="block",more.addEventListener("click",()=>void this.#loadConversations(!0).then(()=>this.#render())),list.append(more)}let start=el("button","primary",this.#t({id:"-HY5kX"}));start.type="button",start.addEventListener("click",()=>{this.#view={kind:"thread",id:null},this.#render(),this.#textarea.focus()}),this.#body.replaceChildren(list,start)}async#openThread(id){if(this.#view={kind:"thread",id},this.#render(),!this.#threads.get(id)?.complete&&!this.#threads.get(id)?.messages.length)await this.#loadMessages(id).catch(()=>{return});this.#render(),this.#scrollToEnd(),this.#markRead()}#avatar(author){let avatar=el("span","avatar",author.initials||""),url=author.avatar_url,state=url?this.#avatars.get(url):!1;if(!url||state===!1)return avatar;let img=el("img");if(img.alt="",img.referrerPolicy="no-referrer",state)return img.src=url,avatar.replaceChildren(img),avatar;return img.addEventListener("load",()=>{if(this.#avatars.set(url,!0),avatar.isConnected)avatar.replaceChildren(img)}),img.addEventListener("error",()=>this.#avatars.set(url,!1)),img.src=url,avatar}#renderThread(){let view=this.#view;if(view?.kind!=="thread")return;let id=view.id,sameThread=this.#scrollThread===id,atEnd=this.#atEnd,thread=id?this.#threads.get(id):void 0,messages=thread?.messages??[],pending=this.#pending.filter((p)=>p.conversation===id),nodes=[],greeting=this.#inbox?.chat.greeting;if(!thread||thread.complete){if(greeting){let bubble=el("div","bubble greeting");bubble.append(richText(greeting)),nodes.push(bubble)}else if(messages.length===0&&pending.length===0){let center=el("div","center");center.append(el("p","empty",this.#t({id:"meAa31"})),el("p","hint",this.#t({id:"SdV5Cn"}))),nodes.push(center)}}else if(thread.loading)nodes.push(el("p","hint",this.#t({id:"Pwqkdw"})));messages.forEach((message,i)=>{let previous=messages[i-1],next=messages[i+1]??(pending.length>0?null:void 0),mine=message.author.type==="contact",starts=!previous||authorKey(previous)!==authorKey(message)||time(message.created_at)-time(previous.created_at)>groupGap,ends=next===void 0||(next===null?!mine:authorKey(next)!==authorKey(message)||time(next.created_at)-time(message.created_at)>groupGap);if(!mine&&starts&&message.author.name)nodes.push(el("div","author",message.author.name));let row=el("div",`row ${mine?"mine":"theirs"}${starts&&i>0?" group-gap":""}`);if(!mine){let avatar=this.#avatar(message.author);if(!ends)avatar.style.visibility="hidden";row.append(avatar)}let bubble=el("div","bubble");if(bubble.dir="auto",bubble.title=new Date(message.created_at).toLocaleString(this.#host.config().locale),message.body.trim())bubble.append(richText(message.body));if(message.attachments.length>0)bubble.append(this.#renderAttachments(message.attachments));if(row.append(bubble),nodes.push(row),ends){let meta=this.#formatTime(message.created_at);if(mine&&i===messages.length-1&&pending.length===0){let readAt=id?this.#conversations.get(id)?.last_read_by_member_at:void 0,seen=readAt&&time(readAt)>=time(message.created_at);meta+=` · ${seen?this.#t({id:"6lGaum"}):this.#t({id:"h69WC6"})}`}let line=el("div","meta",meta);if(!mine)line.style.alignSelf="flex-start";if(!mine)line.style.marginInlineStart="36px";nodes.push(line)}});let conversation=id?this.#conversations.get(id):void 0,rate=conversation?this.#renderRating(conversation):null;if(rate)nodes.push(rate);pending.forEach((item,i)=>{let row=el("div",`row mine${i===0&&messages.length>0&&messages[messages.length-1]?.author.type!=="contact"?" group-gap":""}`),bubble=el("div","bubble");if(bubble.dir="auto",item.body)bubble.append(richText(item.body));if(item.files.length>0){let files=el("div","files");for(let file of item.files)files.append(el("span","file",file.name||"image"));bubble.append(files)}if(row.append(bubble),nodes.push(row),item.state==="failed"){let line=el("div","meta failed",`${this.#t({id:"upFvcp"})} `),retry=el("button","link",this.#t({id:"6gRgw8"}));retry.type="button",retry.addEventListener("click",()=>void this.#deliver(item)),line.append(retry),nodes.push(line)}else if(item.state==="refused"){let reason=item.status===413?this.#t({id:"eOu9Px"}):this.#t({id:"JkW3Ph"});nodes.push(el("div","meta failed",`${this.#t({id:"upFvcp"})} ${reason}`))}else if(i===pending.length-1)nodes.push(el("div","meta",this.#t({id:"Sad2tK"})))});let typing=id?this.#typing.get(id):void 0;if(typing){let line=el("div","typing");line.append(el("i"),el("i"),el("i"));let name=typing.name;line.append(el("span","",name?this.#t({id:"tHaDPf",values:{name}}):this.#t({id:"PxYAul"}))),nodes.push(line)}let focused=this.#scroll.getRootNode().activeElement===this.#rateComment,{selectionStart,selectionEnd}=this.#rateComment;if(this.#scroll.replaceChildren(...nodes),focused&&this.#rateComment.isConnected)this.#rateComment.focus({preventScroll:!0}),this.#rateComment.setSelectionRange(selectionStart,selectionEnd);if(this.#renderEmail(),this.#body.firstChild!==this.#scroll)this.#body.replaceChildren(this.#scroll,this.#email,this.#composer);if(this.#scrollThread=id,!sameThread||atEnd)this.#scrollToEnd()}#renderRating(conversation){let rated=conversation.status==="closed"?conversation.rating:void 0,draft=conversation.can_rate&&this.#inbox?.ask_for_rating?this.#ratings.get(conversation.id):void 0;if(!rated&&!(conversation.can_rate&&this.#inbox?.ask_for_rating))return null;let card=this.#rateCard,key=[conversation.id,rated,draft?.choice,draft?.state,this.#host.config().locale].join(":");if(key===this.#rateKey)return card;if(this.#rateKey=key,this.#rateFor!==conversation.id)this.#rateFor=conversation.id,this.#rateComment.value="";let question=this.#t({id:"uA8iBc"});card.setAttribute("role","group"),card.setAttribute("aria-label",question);let choices=el("div","choices");for(let value of["good","bad"]){if(rated&&rated!==value)continue;let button=el("button","choice",value==="good"?"\uD83D\uDC4D":"\uD83D\uDC4E");button.type="button";let label=value==="good"?this.#t({id:"OEEQKT"}):this.#t({id:"-f5Tkb"});button.setAttribute("aria-label",label),button.title=label,button.setAttribute("aria-pressed",String((rated??draft?.choice)===value)),button.disabled=!!rated||draft?.state==="sending",button.addEventListener("click",()=>this.#choose(conversation.id,value)),choices.append(button)}if(rated)return card.replaceChildren(choices,el("p","",this.#t({id:"SOk0EB"}))),card;if(card.replaceChildren(el("p","",question),choices),!draft)return card;this.#rateComment.placeholder=this.#t({id:"axQ1h6"}),this.#rateComment.setAttribute("aria-label",this.#t({id:"NBdIgR"})),this.#rateComment.disabled=draft.state==="sending";let form=el("form");form.addEventListener("submit",(event)=>{event.preventDefault(),this.#submitRating(conversation.id,!0)});let skip=el("button","link",this.#t({id:"6Uau97"}));skip.type="button",skip.disabled=draft.state==="sending",skip.addEventListener("click",()=>void this.#submitRating(conversation.id,!1));let send=el("button","",draft.state==="sending"?this.#t({id:"Sad2tK"}):this.#t({id:"JlFcis"}));send.type="submit",send.disabled=draft.state==="sending";let actions=el("div","actions");if(actions.append(skip,send),form.append(this.#rateComment,actions),card.append(form),draft.state==="failed")card.append(el("p","error",this.#t({id:"4TqZiz"})));return card}#renderAttachments(attachments){let files=el("div","files");for(let attachment of attachments)if(isImage(attachment)){let img=el("img");img.alt=attachment.filename;let cached=this.#blobs.get(attachment.id);if(cached)img.src=cached;else this.#attachmentUrl(attachment).then((url)=>{img.src=url}).catch(()=>{return});img.addEventListener("load",()=>{if(this.#atEnd)this.#scroll.scrollTop=this.#scroll.scrollHeight}),img.addEventListener("click",()=>void this.#download(attachment)),files.append(img)}else{let button=el("button","file");button.type="button",button.innerHTML=icons.file,button.append(el("span","",attachment.filename)),button.addEventListener("click",()=>void this.#download(attachment)),files.append(button)}return files}#formatTime(value){return new Intl.DateTimeFormat(this.#host.config().locale,{timeStyle:"short"}).format(new Date(value))}#renderEmail(){let contact=this.#contact,chat=this.#inbox?.chat,sent=(this.#view?.kind==="thread"?this.#view.id:null)!==null||this.#pending.length>0,known=contact?.email||contact?.typed_email,show=!!chat?.ask_email_offline&&this.#nobodyAvailable()&&sent&&(!known||this.#emailSaved);if(this.#email.hidden=!show,!show)return;if(known&&this.#emailSaved){this.#email.replaceChildren(el("p","",this.#t({id:"iGNUZJ",values:{known}})));return}if(this.#email.querySelector("form")){let error=this.#email.querySelector(".error");if(error)error.textContent=this.#emailError;else if(this.#emailError)this.#email.append(el("p","error",this.#emailError));return}let form=el("form");form.noValidate=!0,form.addEventListener("submit",(event)=>{event.preventDefault(),this.#saveEmail()});let save=el("button","",this.#t({id:"tfDRzk"}));if(save.type="submit",form.append(this.#emailInput,save),this.#email.replaceChildren(el("p","",this.#t({id:"M62PBt"})),form),this.#emailError)this.#email.append(el("p","error",this.#emailError))}#renderChips(){this.#chips.hidden=this.#files.length===0,this.#chips.replaceChildren(...this.#files.map((file,index)=>{let chip=el("span","chip");return chip.append(el("span","",file.name||"image"),iconButton(icons.close,this.#t({id:"w61W3L",values:{0:file.name}}),()=>{this.#files=this.#files.filter((_,i)=>i!==index),this.#renderChips(),this.#syncSend()})),chip}))}}function mount(host){return new Chat(host)}export{mount};