useyuva 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +89 -1
  2. package/dist/esm/chat.js +2 -2
  3. package/dist/esm/docs.js +134 -0
  4. package/dist/esm/index-dj5dhqc1.js +12 -0
  5. package/dist/esm/index-e2tek7yk.js +2 -0
  6. package/dist/esm/index-jdxce2se.js +4 -0
  7. package/dist/esm/index-rdzxvj2r.js +2 -0
  8. package/dist/esm/index.js +1 -1
  9. package/dist/esm/nuxt/module.js +20 -0
  10. package/dist/esm/nuxt/runtime/components.js +88 -0
  11. package/dist/esm/react.js +1 -1
  12. package/dist/esm/thread-3ydc3xfc.js +61 -0
  13. package/dist/esm/{yuva-chat-tebg111a.js → yuva-chat-86e4mz63.js} +2 -4
  14. package/dist/types/client/api.d.ts +17 -0
  15. package/dist/types/client/client.d.ts +23 -1
  16. package/dist/types/client/reader.d.ts +12 -0
  17. package/dist/types/docs/base.d.ts +43 -0
  18. package/dist/types/docs/define.d.ts +1 -0
  19. package/dist/types/docs/discussions.d.ts +22 -0
  20. package/dist/types/docs/dom.d.ts +1 -0
  21. package/dist/types/docs/feedback.d.ts +21 -0
  22. package/dist/types/docs/page.d.ts +2 -0
  23. package/dist/types/docs/preview.d.ts +1 -0
  24. package/dist/types/docs/thread.d.ts +71 -0
  25. package/dist/types/docs.d.ts +7 -0
  26. package/dist/types/element.d.ts +0 -1
  27. package/dist/types/i18n.d.ts +1 -1
  28. package/dist/types/index.d.ts +3 -2
  29. package/dist/types/locales/en/docs.d.ts +2 -0
  30. package/dist/types/locales/en/thread.d.ts +2 -0
  31. package/dist/types/locales/tr/docs.d.ts +2 -0
  32. package/dist/types/locales/tr/thread.d.ts +2 -0
  33. package/dist/types/nuxt/module.d.ts +12 -0
  34. package/dist/types/nuxt/runtime/components.d.ts +88 -0
  35. package/dist/types/react.d.ts +26 -2
  36. package/dist/types/schema.gen.d.ts +6638 -3874
  37. package/dist/types/translate.d.ts +2 -0
  38. package/dist/types/types.d.ts +1 -0
  39. package/dist/widget/yuva-docs-thread-4580g2ny.js +61 -0
  40. package/dist/yuva-chat.js +8 -8
  41. package/dist/yuva-docs.js +144 -0
  42. package/dist/yuva.js +2 -2
  43. package/package.json +39 -8
  44. package/dist/esm/index-d1vxbqpr.js +0 -12
  45. package/dist/esm/index-r5vcg0sx.js +0 -2
@@ -0,0 +1,144 @@
1
+ (()=>{class d extends Error{status;code;constructor(e,t){super(`${e} ${t}`);this.status=e;this.code=t}}async function U(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()}class E{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 ne(e,t,i){let s=new URL("/account/connect",e);return s.searchParams.set("channel",t),s.searchParams.set("origin",i),s.href}function re(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 L(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(ne(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(!re(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 O(e){return`yuva:${e}`}function z(e,t){return`yuva:reader:${e} ${t}`}function W(){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 oe(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 ae(){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 D(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 le(e){return e.replace(/"/g,"%22").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function ce(e,t,i){let s=[];for(let[n,o]of e)s.push(`--${i}\r
2
+ Content-Disposition: form-data; name="${n}"\r
3
+ \r
4
+ ${o}\r
5
+ `);for(let n of t){let o=n.name||"file";s.push(`--${i}\r
6
+ Content-Disposition: form-data; name="files"; filename="${le(o)}"\r
7
+ Content-Type: ${n.type||"application/octet-stream"}\r
8
+ \r
9
+ `,n,`\r
10
+ `)}return s.push(`--${i}--\r
11
+ `),new Blob(s)}class q{server;channel;#e;#i;#n;#t;#r;#o=null;#s=null;#h=null;#g=null;#l=null;#c;#p=new Map;constructor(e){this.server=e.server.replace(/\/+$/,""),this.channel=e.channel,this.#e=e.fetch??((t,i)=>fetch(t,i)),this.#i=e.WebSocket??globalThis.WebSocket,this.#n=e.storage??ae(),this.#t=e.identityToken??null,this.#r=e.idempotencyKeys??typeof globalThis.document>"u"}get session(){return this.#s}get token(){return this.#o}get connected(){return this.#l?.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)}#d(e,t){for(let i of this.#p.get(e)??[])i(t)}stored(){try{let e=this.#n.getItem(O(this.channel));return e?JSON.parse(e):{}}catch{return{}}}#x(e){try{this.#n.setItem(O(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})}setIdentityToken(e){this.#t=e,this.reset()}start(){if(this.#s)return Promise.resolve(this.#s);return this.#h??=this.#S(!1).then((e)=>(this.#d("session",{session:e,renewed:!1}),e)).finally(()=>{this.#h=null}),this.#h}async refresh(){let e=await this.#a("/client/v1/session");return this.#s={...this.#s,...e},this.#d("session",{session:this.#s,renewed:!1}),this.#s}reset(){this.#l?.stop(),this.#l?.reset(),this.#h=null,this.#g=null,this.#o=null,this.#s=null}async signOut(){let e=this.#o;this.reset();let t=this.stored();if(delete t.session,this.#x(t),e)await this.#f("/client/v1/session",{method:"DELETE",token:e}).catch(()=>{return})}async connect(){if(!this.#i)throw Error("Yuva: no WebSocket in this runtime; pass options.WebSocket");if(await this.start(),this.#l??=new E(this.server,this.#i,{token:()=>this.#o,event:(e)=>{if(e.type==="ready")this.#d("connection",{state:"open",attempt:0});this.#d("event",e)},sessionEnded:()=>void this.#y().catch(()=>this.#l?.nudge()),reconnecting:(e)=>{if(this.#d("connection",{state:"reconnecting",attempt:e}),e===2)this.#a("/client/v1/session").catch(()=>{return})}}),!this.#l.connected)this.#d("connection",{state:"connecting",attempt:0});this.#l.start()}disconnect(){this.#l?.stop(),this.#d("connection",{state:"closed",attempt:0})}reconnect(){this.#l?.nudge()}listConversations(e={}){return this.#a(`/client/v1/conversations${D({...e})}`)}getConversation(e){return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}`)}startConversation(e){return this.#a("/client/v1/conversations",this.#C(e))}listMessages(e,t={}){return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}/messages${D({...t})}`)}sendMessage(e,t){return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}/messages`,this.#C(t))}markRead(e,t){return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}/read`,{method:"POST",json:t?{message_id:t}:{}})}rate(e,t,i){let s={rating:t,comment:i?.trim()||void 0};return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}/rating`,{method:"POST",json:s})}setTyping(e,t){return this.#a(`/client/v1/conversations/${encodeURIComponent(e)}/typing`,{method:"POST",json:{typing:t}})}setEmail(e){return this.#a("/client/v1/contact/email",{method:"PUT",json:{email:e}})}attachment(e){return this.#a(`/client/v1/attachments/${encodeURIComponent(e)}`,{blob:!0})}sendFeedback(e){let t=e.client_id??W();return this.#a("/client/v1/feedback",{method:"POST",headers:this.#w(t),json:{...e,client_id:t}})}get reader(){if(this.#c===void 0)try{let e=this.#n.getItem(z(this.server,this.channel));this.#c=e?JSON.parse(e):null}catch{this.#c=null}if(this.#c&&Date.parse(this.#c.expires_at)<=Date.now()+30000)this.#m(null);return this.#c}#m(e){let t=this.#c?.token!==e?.token;this.#c=e;try{this.#n.setItem(z(this.server,this.channel),e?JSON.stringify(e):"")}catch{}if(t)this.#d("reader",e)}readerSignIn(e){return L(this.server,this.channel,e).then((t)=>(this.#m(t),t))}setReader(e){this.#m(e)}async readerSignOut(){let e=this.reader?.token;if(this.#m(null),e)await this.#f("/client/v1/reader-token",{method:"DELETE",token:e}).catch(()=>{return})}listDiscussions(e,t={}){return this.#u(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions${D({page:e,...t})}`,{},!1)}getDiscussion(e){return this.#u(`/client/v1/channels/${encodeURIComponent(this.channel)}/discussions/${encodeURIComponent(e)}`,{},!1)}startDiscussion(e){return this.#u("/client/v1/discussions",{method:"POST",json:e})}replyToDiscussion(e,t){return this.#u(`/client/v1/discussions/${encodeURIComponent(e)}/posts`,{method:"POST",json:t})}editDiscussionPost(e,t){return this.#u(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"PATCH",json:t})}deleteDiscussionPost(e){return this.#u(`/client/v1/discussion-posts/${encodeURIComponent(e)}`,{method:"DELETE"})}voteDiscussionPost(e,t=!0){return this.#u(`/client/v1/discussion-posts/${encodeURIComponent(e)}/vote`,{method:t?"PUT":"DELETE"})}followDiscussion(e,t=!0){return this.#u(`/client/v1/discussions/${encodeURIComponent(e)}/follow`,{method:t?"PUT":"DELETE"})}acceptDiscussionAnswer(e,t){let i=`/client/v1/discussions/${encodeURIComponent(e)}/answer`;return this.#u(i,t?{method:"PUT",json:{post_id:t}}:{method:"DELETE"})}async discussionWriter(){if(this.reader)return"reader";if(this.#s)return this.#s.contact.identified?"contact":null;return await this.#t?.()?"contact":null}async#u(e,t,i=!0){let s=this.reader;if(s)try{return await this.#f(e,{...t,token:s.token})}catch(o){if(!(o instanceof d)||o.status!==401||this.#c?.token!==s.token)throw o;if(this.#m(null),i)throw new d(403,"sign_in_required")}if(await this.discussionWriter()==="contact")return this.#a(e,t);if(i)throw new d(403,"sign_in_required");return this.#f(e,t)}#w(e){return this.#r&&/^[\x20-\x7e]{1,255}$/.test(e)?{"Idempotency-Key":e}:{}}#C({body:e,subject:t,files:i=[],client_id:s=W()}){let n=this.#w(s);if(i.length===0)return{method:"POST",headers:n,json:{body:e,subject:t,client_id:s}};let o=[];if(t)o.push(["subject",t]);if(e)o.push(["body",e]);o.push(["client_id",s]);let r=`yuva-${s.replace(/[^\w-]/g,"").slice(0,60)}-${s.length}`;return n["Content-Type"]=`multipart/form-data; boundary=${r}`,{method:"POST",headers:n,body:ce(o,i,r)}}#f(e,t){return U(this.#e,this.server,e,t)}async#a(e,t={},i=!0){if(!this.#o)await this.start();try{return await this.#f(e,{...t,token:this.#o})}catch(s){if(!i||!(s instanceof d)||s.status!==401)throw s;return await this.#y(),this.#a(e,t,!1)}}#y(){return this.#g??=(async()=>{let e=await this.#S(!0);if(this.#l)this.#l.stop(),this.#l.reset(),this.#l.start();this.#d("session",{session:e,renewed:!0})})().finally(()=>{this.#g=null}),this.#g}async#S(e){let t=this.stored(),i=await this.#t?.()||null,s=i?oe(i):null,n=t.session;if(!e&&n&&n.sub===s&&Date.parse(n.expires_at)>Date.now()+60000)try{let c=await this.#f("/client/v1/session",{token:n.token});return this.#b(c,n.token,s)}catch(c){if(!(c instanceof d)||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:r,...l}=o;return this.#b(l,r,s)}#b(e,t,i){this.#o=t,this.#s=e;let s=this.stored();if(s.session={token:t,expires_at:e.expires_at,sub:i},e.visitor_id)s.visitor_id=e.visitor_id;else if(e.contact.identified)delete s.visitor_id;return this.#x(s),e}}function j(e){return new q(e)}var M=JSON.parse('{"6I7cJR":["Open chat"],"OkHvGB":["Open chat, ",["count"]," unread"],"pqZJT2":["Close chat"]}');var K=JSON.parse('{"6I7cJR":["Sohbeti aç"],"OkHvGB":["Sohbeti aç, ",["count"]," okunmamış"],"pqZJT2":["Sohbeti kapat"]}');function Y(e,t,i){let s=e[t.id]??i[t.id],n=t.values??{};if(typeof s==="string")return s;if(Array.isArray(s))return s.map((o)=>typeof o==="string"?o:Array.isArray(o)?String(n[o[0]]??""):"").join("");return t.message??t.id}var B={en:M,tr:K},de=new Set(["ar","fa","he","ur"]),he="en";function H(...e){for(let t of e){if(!t)continue;let i=t.toLowerCase();if(B[i])return i;let s=i.split(/[-_]/)[0]??"";if(B[s])return s}return he}function F(e){return de.has(e.split(/[-_]/)[0]??"")?"rtl":"ltr"}function N(e,t,i=M){return Y(e,t,i)}var w=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 G=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"]}');function J(e){return{position:e.chat.launcher_position,color:e.chat.launcher_color??e.branding.color}}function V(e){let t=Number.parseInt(e.slice(1),16),[i,s,n]=[t>>16&255,t>>8&255,t&255].map((o)=>{let r=o/255;return r<=0.03928?r/12.92:((r+0.055)/1.055)**2.4});return 0.2126*i+0.7152*s+0.0722*n>0.4?"#111827":"#ffffff"}function Q(e){return`yuva:${e}`}function I(e){try{let t=localStorage.getItem(Q(e));return t?JSON.parse(t):{}}catch{return{}}}function Z(e,t){try{localStorage.setItem(Q(e),JSON.stringify(t))}catch{}}function a(e,t,i){let s=document.createElement(e);if(t)s.className=t;if(i!==void 0)s.textContent=i;return s}var X=Symbol.for("yuva.navigation");function ue(){let e=window,t=e[X];if(t)return t;let i=new EventTarget;t=e[X]=i;let s=()=>i.dispatchEvent(new Event("change"));for(let n of["pushState","replaceState"]){let o=history[n];history[n]=function(...r){let l=o.apply(this,r);return s(),l}}return window.addEventListener("popstate",s),window.addEventListener("hashchange",s),t}function P(e){try{let t=new URL(e||location.href,location.href);return t.search="",t.hash="",t.href}catch{return e||location.href}}function ee(e){let t=ue(),i=!1,s=()=>{if(i)return;i=!0,queueMicrotask(()=>{i=!1,e()})};return t.addEventListener("change",s),()=>t.removeEventListener("change",s)}var pe={en:w,tr:G},_=new Map,fe=typeof HTMLElement>"u"?class{}:HTMLElement,T=typeof document<"u"&&document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"",ge=`
12
+ :host {
13
+ --yuva-accent: #2563eb;
14
+ --yuva-on-accent: #ffffff;
15
+ --yuva-border: rgb(127 127 127 / 0.35);
16
+ --yuva-soft: rgb(127 127 127 / 0.1);
17
+ --yuva-danger: #dc2626;
18
+ display: block;
19
+ color: inherit;
20
+ font: inherit;
21
+ line-height: 1.5;
22
+ }
23
+ :host([hidden]) { display: none; }
24
+ @media (prefers-color-scheme: dark) {
25
+ :host { --yuva-danger: #f87171; }
26
+ }
27
+ [hidden] { display: none !important; }
28
+ * { box-sizing: border-box; }
29
+ p { margin: 0; }
30
+ .muted { opacity: 0.72; font-size: 0.9em; }
31
+ .error { color: var(--yuva-danger); font-size: 0.9em; }
32
+ form { display: flex; flex-direction: column; gap: 8px; }
33
+ textarea, input {
34
+ inline-size: 100%;
35
+ padding: 8px 10px;
36
+ border: 1px solid var(--yuva-border);
37
+ border-radius: 8px;
38
+ background: transparent;
39
+ color: inherit;
40
+ font: inherit;
41
+ }
42
+ textarea { resize: vertical; min-block-size: 72px; }
43
+ textarea:focus-visible, input:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: -1px; border-color: transparent; }
44
+ .actions { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: flex-end; }
45
+ .send {
46
+ padding: 8px 14px;
47
+ border: 0;
48
+ border-radius: 8px;
49
+ background: var(--yuva-accent);
50
+ color: var(--yuva-on-accent);
51
+ font: inherit;
52
+ font-weight: 600;
53
+ cursor: pointer;
54
+ }
55
+ .send:disabled { opacity: 0.6; cursor: default; }
56
+ .send:focus-visible, .link:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
57
+ .link { padding: 0; border: 0; background: none; color: inherit; font: inherit; text-decoration: underline; cursor: pointer; opacity: 0.8; }
58
+ @media (max-width: 480px) { textarea, input { font-size: 16px; } }
59
+ `;class C extends fe{static observedAttributes=["channel","server","locale","dir","page","page-title","identity-token"];root;inbox=null;pageUrl="";refused=!1;direction="ltr";#e=w;#i=null;#n=null;#t=null;#r="";#o=!1;#s="";constructor(){super();this.root=this.attachShadow({mode:"open"})}get channel(){return this.getAttribute("channel")}set channel(e){this.#h("channel",e)}get server(){return(this.getAttribute("server")||(T?new URL(T).origin:location.origin)).replace(/\/+$/,"")}set server(e){this.#h("server",e)}get locale(){return H(this.getAttribute("locale"),navigator.language)}set locale(e){this.#h("locale",e)}get page(){return this.pageUrl||P(this.getAttribute("page"))}set page(e){this.#h("page",e)}get pageTitle(){return this.getAttribute("page-title")||document.title}set pageTitle(e){this.#h("page-title",e)}#h(e,t){if(t===null||t===void 0||t==="")this.removeAttribute(e);else this.setAttribute(e,t)}setIdentityToken(e){if(this.#n=e,this.#i?.setIdentityToken(()=>this.#g()),this.#o&&!this.refused)this.render()}connectedCallback(){this.#o=!0,this.#t??=ee(()=>this.#l()),this.pageUrl=P(this.getAttribute("page")),this.#c(),this.#p(),this.render(),this.pageChanged()}disconnectedCallback(){this.#o=!1,this.#t?.(),this.#t=null}attributeChangedCallback(e,t,i){if(!this.#o||t===i)return;if(e==="channel"||e==="server"){this.#i?.reset(),this.#i=null,this.refused=!1,this.inbox=null,this.#r="",this.#p(),this.reset(),this.render(),this.pageChanged();return}if(e==="page")return this.#l();if(e==="identity-token")this.#i?.setIdentityToken(()=>this.#g());if(e==="locale"||e==="dir")this.#c();this.render()}t(e){return N(this.#e,e,w)}client(){return this.#i??=j({server:this.server,channel:this.channel??"",identityToken:()=>this.#g()}),this.#i}get identified(){return!!this.#n||this.hasAttribute("identity-token")}get canWrite(){return this.identified||this.inbox?.chat.allow_anonymous!==!1}emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}refusal(e,t=!0){let i=e instanceof d&&(e.code==="origin_not_allowed"||e.code==="page_origin"||t&&e.status===404);if(i&&!this.refused)this.refused=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${this.pageUrl}`),this.root.replaceChildren();return i}errorText(e){let t=e instanceof d?e.code:"";if(t==="rate_limited")return this.t({id:"tzsBOP"});if(t==="network")return this.t({id:"GQVIIl"});if(t==="anonymous_not_allowed"||t==="invalid_identity_token")return this.t({id:"uuIskV"});return this.t({id:"tAL5wg"})}frame(e,...t){let i=a("style");i.textContent=ge+e;let s=a("div","frame");if(s.dir=this.direction,s.lang=this.locale,this.#s)s.style.setProperty("--yuva-accent",this.#s),s.style.setProperty("--yuva-on-accent",V(this.#s));s.append(...t);let n=null;try{n=this.root.activeElement}catch{}if(this.root.replaceChildren(i,s),n instanceof HTMLElement&&n.isConnected)n.focus({preventScroll:!0})}async#g(){return this.#n?await this.#n()??null:this.getAttribute("identity-token")}#l(){if(!this.#o)return;let e=P(this.getAttribute("page"));if(e===this.pageUrl)return;this.pageUrl=e,this.reset(),this.render(),this.pageChanged()}#c(){let e=this.locale;this.#e=pe[e]??w,this.direction=this.getAttribute("dir")==="rtl"?"rtl":this.getAttribute("dir")==="ltr"?"ltr":F(e)}#p(){let e=this.channel,t=`${this.server} ${e}`;if(!e||this.#r===t)return;this.#r=t;let i=I(e).launcher;if(i?.color)this.#d(i.color);let s=_.get(t);if(!s)s=this.client().channelSettings(),_.set(t,s),s.catch(()=>_.delete(t));s.then((n)=>{if(this.channel!==e)return;this.inbox=n;let o=J(n);if(o.color)this.#d(o.color);if(Z(e,{...I(e),launcher:o}),!this.refused)this.render()}).catch((n)=>{if(this.channel===e)this.refusal(n)})}#d(e){if(!/^#[0-9a-f]{6}$/i.test(e))return;this.#s=e}}var te="#yuva-discussion-",me=60000,x=new Map;function ye(e){for(let t of x.keys())if(t.startsWith(e))x.delete(t)}var S=(e)=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e}</svg>`,v={up:S('<path d="M12 19V5M5 12l7-7 7 7"/>'),comment:S('<path d="M21 12a8 8 0 01-11.6 7.1L4 20l1-4.6A8 8 0 1121 12z"/>'),check:S('<path d="M20 6L9 17l-5-5"/>'),lock:S('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/>'),clock:S('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>')},ve=`
60
+ .frame { display: flex; flex-direction: column; gap: 16px; }
61
+ :host { --yuva-success: #1a7f37; --yuva-warn: #9a6700; }
62
+ @media (prefers-color-scheme: dark) { :host { --yuva-success: #3fb950; --yuva-warn: #d29922; } }
63
+ h2 { margin: 0; font-size: 1.2em; font-weight: 600; }
64
+ h3 { margin: 0; font-size: 1.15em; font-weight: 600; overflow-wrap: anywhere; }
65
+ h3:focus { outline: none; }
66
+ button { font: inherit; color: inherit; }
67
+ .head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px; }
68
+ .who { display: flex; align-items: center; gap: 8px; font-size: 0.9em; }
69
+ .bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; }
70
+ .tabs { display: inline-flex; padding: 3px; gap: 2px; border: 1px solid var(--yuva-border); border-radius: 10px; }
71
+ .tab { padding: 4px 12px; border: 0; border-radius: 7px; background: none; cursor: pointer; opacity: 0.8; }
72
+ .tab[aria-selected="true"] { background: var(--yuva-soft); opacity: 1; font-weight: 600; }
73
+ .tab:focus-visible, .ghost:focus-visible, .vote:focus-visible, .title:focus-visible, .chip:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
74
+ .ghost {
75
+ display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px;
76
+ border: 1px solid var(--yuva-border); border-radius: 8px; background: none; cursor: pointer;
77
+ }
78
+ .ghost:hover:not(:disabled) { background: var(--yuva-soft); }
79
+ .ghost:disabled, .vote:disabled { opacity: 0.55; cursor: default; }
80
+ .ghost[aria-pressed="true"] { border-color: var(--yuva-accent); color: var(--yuva-accent); }
81
+ .plain { padding: 2px 4px; border: 0; background: none; cursor: pointer; font-size: 0.875em; opacity: 0.75; border-radius: 6px; }
82
+ .plain:hover:not(:disabled) { opacity: 1; background: var(--yuva-soft); }
83
+ .plain:focus-visible { outline: 2px solid var(--yuva-accent); opacity: 1; }
84
+ .plain.danger { color: var(--yuva-danger); opacity: 1; }
85
+ .list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--yuva-border); border-radius: 12px; overflow: hidden; }
86
+ .item { display: flex; gap: 12px; padding: 12px 14px; align-items: flex-start; }
87
+ .item + .item { border-block-start: 1px solid var(--yuva-border); }
88
+ .item:hover { background: var(--yuva-soft); }
89
+ .main { flex: 1; min-inline-size: 0; display: flex; flex-direction: column; gap: 2px; }
90
+ .title { padding: 0; border: 0; background: none; cursor: pointer; text-align: start; font-weight: 600; font-size: 1em; overflow-wrap: anywhere; }
91
+ .title:hover { color: var(--yuva-accent); text-decoration: underline; }
92
+ .excerpt { opacity: 0.75; font-size: 0.9em; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; }
93
+ .meta { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; font-size: 0.82em; opacity: 0.8; }
94
+ .counts { display: flex; gap: 12px; font-size: 0.85em; opacity: 0.8; flex-shrink: 0; padding-block-start: 2px; }
95
+ .count { display: inline-flex; align-items: center; gap: 4px; }
96
+ .avatar {
97
+ flex-shrink: 0; inline-size: 32px; block-size: 32px; border-radius: 50%;
98
+ display: inline-grid; place-items: center; font-size: 0.8em; font-weight: 600; color: #fff;
99
+ background: var(--avatar, #6b7280); text-transform: uppercase; user-select: none;
100
+ }
101
+ .avatar.small { inline-size: 24px; block-size: 24px; font-size: 0.68em; }
102
+ .avatar.team { background: var(--yuva-accent); color: var(--yuva-on-accent); }
103
+ .avatar.gone { background: var(--yuva-soft); color: inherit; }
104
+ .badge {
105
+ display: inline-flex; align-items: center; gap: 4px; padding: 1px 8px; border-radius: 999px;
106
+ font-size: 0.78em; font-weight: 600; border: 1px solid currentColor; line-height: 1.5; white-space: nowrap;
107
+ }
108
+ .badge.answered { color: var(--yuva-success); }
109
+ .badge.pending { color: var(--yuva-warn); }
110
+ .badge.team { color: var(--yuva-accent); }
111
+ .badge.locked { opacity: 0.75; }
112
+ .empty { padding: 28px 16px; text-align: center; border: 1px dashed var(--yuva-border); border-radius: 12px; }
113
+ .empty p + p { margin-block-start: 4px; }
114
+ .notice { padding: 10px 12px; border-radius: 10px; background: var(--yuva-soft); font-size: 0.9em; display: flex; gap: 8px; align-items: flex-start; }
115
+ .notice svg { flex-shrink: 0; margin-block-start: 3px; }
116
+ .more { align-self: center; }
117
+ .skeleton { block-size: 64px; border-radius: 12px; background: var(--yuva-soft); }
118
+ @media (max-width: 560px) {
119
+ .item { gap: 10px; padding: 12px; }
120
+ .item .avatar { display: none; }
121
+ .bar .send { inline-size: 100%; }
122
+ }
123
+ `;function be(e){let t=0;for(let i of e)t=t*31+i.charCodeAt(0)|0;return Math.abs(t)%360}function xe(e){let t=document.createElement("template");return t.innerHTML=e,(t.content.textContent??"").replace(/\s+/g," ").trim().slice(0,240)}class k extends C{static loadThread;#e={view:{kind:"list"},items:[],thread:null,threadState:"loading",writer:null,reader:null,busy:new Set,notice:"",error:"",confirm:"",focus:""};#i="new";#n;#t="loading";#r="";#o=null;#s=null;#h=null;#g="";get discussions(){return this.#e.items}get reader(){return this.#e.reader}#l=()=>this.#x();connectedCallback(){super.connectedCallback(),window.addEventListener("hashchange",this.#l),this.#c()}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener("hashchange",this.#l),this.#o?.(),this.#o=null}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),t===i||!this.isConnected)return;if(e==="channel"||e==="server")this.#o?.(),this.#o=null,this.#c();else if(e==="identity-token")this.#p(!0)}setIdentityToken(e){super.setIdentityToken(e),this.#p(!0)}#c(){if(!this.channel||this.#o)return;let e=this.client();this.#e.reader=e.reader,this.#o=e.on("reader",(t)=>{this.#e.reader=t,this.emit("yuva-reader",t?t.reader:null),this.#p(!0)}),this.#p(!1)}async#p(e){if(!this.channel)return;let t=await this.client().discussionWriter().catch(()=>null),i=t!==this.#e.writer;if(this.#e.writer=t,e&&i){if(this.#r="",this.#a(!1),this.#e.view.kind==="thread")this.#y(this.#e.view.id,!1)}this.render()}reset(){let e=this.#e;e.view={kind:"list"},e.items=[],this.#n=void 0,this.#t="loading",this.#r="",e.thread=null,e.notice="",e.error="",e.confirm="",this.#s?.reset()}pageChanged(){this.#a(!1),this.#x()}#d(){let e=location.hash;return e.startsWith(te)?decodeURIComponent(e.slice(te.length)):""}#x(){let e=this.#d();if(!e||!this.channel||this.refused)return;if(this.#e.view.kind==="thread"&&this.#e.view.id===e)return;this.#s?.close(),this.#e.confirm="",this.#y(e,!0),this.scrollIntoView({block:"start"})}#m(e){let t=()=>void this.#u();e.addEventListener("pointerenter",t,{once:!0}),e.addEventListener("focus",t,{once:!0})}#u(){return this.#h??=k.loadThread().then((e)=>{if(this.#g=e.styles,this.#s=e.createThread(this.#w),this.#e.view.kind!=="list")this.render();return this.#s},()=>{if(this.#h=null,this.#e.view.kind!=="list")this.#e.view={kind:"list"},this.#e.error=this.t({id:"D16wQE"}),this.render();return null}),this.#h}#w=this.#C();#C(){return{s:this.#e,icons:v,root:this.root,locale:()=>this.locale,direction:()=>this.direction,page:()=>this.pageUrl,pageTitle:()=>this.pageTitle,mode:()=>this.#P,client:()=>this.client(),render:()=>this.render(),emit:(e,t)=>this.emit(e,t),act:(e,t)=>this.#I(e,t),signIn:()=>this.signIn(),open:(e,t)=>this.#y(e,t),toList:()=>this.#S(),forget:()=>ye(this.#f),button:(e,t,i,s,n)=>this.#v(e,t,i,s,n),avatar:(e,t)=>this.#T(e,t),badge:(e,t)=>this.#k(e,t),time:(e)=>this.#E(e),authorName:(e)=>this.#R(e),noticeBox:(e,t)=>this.#M(e,t)}}reload(){return this.#a(!0)}open(e){return this.#y(e,!0)}signIn(){return this.#e.error="",this.client().readerSignIn().then(()=>{return}).catch((e)=>{let t=e instanceof d?e.code:"";if(t==="sign_in_cancelled")return;this.#e.error=t==="popup_blocked"?this.t({id:"nW3go1"}):this.#b(e),this.render()})}signOut(){return this.client().readerSignOut()}get#f(){return`${this.server} ${this.channel} ${this.pageUrl} `}async#a(e,t=!1){let i=this.pageUrl;if(!this.channel||!i||this.refused)return;let s=this.client().reader,n=s?s.token.slice(-12):this.#e.writer??"-",o=`${this.#f}${this.#i} ${n}`;if(!e&&!t&&this.#r===o)return;this.#r=o;let r;if(t)r=this.client().listDiscussions(i,{sort:this.#i,cursor:this.#n});else{let l=x.get(o);if(e||!l||Date.now()-l.at>me){l={at:Date.now(),request:this.client().listDiscussions(i,{sort:this.#i})},x.set(o,l);let c=l;l.request.catch(()=>x.get(o)===c&&x.delete(o))}if(r=l.request,!this.#e.items.length)this.#t="loading"}if(t)this.#e.busy.add("more");this.render();try{let l=await r;if(this.#r!==o)return;this.#e.items=t?[...this.#e.items,...l.items.filter((c)=>!this.#e.items.some((h)=>h.id===c.id))]:l.items,this.#n=l.next_cursor,this.#t="ready"}catch(l){if(this.#r!==o||this.refusal(l))return;if(!t)this.#r="";if(this.#t=l instanceof d&&l.code==="discussions_off"?"off":t?"ready":"error",t)this.#e.error=this.#b(l)}finally{this.#e.busy.delete("more")}this.render()}async#y(e,t){let i=this.#e,s=this.pageUrl,n=i.thread?.discussion.id===e?i.thread:null;this.#u(),i.view={kind:"thread",id:e};let o=i.items.find((r)=>r.id===e);if(i.thread=n??(o?{discussion:o,posts:[]}:null),i.threadState=n?"ready":"loading",t)i.notice=n?i.notice:"",i.error="",i.focus="thread-title";this.render();try{let r=await this.client().getDiscussion(e);if(this.pageUrl!==s||i.view.kind!=="thread"||i.view.id!==e)return;let l=!!i.thread;if(i.thread=r,i.threadState="ready",t&&!l)i.focus="thread-title";i.items=i.items.map((c)=>c.id===e?r.discussion:c)}catch(r){if(this.pageUrl!==s||i.view.kind!=="thread"||i.view.id!==e)return;if(this.refusal(r,!1))return;i.threadState=r instanceof d&&r.status===404?"missing":"error"}this.render()}#S(){let e=this.#e;if(this.#d()){let t=new URL(location.href);t.hash="",history.replaceState(history.state,"",t.href)}e.view={kind:"list"},this.#s?.close(),e.confirm="",e.error="",e.focus=e.thread?`open-${e.thread.discussion.id}`:"start",this.render(),this.#a(!1)}#b(e){let t=e instanceof d?e.code:"";if(t==="sign_in_required")return this.t({id:"LwDe8g"});if(t==="discussion_locked")return this.t({id:"KEjhwb"});if(t==="edit_window_closed")return this.t({id:"b_f4xj"});if(t==="discussions_off")return this.t({id:"tayT8P"});if(t==="forbidden")return this.t({id:"8Ekoev"});if(t==="validation_failed")return this.t({id:"Su3Vyp"});return this.errorText(e)}async#I(e,t){let i=this.#e;if(i.busy.has(e))return;i.busy.add(e),i.error="",this.render();try{return await t()}catch(s){if(!this.refusal(s,!1))i.error=this.#b(s);if(s instanceof d&&s.code==="sign_in_required")this.#p(!1);return}finally{i.busy.delete(e),this.render()}}get#P(){return this.inbox?.chat.discussions??"moderated"}#v(e,t,i,s,n=""){let o=a("button",e);if(o.type="button",n)o.innerHTML=n;return o.append(t),o.dataset.key=i,o.addEventListener("click",s),o}#R(e){if(e.deleted)return e.kind==="member"?this.t({id:"-UxBoG"}):this.t({id:"FMWGhb"});if(e.kind==="anonymous")return this.t({id:"D9CFV5"});return e.name||(e.kind==="member"?this.t({id:"nLqMRA"}):this.t({id:"zmA6sS"}))}#T(e,t=!1){let i=a("span",`avatar${t?" small":""}`,e.deleted?"":e.initials||"?");if(i.setAttribute("aria-hidden","true"),e.deleted||e.kind==="anonymous")i.classList.add("gone");else if(e.kind==="member")i.classList.add("team");else i.style.setProperty("--avatar",`hsl(${be(e.name||e.initials)} 45% 42%)`);return i}#k(e,t=!1){let i=e==="answered"?this.t({id:"GqCA_t"}):e==="pending"?t?this.t({id:"UbRKMZ"}):this.t({id:"lWv8id"}):e==="team"?this.t({id:"KM6m8p"}):this.t({id:"G2fuEb"}),s=a("span",`badge ${e}`);if(e!=="team")s.innerHTML=e==="answered"?v.check:e==="pending"?v.clock:v.lock;return s.append(i),s}#E(e){let t=a("time");t.dateTime=e;let i=new Date(e);t.title=i.toLocaleString(this.locale);let s=(i.getTime()-Date.now())/1000,n=[["second",60],["minute",60],["hour",24],["day",30],["month",12],["year",1/0]],o=s;for(let[r,l]of n){if(Math.abs(o)<l){t.textContent=r==="second"?this.t({id:"xOTzt5"}):new Intl.RelativeTimeFormat(this.locale,{numeric:"auto"}).format(Math.round(o),r);break}o/=l}return t}#_(){let e=a("div","head");e.append(a("h2","",this.t({id:"7oGBMv"})));let t=a("div","who"),i=this.#e.reader;if(i){let s=i.reader.name||this.t({id:"zmA6sS"});t.append(this.#T({kind:"reader",name:s,initials:i.reader.initials,deleted:!1},!0)),t.append(a("span","",s)),t.append(this.#v("plain",this.t({id:"fcWrnU"}),"sign-out",()=>void this.signOut()))}else if(!this.#e.writer&&this.#P!=="off")t.append(this.#v("ghost",this.t({id:"5lWFkC"}),"sign-in",()=>void this.signIn()));return e.append(t),e}#A(){let e=[],t=a("div","bar"),i=a("div","tabs");i.setAttribute("role","tablist"),i.setAttribute("aria-label",this.t({id:"78dEKp"}));let s=[["new",this.t({id:"isRobC"})],["top",this.t({id:"WWy8TN"})],["unanswered",this.t({id:"2lF8Zj"})]];s.forEach(([r,l],c)=>{let h=this.#v("tab",l,`sort-${r}`,()=>this.#D(r));h.setAttribute("role","tab"),h.setAttribute("aria-selected",String(this.#i===r)),h.setAttribute("aria-controls","yuva-discussion-list"),h.tabIndex=this.#i===r?0:-1,h.addEventListener("keydown",(p)=>{let u=p.key==="ArrowRight"?1:p.key==="ArrowLeft"?-1:0;if(!u)return;p.preventDefault();let y=this.direction==="rtl"?-u:u,f=s[(c+y+s.length)%s.length];if(f)this.#D(f[0])}),i.append(h)});let n=this.#v("send",this.t({id:"z1qf6l"}),"start",()=>{this.#u(),this.#e.view={kind:"new"},this.#e.error="",this.#e.notice="",this.#e.focus="new-title",this.render()});if(this.#m(n),t.append(i,n),e.push(t),this.#t==="loading"&&!this.#e.items.length){let r=a("div","skeleton");return r.setAttribute("aria-busy","true"),r.setAttribute("aria-label",this.t({id:"pzatAP"})),e.push(r),e}if(this.#t==="error"&&!this.#e.items.length){let r=a("div","empty");r.append(a("p","",this.t({id:"MDmQKn"})));let l=this.#v("ghost",this.t({id:"KDw4GX"}),"retry",()=>void this.#a(!0));return l.style.marginBlockStart="8px",r.append(l),e.push(r),e}if(!this.#e.items.length){let r=a("div","empty");if(r.append(a("p","",this.#i==="unanswered"?this.t({id:"twEQ41"}):this.t({id:"rpfOwz"}))),this.#i!=="unanswered")r.append(a("p","muted",this.t({id:"b6Orhy"})));return e.push(r),e}let o=a("ul","list");o.id="yuva-discussion-list",o.setAttribute("aria-label",this.t({id:"j-3eim"})),o.setAttribute("aria-busy",String(this.#t==="loading"));for(let r of this.#e.items){let l=a("li","item");l.append(this.#T(r.author));let c=a("div","main"),h=this.#v("title",r.title,`open-${r.id}`,()=>void this.#y(r.id,!0));h.dir="auto",this.#m(h),c.append(h);let p=r.deleted?"":xe(r.body_html);if(p){let g=a("p","excerpt",p);g.dir="auto",c.append(g)}let u=a("div","meta");if(u.append(a("span","",this.#R(r.author)),this.#E(r.created_at)),r.author.kind==="member"&&!r.author.deleted)u.append(this.#k("team"));if(r.answer_post_id)u.append(this.#k("answered"));if(r.state==="pending")u.append(this.#k("pending"));if(r.locked)u.append(this.#k("locked"));c.append(u);let y=a("div","counts"),f=a("span","count");f.innerHTML=v.up,f.append(String(r.votes)),f.setAttribute("aria-label",this.t({id:"8ntmc1",values:{0:r.votes}})),f.title=f.getAttribute("aria-label")??"";let m=a("span","count");m.innerHTML=v.comment,m.append(String(r.reply_count)),m.setAttribute("aria-label",this.t({id:"Hw3P48",values:{0:r.reply_count}})),m.title=m.getAttribute("aria-label")??"",y.append(f,m),l.append(c,y),o.append(l)}if(e.push(o),this.#n){let r=this.#v("ghost more",this.#e.busy.has("more")?this.t({id:"Pwqkdw"}):this.t({id:"fMPkxb"}),"more",()=>void this.#a(!1,!0));r.disabled=this.#e.busy.has("more"),e.push(r)}return e}#D(e){if(this.#i===e)return;this.#i=e,this.#e.items=[],this.#n=void 0,this.#t="loading",this.#e.focus=`sort-${e}`,this.#a(!1)}#M(e,t=v.clock){let i=a("div","notice");return i.setAttribute("role","status"),i.innerHTML=t,i.append(a("p","",e)),i}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let e="";try{e=this.root.activeElement?.dataset?.key??""}catch{}let t=[this.#_()];if(this.#P==="off"||this.#t==="off")t.push(a("p","muted",this.t({id:"tayT8P"})));else if(this.#e.view.kind!=="list"){let r=this.#s;if(r)t.push(...this.#e.view.kind==="thread"?r.threadView():r.newView());else{let l=a("div","skeleton");l.setAttribute("aria-busy","true"),l.setAttribute("aria-label",this.t({id:"Pwqkdw"})),t.push(l)}}else{if(this.#e.notice)t.push(this.#M(this.#e.notice));t.push(...this.#A())}if(this.#e.error){let r=a("p","error",this.#e.error);r.setAttribute("role","alert"),t.push(r)}if(this.frame(ve+this.#g,...t),this.#e.view.kind!=="list"&&!this.#s)return;this.#s?.syncSend();let i=this.#e.focus;this.#e.focus="";let s=i||e;if(!s)return;let n=null;try{n=this.root.activeElement}catch{}if(n instanceof HTMLElement&&n.dataset.key===s)return;[...this.root.querySelectorAll("[data-key]")].find((r)=>r.dataset.key===s)?.focus({preventScroll:!i})}}var ke=500,we=(e)=>`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"${e?' style="transform:scaleY(-1)"':""}><path d="M7 10v11H3V10zM7 10l4-8a3 3 0 013 3v4h6a2 2 0 012 2.3l-1.4 8A2 2 0 0118.6 21H7"/></svg>`,Ce=`
124
+ .frame { display: flex; flex-direction: column; gap: 12px; }
125
+ .ask { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; }
126
+ .question { font-weight: 600; }
127
+ .choices { display: flex; gap: 8px; }
128
+ .choice {
129
+ display: inline-flex;
130
+ align-items: center;
131
+ gap: 6px;
132
+ padding: 6px 12px;
133
+ border: 1px solid var(--yuva-border);
134
+ border-radius: 999px;
135
+ background: transparent;
136
+ color: inherit;
137
+ font: inherit;
138
+ cursor: pointer;
139
+ }
140
+ .choice:hover:not(:disabled), .choice[aria-pressed="true"] { border-color: var(--yuva-accent); box-shadow: inset 0 0 0 1px var(--yuva-accent); }
141
+ .choice[aria-pressed="true"] { background: var(--yuva-soft); }
142
+ .choice:disabled { cursor: default; }
143
+ .choice:focus-visible { outline: 2px solid var(--yuva-accent); outline-offset: 2px; }
144
+ `;function ie(e){return`yuva:${e}:page-ratings`}function R(e){try{let t=localStorage.getItem(ie(e));return t?JSON.parse(t):{}}catch{return{}}}function Se(e,t,i){try{let s=R(e);delete s[t],s[t]=i;let n=Object.keys(s);for(let o of n.slice(0,Math.max(0,n.length-ke)))delete s[o];localStorage.setItem(ie(e),JSON.stringify(s))}catch{}}class A extends C{#e="ask";#i;#n="";#t=a("textarea");#r=a("input");constructor(){super();this.#t.rows=3,this.#t.maxLength=5000,this.#t.dir="auto",this.#t.addEventListener("input",()=>this.#s()),this.#r.type="email",this.#r.autocomplete="email"}get rating(){return this.#i??null}reset(){this.#e="ask",this.#n="",this.#t.value="",this.#i=this.channel?R(this.channel)[this.pageUrl]:void 0}pageChanged(){if(this.#e==="ask"&&!this.#n)this.#i=this.channel?R(this.channel)[this.pageUrl]:void 0;this.render()}async rate(e){let t=this.channel;if(!t||this.refused||this.#e==="rating"||this.#e==="sending")return;let i=this.pageUrl,s=R(t)[i];if(this.#n="",s===e){this.#i=e,this.#e=this.canWrite?"form":"thanks",this.render(),this.#t.focus({preventScroll:!0});return}this.#e="rating",this.#i=e,this.render();try{await this.client().ratePage({page:i,title:this.pageTitle||void 0,rating:e,previous:s})}catch(n){if(this.pageUrl!==i||this.refusal(n))return;this.#i=s,this.#e="ask",this.#n=this.errorText(n),this.render();return}if(Se(t,i,e),this.emit("yuva-rating",{page:i,rating:e,previous:s??null}),this.pageUrl!==i)return;this.#e=this.canWrite?"form":"thanks",this.render(),this.#t.focus({preventScroll:!0})}async#o(){let e=this.#t.value.trim(),t=this.#r.value.trim(),i=this.#i;if(!e||this.#e!=="form")return;if(t&&!this.#r.checkValidity()){this.#n=this.t({id:"E_qvzP"}),this.render();return}let s=this.pageUrl;this.#e="sending",this.#n="",this.render();try{let{conversation:n}=await this.client().sendFeedback({page_url:s,page_title:this.pageTitle||void 0,rating:i,body:e,locale:this.locale,allow_email:this.identified||!!t,email:!this.identified&&t?t:void 0});if(this.emit("yuva-feedback",{page:s,rating:i??null,conversation_id:n.id}),this.pageUrl!==s)return;this.#t.value="",this.#e="thanks"}catch(n){if(this.pageUrl!==s||this.refusal(n,!1))return;this.#e="form",this.#n=this.errorText(n)}this.render()}#s(){let e=this.root.querySelector(".send");if(e)e.disabled=this.#e!=="form"||this.#t.value.trim()===""}render(){if(this.refused||!this.channel){this.root.replaceChildren();return}let e=this.t({id:"SOvBw9"}),t=a("div","ask");t.setAttribute("role","group"),t.setAttribute("aria-label",e);let i=a("div","choices");for(let n of["up","down"]){let o=a("button","choice");o.type="button",o.innerHTML=we(n==="down"),o.append(a("span","",n==="up"?this.t({id:"l75CjT"}):this.t({id:"1UzENP"}))),o.setAttribute("aria-pressed",String(this.#i===n)),o.disabled=this.#e==="rating"||this.#e==="sending",o.addEventListener("click",()=>void this.rate(n)),i.append(o)}t.append(a("p","question",e),i);let s=[t];if(this.#e==="form"||this.#e==="sending"){let n=a("form");n.noValidate=!0,n.addEventListener("submit",(h)=>{h.preventDefault(),this.#o()});let o=this.#i==="down"?this.t({id:"U7H5Fm"}):this.t({id:"EmiQvf"});if(this.#t.placeholder=o,this.#t.setAttribute("aria-label",o),this.#t.disabled=this.#e==="sending",n.append(this.#t),!this.identified)this.#r.placeholder=this.t({id:"a_qtPP"}),this.#r.setAttribute("aria-label",this.t({id:"XJURKP"})),this.#r.disabled=this.#e==="sending",n.append(this.#r);let r=a("button","link",this.t({id:"tA4dAO"}));r.type="button",r.disabled=this.#e==="sending",r.addEventListener("click",()=>{this.#e="thanks",this.#n="",this.render()});let l=a("button","send",this.#e==="sending"?this.t({id:"Sad2tK"}):this.t({id:"JlFcis"}));l.type="submit";let c=a("div","actions");c.append(r,l),n.append(c),s.push(n)}else if(this.#e==="thanks"){let n=a("p","muted",this.t({id:"d6N994"}));n.setAttribute("role","status"),s.push(n)}if(this.#n){let n=a("p","error",this.#n);n.setAttribute("role","alert"),s.push(n)}this.frame(Ce,...s),this.#s()}}function se(){if(typeof customElements>"u")return;if(!customElements.get("yuva-discussions"))customElements.define("yuva-discussions",k);if(!customElements.get("yuva-page-feedback"))customElements.define("yuva-page-feedback",A)}k.loadThread=()=>import(new URL("widget/yuva-docs-thread-4580g2ny.js",T||location.href).href);se();})();
package/dist/yuva.js CHANGED
@@ -1,4 +1,4 @@
1
- (()=>{var o=JSON.parse('{"6I7cJR":["Open chat"],"OkHvGB":["Open chat, ",["count"]," unread"],"pqZJT2":["Close chat"]}');var d=JSON.parse('{"6I7cJR":["Sohbeti aç"],"OkHvGB":["Sohbeti aç, ",["count"]," okunmamış"],"pqZJT2":["Sohbeti kapat"]}');var l={en:o,tr:d},k=new Set(["ar","fa","he","ur"]),w="en";function p(...t){for(let e of t){if(!e)continue;let i=e.toLowerCase();if(l[i])return i;let n=i.split(/[-_]/)[0]??"";if(l[n])return n}return w}function f(t){return k.has(t.split(/[-_]/)[0]??"")?"rtl":"ltr"}function g(t){return l[t]??o}function r(t,e){let i=t[e.id]??o[e.id],n=e.values??{};if(typeof i==="string")return i;if(Array.isArray(i))return i.map((s)=>typeof s==="string"?s:Array.isArray(s)?String(n[s[0]]??""):"").join("");return e.message??e.id}function y(t){return{position:t.chat.launcher_position,color:t.chat.launcher_color??t.branding.color}}function m(t){return`yuva:${t}`}function c(t){try{let e=localStorage.getItem(m(t));return e?JSON.parse(e):{}}catch{return{}}}function v(t,e){try{localStorage.setItem(m(t),JSON.stringify(e))}catch{}}var C=`
1
+ (()=>{var o=JSON.parse('{"6I7cJR":["Open chat"],"OkHvGB":["Open chat, ",["count"]," unread"],"pqZJT2":["Close chat"]}');var p=JSON.parse('{"6I7cJR":["Sohbeti aç"],"OkHvGB":["Sohbeti aç, ",["count"]," okunmamış"],"pqZJT2":["Sohbeti kapat"]}');function g(e,t,i){let n=e[t.id]??i[t.id],a=t.values??{};if(typeof n==="string")return n;if(Array.isArray(n))return n.map((s)=>typeof s==="string"?s:Array.isArray(s)?String(a[s[0]]??""):"").join("");return t.message??t.id}var c={en:o,tr:p},C=new Set(["ar","fa","he","ur"]),S="en";function f(...e){for(let t of e){if(!t)continue;let i=t.toLowerCase();if(c[i])return i;let n=i.split(/[-_]/)[0]??"";if(c[n])return n}return S}function y(e){return C.has(e.split(/[-_]/)[0]??"")?"rtl":"ltr"}function m(e){return c[e]??o}function r(e,t,i=o){return g(e,t,i)}function b(e){return{position:e.chat.launcher_position,color:e.chat.launcher_color??e.branding.color}}function v(e){let t=Number.parseInt(e.slice(1),16),[i,n,a]=[t>>16&255,t>>8&255,t&255].map((s)=>{let l=s/255;return l<=0.03928?l/12.92:((l+0.055)/1.055)**2.4});return 0.2126*i+0.7152*n+0.0722*a>0.4?"#111827":"#ffffff"}function x(e){return`yuva:${e}`}function h(e){try{let t=localStorage.getItem(x(e));return t?JSON.parse(t):{}}catch{return{}}}function k(e,t){try{localStorage.setItem(x(e),JSON.stringify(t))}catch{}}var L=`
2
2
  :host {
3
3
  --yuva-accent: #2563eb;
4
4
  --yuva-on-accent: #ffffff;
@@ -106,4 +106,4 @@
106
106
  block-size: 100%;
107
107
  min-block-size: 320px;
108
108
  }
109
- `,S='<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>',L='<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>',h=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";function A(t){let e=Number.parseInt(t.slice(1),16),[i,n,s]=[e>>16&255,e>>8&255,e&255].map((x)=>{let a=x/255;return a<=0.03928?a/12.92:((a+0.055)/1.055)**2.4});return 0.2126*i+0.7152*n+0.0722*s>0.4?"#111827":"#ffffff"}class u extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",h||location.href).href);#r;#s=null;#n=null;#i;#t=null;#a={};#e=!1;#u=0;#l=null;#o=!1;constructor(){super();this.#r=this.attachShadow({mode:"open"}),this.#i=document.createElement("section"),this.#i.className="panel",this.#i.setAttribute("role","dialog"),this.#i.hidden=!0,this.#i.addEventListener("keydown",(t)=>{if(t.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")||(h?new URL(h).origin:location.origin)).replace(/\/+$/,"")}get locale(){return p(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#e}get unread(){return this.#u}setIdentityToken(t){if(this.#l=t,this.#t)this.#t.then((e)=>e.identityChanged())}async signOut(){if(this.#l=null,this.removeAttribute("identity-token"),this.#t)await(await this.#t).signOut()}async rate(t,e,i){return(await this.#d()).rate(t,e,i)}connectedCallback(){this.#c();let t=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!t)return;let e=c(t);if(e.launcher)this.#p(e.launcher);let i=()=>{if(!this.isConnected||this.#t||this.channel!==t)return;if(e.session)this.#d();else this.#g(t)};if("requestIdleCallback"in window)requestIdleCallback(i,{timeout:3000});else setTimeout(i,1000)}#g(t){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(t)}`,{credentials:"omit"}).then((e)=>{if(e.status===403||e.status===404)this.#f();return e.ok?e.json():null}).then((e)=>{if(!e||this.channel!==t||this.#t)return;let i=y(e);this.#p(i),v(t,{...c(t),launcher:i})}).catch(()=>{return})}disconnectedCallback(){let t=this.#t;if(this.#t=null,t)t.then((e)=>e.destroy())}attributeChangedCallback(t,e,i){if(!this.isConnected||e===i)return;if(t==="open"){i===null?this.close():this.open();return}if(t==="identity-token"){if(this.#t)this.#t.then((n)=>n.identityChanged());return}if(t==="channel"||t==="server"){this.disconnectedCallback(),this.#o=!1,this.#c();return}if(this.#c(),this.#t)this.#t.then((n)=>n.update())}async open(){if(this.#e||this.#o)return;this.#e=!0,this.toggleAttribute("open-panel",!0),this.#h();let t=await this.#d();if(!this.#e)return;this.#i.hidden=!1,t.opened()}close(){if(!this.#e||this.layout==="embedded")return;if(this.#e=!1,this.toggleAttribute("open-panel",!1),this.#i.hidden=!0,this.#h(),this.#s?.focus(),this.#t)this.#t.then((t)=>t.closed())}toggle(){return this.#e?this.close():this.open()}#y(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#d(){return this.#t??=u.loadPanel().then(({mount:t})=>t({panel:this.#i,config:()=>this.#y(),identityToken:async()=>this.#l?await this.#l()??null:this.getAttribute("identity-token"),isOpen:()=>this.#e,close:()=>this.close(),setUnread:(e)=>{this.#u=e,this.#h(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count:e}}))},setLauncher:(e)=>this.#p(e),refused:()=>this.#f()})),this.#t}#f(){if(this.#o)return;this.#o=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#e=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#c()}#p(t){if(this.setAttribute("position",t.position==="left"?"left":"right"),t.color&&/^#[0-9a-f]{6}$/i.test(t.color))this.style.setProperty("--yuva-accent",t.color),this.style.setProperty("--yuva-on-accent",A(t.color))}#c(){let t=this.locale;this.#a=g(t),this.setAttribute("lang",t);let e=document.createElement("style");if(e.textContent=C,this.#i.dir=this.getAttribute("dir")??f(t),this.#i.setAttribute("aria-modal","false"),this.#o){this.#s=null,this.#n=null,this.#r.replaceChildren();return}if(this.layout==="embedded"){this.#s=null,this.#n=null,this.#r.replaceChildren(e,this.#i),this.#e=!1,this.open();return}let i=document.createElement("button");if(i.type="button",i.className="launcher",i.addEventListener("click",()=>void this.toggle()),this.#s=i,this.#n=document.createElement("span"),this.#n.className="badge",this.#n.setAttribute("aria-hidden","true"),this.#r.replaceChildren(e,this.#i,i),this.#h(),this.hasAttribute("open")&&!this.#e)this.open()}#h(){let t=this.#s,e=this.#n;if(!t||!e)return;let i=this.#u;t.setAttribute("aria-expanded",String(this.#e)),t.setAttribute("aria-label",this.#e?r(this.#a,{id:"pqZJT2"}):i>0?r(this.#a,{id:"OkHvGB",values:{count:i}}):r(this.#a,{id:"6I7cJR"})),t.innerHTML=this.#e?L:S,e.textContent=i>9?"9+":String(i),e.hidden=this.#e||i===0,t.append(e)}}function b(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",u)}b();})();
109
+ `,A='<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>',M='<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>',u=document.currentScript instanceof HTMLScriptElement?document.currentScript.src:"";class d extends HTMLElement{static observedAttributes=["channel","server","layout","locale","dir","identity-token","open"];static loadPanel=()=>import(new URL("yuva-chat.js",u||location.href).href);#r;#s=null;#n=null;#i;#e=null;#a={};#t=!1;#u=0;#l=null;#o=!1;constructor(){super();this.#r=this.attachShadow({mode:"open"}),this.#i=document.createElement("section"),this.#i.className="panel",this.#i.setAttribute("role","dialog"),this.#i.hidden=!0,this.#i.addEventListener("keydown",(e)=>{if(e.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")||(u?new URL(u).origin:location.origin)).replace(/\/+$/,"")}get locale(){return f(this.getAttribute("locale"),navigator.language)}get isOpen(){return this.#t}get unread(){return this.#u}setIdentityToken(e){if(this.#l=e,this.#e)this.#e.then((t)=>t.identityChanged())}async signOut(){if(this.#l=null,this.removeAttribute("identity-token"),this.#e)await(await this.#e).signOut()}async rate(e,t,i){return(await this.#d()).rate(e,t,i)}connectedCallback(){this.#c();let e=this.channel;if(this.layout==="embedded"||this.hasAttribute("open")||!e)return;let t=h(e);if(t.launcher)this.#p(t.launcher);let i=()=>{if(!this.isConnected||this.#e||this.channel!==e)return;if(t.session)this.#d();else this.#f(e)};if("requestIdleCallback"in window)requestIdleCallback(i,{timeout:3000});else setTimeout(i,1000)}#f(e){fetch(`${this.server}/client/v1/channels/${encodeURIComponent(e)}`,{credentials:"omit"}).then((t)=>{if(t.status===403||t.status===404)this.#g();return t.ok?t.json():null}).then((t)=>{if(!t||this.channel!==e||this.#e)return;let i=b(t);this.#p(i),k(e,{...h(e),launcher:i})}).catch(()=>{return})}disconnectedCallback(){let e=this.#e;if(this.#e=null,e)e.then((t)=>t.destroy())}attributeChangedCallback(e,t,i){if(!this.isConnected||t===i)return;if(e==="open"){i===null?this.close():this.open();return}if(e==="identity-token"){if(this.#e)this.#e.then((n)=>n.identityChanged());return}if(e==="channel"||e==="server"){this.disconnectedCallback(),this.#o=!1,this.#c();return}if(this.#c(),this.#e)this.#e.then((n)=>n.update())}async open(){if(this.#t||this.#o)return;this.#t=!0,this.toggleAttribute("open-panel",!0),this.#h();let e=await this.#d();if(!this.#t)return;this.#i.hidden=!1,e.opened()}close(){if(!this.#t||this.layout==="embedded")return;if(this.#t=!1,this.toggleAttribute("open-panel",!1),this.#i.hidden=!0,this.#h(),this.#s?.focus(),this.#e)this.#e.then((e)=>e.closed())}toggle(){return this.#t?this.close():this.open()}#y(){return{channel:this.channel,server:this.server,layout:this.layout,locale:this.locale}}#d(){return this.#e??=d.loadPanel().then(({mount:e})=>e({panel:this.#i,config:()=>this.#y(),identityToken:async()=>this.#l?await this.#l()??null:this.getAttribute("identity-token"),isOpen:()=>this.#t,close:()=>this.close(),setUnread:(t)=>{this.#u=t,this.#h(),this.dispatchEvent(new CustomEvent("yuva-unread",{detail:{count:t}}))},setLauncher:(t)=>this.#p(t),refused:()=>this.#g()})),this.#e}#g(){if(this.#o)return;this.#o=!0,console.warn(`Yuva: channel ${this.channel} is unknown or does not allow ${location.origin}`),this.#t=!1,this.toggleAttribute("open-panel",!1),this.disconnectedCallback(),this.#c()}#p(e){if(this.setAttribute("position",e.position==="left"?"left":"right"),e.color&&/^#[0-9a-f]{6}$/i.test(e.color))this.style.setProperty("--yuva-accent",e.color),this.style.setProperty("--yuva-on-accent",v(e.color))}#c(){let e=this.locale;this.#a=m(e),this.setAttribute("lang",e);let t=document.createElement("style");if(t.textContent=L,this.#i.dir=this.getAttribute("dir")??y(e),this.#i.setAttribute("aria-modal","false"),this.#o){this.#s=null,this.#n=null,this.#r.replaceChildren();return}if(this.layout==="embedded"){this.#s=null,this.#n=null,this.#r.replaceChildren(t,this.#i),this.#t=!1,this.open();return}let i=document.createElement("button");if(i.type="button",i.className="launcher",i.addEventListener("click",()=>void this.toggle()),this.#s=i,this.#n=document.createElement("span"),this.#n.className="badge",this.#n.setAttribute("aria-hidden","true"),this.#r.replaceChildren(t,this.#i,i),this.#h(),this.hasAttribute("open")&&!this.#t)this.open()}#h(){let e=this.#s,t=this.#n;if(!e||!t)return;let i=this.#u;e.setAttribute("aria-expanded",String(this.#t)),e.setAttribute("aria-label",this.#t?r(this.#a,{id:"pqZJT2"}):i>0?r(this.#a,{id:"OkHvGB",values:{count:i}}):r(this.#a,{id:"6I7cJR"})),e.innerHTML=this.#t?M:A,t.textContent=i>9?"9+":String(i),t.hidden=this.#t||i===0,e.append(t)}}function w(){if(!customElements.get("yuva-chat"))customElements.define("yuva-chat",d)}w();})();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "useyuva",
3
- "version": "0.0.6",
4
- "description": "Yuva for the web: a headless client for contacts, the <yuva-chat> element, React hooks and a typed /v1 client.",
3
+ "version": "0.0.8",
4
+ "description": "Yuva for the web: a headless client for contacts, the <yuva-chat> element, documentation page feedback and discussions, React hooks, a Nuxt module and a typed /v1 client.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -15,13 +15,16 @@
15
15
  "support",
16
16
  "live-chat",
17
17
  "web-component",
18
- "customer-messaging"
18
+ "customer-messaging",
19
+ "nuxt"
19
20
  ],
20
21
  "type": "module",
21
22
  "sideEffects": [
22
23
  "./dist/esm/chat.js",
24
+ "./dist/esm/docs.js",
23
25
  "./dist/yuva.js",
24
- "./dist/yuva-chat.js"
26
+ "./dist/yuva-chat.js",
27
+ "./dist/yuva-docs.js"
25
28
  ],
26
29
  "exports": {
27
30
  ".": {
@@ -32,6 +35,10 @@
32
35
  "types": "./dist/types/chat.d.ts",
33
36
  "default": "./dist/esm/chat.js"
34
37
  },
38
+ "./docs": {
39
+ "types": "./dist/types/docs.d.ts",
40
+ "default": "./dist/esm/docs.js"
41
+ },
35
42
  "./react": {
36
43
  "types": "./dist/types/react.d.ts",
37
44
  "default": "./dist/esm/react.js"
@@ -40,6 +47,14 @@
40
47
  "types": "./dist/types/api.d.ts",
41
48
  "default": "./dist/esm/api.js"
42
49
  },
50
+ "./nuxt": {
51
+ "types": "./dist/types/nuxt/module.d.ts",
52
+ "default": "./dist/esm/nuxt/module.js"
53
+ },
54
+ "./nuxt/components": {
55
+ "types": "./dist/types/nuxt/runtime/components.d.ts",
56
+ "default": "./dist/esm/nuxt/runtime/components.js"
57
+ },
43
58
  "./package.json": "./package.json"
44
59
  },
45
60
  "types": "./dist/types/index.d.ts",
@@ -54,21 +69,32 @@
54
69
  "extract": "lingui extract --clean --workers 1",
55
70
  "compile": "lingui compile --strict --typescript",
56
71
  "typecheck": "tsc --noEmit",
57
- "check": "bun run compile && bun run typecheck && bun test",
72
+ "check": "bun run format:check && bun run lint && bun run compile && bun run typecheck && bun test",
58
73
  "build": "bun run compile && bun scripts/build.ts",
59
74
  "example": "bun scripts/serve.ts",
60
- "prepublishOnly": "bun run check && bun run build"
75
+ "prepublishOnly": "bun run check && bun run build",
76
+ "lint": "oxlint",
77
+ "format": "oxfmt",
78
+ "format:check": "oxfmt --check"
61
79
  },
62
80
  "dependencies": {
63
81
  "@lingui/core": "^6.9.0",
64
82
  "openapi-fetch": "0.17.0"
65
83
  },
66
84
  "peerDependencies": {
67
- "react": ">=18"
85
+ "@nuxt/kit": ">=3.15.0",
86
+ "react": ">=18",
87
+ "vue": ">=3.5.0"
68
88
  },
69
89
  "peerDependenciesMeta": {
90
+ "@nuxt/kit": {
91
+ "optional": true
92
+ },
70
93
  "react": {
71
94
  "optional": true
95
+ },
96
+ "vue": {
97
+ "optional": true
72
98
  }
73
99
  },
74
100
  "devDependencies": {
@@ -77,10 +103,15 @@
77
103
  "@lingui/conf": "^6.9.0",
78
104
  "@lingui/format-po": "^6.9.0",
79
105
  "@lingui/native-tools": "^0.1.5",
106
+ "@nuxt/kit": "4.6.1",
107
+ "@nuxt/schema": "4.6.1",
80
108
  "@types/bun": "^1.4.2",
81
109
  "@types/react": "19.2.2",
82
110
  "happy-dom": "^20.14.5",
111
+ "oxfmt": "0.72.0",
112
+ "oxlint": "1.87.0",
83
113
  "react": "19.2.0",
84
- "typescript": "^7.0.2"
114
+ "typescript": "^7.0.2",
115
+ "vue": "3.5.43"
85
116
  }
86
117
  }
@@ -1,12 +0,0 @@
1
- class ApiError2 extends Error{status;code;constructor(status,code){super(`${status} ${code}`);this.status=status;this.code=code}}async function call(fetcher,server,path,{method="GET",json,body,headers={},token,blob}={}){if(headers={...headers},token)headers.Authorization=`Bearer ${token}`;let payload=body;if(json!==void 0)headers["Content-Type"]="application/json",payload=JSON.stringify(json);let response;try{response=await fetcher(server+path,{method,headers,body:payload,credentials:"omit"})}catch{throw new ApiError2(0,"network")}if(!response.ok){let code="error";try{code=(await response.json()).code??code}catch{}throw new ApiError2(response.status,code)}if(response.status===204)return;return blob?await response.blob():await response.json()}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 storageKey(channel){return`yuva:${channel}`}function randomId(){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
- Content-Disposition: form-data; name="${name}"\r
3
- \r
4
- ${value}\r
5
- `);for(let file of files){let filename=file.name||"file";parts.push(`--${boundary}\r
6
- Content-Disposition: form-data; name="files"; filename="${quoted(filename)}"\r
7
- Content-Type: ${file.type||"application/octet-stream"}\r
8
- \r
9
- `,file,`\r
10
- `)}return parts.push(`--${boundary}--\r
11
- `),new Blob(parts)}class YuvaClient2{server;channel;#fetch;#socketClass;#storage;#identity;#idempotencyKeys;#token=null;#session=null;#starting=null;#renewing=null;#realtime=null;#handlers=new Map;constructor(options){this.server=options.server.replace(/\/+$/,""),this.channel=options.channel,this.#fetch=options.fetch??((url,init)=>fetch(url,init)),this.#socketClass=options.WebSocket??globalThis.WebSocket,this.#storage=options.storage??defaultStorage(),this.#identity=options.identityToken??null,this.#idempotencyKeys=options.idempotencyKeys??typeof globalThis.document>"u"}get session(){return this.#session}get token(){return this.#token}get connected(){return this.#realtime?.connected??!1}on(type,handler){let set=this.#handlers.get(type);if(!set)this.#handlers.set(type,set=new Set);return set.add(handler),()=>void set.delete(handler)}#emit(type,value){for(let handler of this.#handlers.get(type)??[])handler(value)}stored(){try{let raw=this.#storage.getItem(storageKey(this.channel));return raw?JSON.parse(raw):{}}catch{return{}}}#store(state){try{this.#storage.setItem(storageKey(this.channel),JSON.stringify(state))}catch{}}channelSettings(){return this.#call(`/client/v1/channels/${encodeURIComponent(this.channel)}`)}setIdentityToken(source){this.#identity=source,this.reset()}start(){if(this.#session)return Promise.resolve(this.#session);return this.#starting??=this.#open(!1).then((session)=>(this.#emit("session",{session,renewed:!1}),session)).finally(()=>{this.#starting=null}),this.#starting}async refresh(){let info=await this.#authed("/client/v1/session");return this.#session={...this.#session,...info},this.#emit("session",{session:this.#session,renewed:!1}),this.#session}reset(){this.#realtime?.stop(),this.#realtime?.reset(),this.#starting=null,this.#renewing=null,this.#token=null,this.#session=null}async signOut(){let token=this.#token;this.reset();let stored=this.stored();if(delete stored.session,this.#store(stored),token)await this.#call("/client/v1/session",{method:"DELETE",token}).catch(()=>{return})}async connect(){if(!this.#socketClass)throw Error("Yuva: no WebSocket in this runtime; pass options.WebSocket");if(await this.start(),this.#realtime??=new Realtime(this.server,this.#socketClass,{token:()=>this.#token,event:(message)=>{if(message.type==="ready")this.#emit("connection",{state:"open",attempt:0});this.#emit("event",message)},sessionEnded:()=>void this.#renew().catch(()=>this.#realtime?.nudge()),reconnecting:(attempt)=>{if(this.#emit("connection",{state:"reconnecting",attempt}),attempt===2)this.#authed("/client/v1/session").catch(()=>{return})}}),!this.#realtime.connected)this.#emit("connection",{state:"connecting",attempt:0});this.#realtime.start()}disconnect(){this.#realtime?.stop(),this.#emit("connection",{state:"closed",attempt:0})}reconnect(){this.#realtime?.nudge()}listConversations(page={}){return this.#authed(`/client/v1/conversations${query({...page})}`)}getConversation(id){return this.#authed(`/client/v1/conversations/${encodeURIComponent(id)}`)}startConversation(input){return this.#authed("/client/v1/conversations",this.#messageRequest(input))}listMessages(conversationId,page={}){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/messages${query({...page})}`)}sendMessage(conversationId,input){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/messages`,this.#messageRequest(input))}markRead(conversationId,messageId){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/read`,{method:"POST",json:messageId?{message_id:messageId}:{}})}rate(conversationId,rating,comment){let body={rating,comment:comment?.trim()||void 0};return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/rating`,{method:"POST",json:body})}setTyping(conversationId,typing){return this.#authed(`/client/v1/conversations/${encodeURIComponent(conversationId)}/typing`,{method:"POST",json:{typing}})}setEmail(email){return this.#authed("/client/v1/contact/email",{method:"PUT",json:{email}})}attachment(id){return this.#authed(`/client/v1/attachments/${encodeURIComponent(id)}`,{blob:!0})}#messageRequest({body,subject,files=[],client_id=randomId()}){let headers=this.#idempotencyKeys&&/^[\x20-\x7e]{1,255}$/.test(client_id)?{"Idempotency-Key":client_id}:{};if(files.length===0)return{method:"POST",headers,json:{body,subject,client_id}};let fields=[];if(subject)fields.push(["subject",subject]);if(body)fields.push(["body",body]);fields.push(["client_id",client_id]);let boundary=`yuva-${client_id.replace(/[^\w-]/g,"").slice(0,60)}-${client_id.length}`;return headers["Content-Type"]=`multipart/form-data; boundary=${boundary}`,{method:"POST",headers,body:multipart(fields,files,boundary)}}#call(path,request){return call(this.#fetch,this.server,path,request)}async#authed(path,request={},retry=!0){if(!this.#token)await this.start();try{return await this.#call(path,{...request,token:this.#token})}catch(error){if(!retry||!(error instanceof ApiError2)||error.status!==401)throw error;return await this.#renew(),this.#authed(path,request,!1)}}#renew(){return this.#renewing??=(async()=>{let session=await this.#open(!0);if(this.#realtime)this.#realtime.stop(),this.#realtime.reset(),this.#realtime.start();this.#emit("session",{session,renewed:!0})})().finally(()=>{this.#renewing=null}),this.#renewing}async#open(fresh){let stored=this.stored(),identity=await this.#identity?.()||null,subject=identity?jwtSubject(identity):null,saved=stored.session;if(!fresh&&saved&&saved.sub===subject&&Date.parse(saved.expires_at)>Date.now()+60000)try{let info=await this.#call("/client/v1/session",{token:saved.token});return this.#apply(info,saved.token,subject)}catch(error){if(!(error instanceof ApiError2)||error.status!==401&&error.status!==403)throw error}let session=await this.#call("/client/v1/session",{method:"POST",json:{channel_key:this.channel,identity_token:identity??void 0,visitor_id:stored.visitor_id}}),{token,...info}=session;return this.#apply(info,token,subject)}#apply(info,token,subject){this.#token=token,this.#session=info;let stored=this.stored();if(stored.session={token,expires_at:info.expires_at,sub:subject},info.visitor_id)stored.visitor_id=info.visitor_id;else if(info.contact.identified)delete stored.visitor_id;return this.#store(stored),info}}function createYuvaClient2(options){return new YuvaClient2(options)}
12
- export{ApiError2,randomId,YuvaClient2,createYuvaClient2};
@@ -1,2 +0,0 @@
1
- function launcherOf(inbox){return{position:inbox.chat.launcher_position,color:inbox.chat.launcher_color??inbox.branding.color}}function storageKey(channel){return`yuva:${channel}`}function readStored(channel){try{let raw=localStorage.getItem(storageKey(channel));return raw?JSON.parse(raw):{}}catch{return{}}}function writeStored(channel,state){try{localStorage.setItem(storageKey(channel),JSON.stringify(state))}catch{}}
2
- export{launcherOf,readStored,writeStored};