domma-cms 1.49.2 → 1.50.0

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.
@@ -1,9 +1,10 @@
1
- const ae={waiting:3e3,open:3e3,bot:9e3,message:2e4},se=6e3,ne="/public/css/launcher-chat.css?v=20261031-chat",Y=()=>document.documentElement.classList.contains("dm-reduced-motion")||!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function ie(){if(document.querySelector("link[data-dm-chat-css]"))return;const t=document.createElement("link");t.rel="stylesheet",t.href=ne,t.dataset.dmChatCss="",document.head.appendChild(t)}const B={get:t=>{try{return globalThis.S?.get?.(t)??null}catch{return null}},set:(t,s)=>{try{globalThis.S?.set?.(t,s)}catch{}},remove:t=>{try{globalThis.S?.remove?globalThis.S.remove(t):globalThis.S?.set?.(t,null)}catch{}}};async function C(t,s,i,l){const g=l?{"X-Chat-Token":l}:{};let u;try{u=t==="GET"?await H.get(s,{headers:g}):await H.post(s,i,{headers:g})}catch(f){const T=f?.data||f?.response?.data;throw new Error(T?.error||"The chat could not be reached. Check your connection and try again.")}if(u&&u.error)throw new Error(u.error);return u}const le=t=>{const s=t?new Date(t):null;return s&&!Number.isNaN(s.getTime())?s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):""};function oe(t){const s=Array.isArray(t.suggestions)&&t.suggestions.length?[...t.suggestions.map(i=>({key:`${t.n}-${i.i}`,n:t.n,i:i.i,label:i.label})),{key:`${t.n}-none`,n:t.n,i:-1,label:"None of these"}]:[];return{key:`m${t.n}`,n:t.n,from:t.from,cls:`dm-chat-msg dm-chat-msg--${t.from}`,name:t.from==="visitor"?"You":t.name||(t.from==="system"?"":"The team"),text:typeof t.text=="string"?t.text:"",html:typeof t.html=="string"?t.html:"",links:(Array.isArray(t.links)?t.links:[]).map(i=>{const l=/^https?:/i.test(i.url);return{url:i.url,label:i.label,target:l?"_blank":"_self",rel:l?"noopener noreferrer":""}}),choices:s,time:le(t.at)}}const re=`
1
+ import{fillGreeting as ye,launcherChatAccentCss as ke}from"/public/js/launcher-settings.mjs?v=20261110-chat-times-settings";const we={waiting:3e3,open:3e3,bot:9e3,message:2e4},Me=6e3,Te="/public/css/launcher-chat.css?v=20261110-chat-greeting",Z=()=>document.documentElement.classList.contains("dm-reduced-motion")||!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function xe(){if(document.querySelector("link[data-dm-chat-css]"))return;const t=document.createElement("link");t.rel="stylesheet",t.href=Te,t.dataset.dmChatCss="",document.head.appendChild(t)}const ee={get:t=>{try{return globalThis.S?.get?.(t)??null}catch{return null}},set:(t,c)=>{try{globalThis.S?.set?.(t,c)}catch{}},remove:t=>{try{globalThis.S?.remove?globalThis.S.remove(t):globalThis.S?.set?.(t,null)}catch{}}};async function I(t,c,o,n){const p=n?{"X-Chat-Token":n}:{};let r;try{r=t==="GET"?await H.get(c,{headers:p}):await H.post(c,o,{headers:p})}catch(l){const w=l?.data||l?.response?.data;throw new Error(w?.error||"The chat could not be reached. Check your connection and try again.")}if(r&&r.error)throw new Error(r.error);return r}const pe=(t,c="time")=>{if(c==="none")return"";const o=t?new Date(t):null;if(!o||Number.isNaN(o.getTime()))return"";const n=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return c!=="datetime"?n:`${new Date().toDateString()===o.toDateString()?"Today":o.toLocaleDateString([],{day:"numeric",month:"short"})}, ${n}`},te=t=>(String(t||"").trim().match(/[\p{L}\p{N}]/u)?.[0]||"?").toUpperCase();function Ee(t,c=!1,o="",n="time"){const p=Array.isArray(t.suggestions)&&t.suggestions.length?[...t.suggestions.map(l=>({key:`${t.n}-${l.i}`,n:t.n,i:l.i,label:l.label})),{key:`${t.n}-none`,n:t.n,i:-1,label:"None of these"}]:[],r=t.from==="visitor"?"You":t.name||(t.from==="system"?"":"The team");return{key:`m${t.n}`,n:t.n,from:t.from,fresh:c,cls:M.observable(`dm-chat-msg dm-chat-msg--${t.from}`),name:r,initial:te(r),avatar:t.from==="bot"?o:"",text:typeof t.text=="string"?t.text:"",html:typeof t.html=="string"?t.html:"",links:(Array.isArray(t.links)?t.links:[]).map(l=>{const w=/^https?:/i.test(l.url);return{url:l.url,label:l.label,target:w?"_blank":"_self",rel:w?"noopener noreferrer":""}}),choices:p,starters:[],time:pe(t.at,n)}}function Se(t){const c=o=>o?`${o.from}|${o.name}`:"";return t.forEach((o,n)=>{const p=l=>l&&l.from!=="system"&&c(l)===c(o),r=[`dm-chat-msg dm-chat-msg--${o.from}`];o.from!=="system"&&p(t[n-1])&&r.push("is-cont"),o.from!=="system"&&p(t[n+1])&&r.push("has-next"),o.fresh&&r.push("is-new"),o.cls.value=r.join(" ")}),t}const Le=`
2
2
  <div class="dm-chat" data-bind-class="rootClass.value">
3
- <p class="dm-chat-status" data-bind-text="statusText.value"></p>
3
+ <p class="dm-chat-status" data-bind-text="statusText.value" data-bind-hidden="inPanel"></p>
4
4
  <div class="dm-chat-log" role="log" aria-live="polite" aria-relevant="additions" tabindex="0">
5
5
  <div class="dm-chat-items" data-each="items.value key=key"></div>
6
6
  <div class="dm-chat-msg dm-chat-msg--bot dm-chat-typing" data-bind-hidden="!typing.value" aria-hidden="true">
7
+ <span class="dm-chat-avatar"><img class="dm-chat-avatar-img" alt="" data-bind-src="botAvatar.value"><span class="dm-chat-avatar-letter" data-bind-text="botInitial.value"></span></span>
7
8
  <div class="dm-chat-bubble"><span class="dm-chat-dot"></span><span class="dm-chat-dot"></span><span class="dm-chat-dot"></span></div>
8
9
  </div>
9
10
  </div>
@@ -26,22 +27,27 @@ const ae={waiting:3e3,open:3e3,bot:9e3,message:2e4},se=6e3,ne="/public/css/launc
26
27
  </div>
27
28
 
28
29
  <div class="dm-chat-actions" data-bind-hidden="ended.value">
29
- <button type="button" class="dm-chat-action" data-bind-hidden="!canAskPerson.value" data-on-click="askPerson"
30
- data-bind-disabled="busy.value" data-bind-text="personLabel.value"></button>
30
+ <button type="button" class="dm-chat-action" data-bind-hidden="!personBelow.value" data-on-click="askPerson"
31
+ data-bind-disabled="busy.value"><span class="dm-chat-action-icon"><span data-icon="user" data-icon-size="14" aria-hidden="true"></span></span><span data-bind-text="personLabel.value"></span></button>
31
32
  <button type="button" class="dm-chat-action dm-chat-action--end" data-bind-hidden="!hasChat.value" data-on-click="end"
32
33
  data-bind-disabled="busy.value">End chat</button>
33
34
  </div>
34
35
 
35
36
  <form class="dm-chat-compose" data-bind-hidden="ended.value" data-on-submit="send">
36
37
  <input type="text" name="website" class="dm-chat-hp" tabindex="-1" autocomplete="off" aria-hidden="true" data-model="hp.value">
37
- <textarea class="form-input dm-chat-input" rows="1" maxlength="1000" placeholder="Type your message\u2026"
38
- aria-label="Your message" data-model="draft.value" data-bind-disabled="ended.value"></textarea>
39
- <button type="submit" class="btn btn-primary dm-chat-send" aria-label="Send" title="Send"
40
- data-bind-disabled="!canSend.value"><span data-icon="send" data-icon-size="16" aria-hidden="true"></span></button>
38
+ <div class="dm-chat-field-wrap">
39
+ <textarea class="form-input dm-chat-input" rows="1" maxlength="1000" placeholder="Type your message\u2026"
40
+ aria-label="Your message" data-model="draft.value" data-bind-disabled="ended.value"></textarea>
41
+ <button type="submit" class="btn btn-primary dm-chat-send" aria-label="Send" title="Send"
42
+ data-bind-disabled="!canSend.value"><span data-icon="send" data-icon-size="16" aria-hidden="true"></span></button>
43
+ </div>
41
44
  </form>
42
- </div>`,ce=`<div data-bind-class="cls" data-n="{{n}}">
45
+ <p class="dm-chat-foot" data-bind-hidden="ended.value" data-bind-text="footText.value"></p>
46
+ </div>`,Ae=`<div data-bind-class="cls.value" data-n="{{n}}">
47
+ <span class="dm-chat-avatar" aria-hidden="true"><img class="dm-chat-avatar-img" alt="" src="{{avatar}}"><span class="dm-chat-avatar-letter">{{initial}}</span></span>
43
48
  <div class="dm-chat-who"><span>{{name}}</span> <time>{{time}}</time></div>
44
49
  <div class="dm-chat-bubble"><span class="dm-chat-text">{{text}}</span><div class="dm-chat-html">{{{html}}}</div></div>
45
50
  <div class="dm-chat-links">{{#each links key=url}}<a class="dm-chat-link" href="{{url}}" target="{{target}}" rel="{{rel}}">{{label}}</a>{{/each}}</div>
46
51
  <div class="dm-chat-choices">{{#each choices key=key}}<button type="button" class="dm-chat-choice" data-n="{{n}}" data-i="{{i}}">{{label}}</button>{{/each}}</div>
47
- </div>`;export function mountChat(t,{launcherId:s,title:i="Chat",chat:l={}}={}){if(!t||!s||!globalThis.M)return{destroy(){}};ie();const g=`chat:${s}`,u=Date.now(),f="/api/chat",T=`launcher=${encodeURIComponent(s)}`,r=M.observable({greeting:l.greeting||"Hi! How can we help?",botName:l.botName||"Assistant",bot:l.bot!==!1,staff:l.staff!==!1,askDetails:l.askDetails||"offline",staffOnline:!1}),b=M.observable([]),p=M.observable(null),S=M.observable(""),$=M.observable(""),D=M.observable(!1),y=M.observable(!1),L=M.observable(""),E=M.observable(!1),G=M.observable(""),K=M.observable(""),N=M.observable("");let o=B.get(g),k=0,n=!0,w=0,A=0;const c=()=>p.value?.status||"none",O=()=>({key:"greet",n:0,from:"bot",cls:"dm-chat-msg dm-chat-msg--bot",name:r.value.botName,text:r.value.greeting,html:"",links:[],choices:[],time:""}),Q={items:b,draft:S,hp:$,typing:D,busy:y,error:L,detailsName:G,detailsEmail:K,detailsMessage:N,ended:M.computed(()=>E.value||c()==="closed"),hasChat:M.computed(()=>!!p.value&&c()!=="closed"),showDetails:M.computed(()=>!!p.value?.askDetails&&c()!=="closed"),detailsWantsMessage:M.computed(()=>c()==="bot"),detailsIntro:M.computed(()=>c()==="waiting"?"So we can reach you if we get cut off:":"Leave your details and we will get back to you."),canAskPerson:M.computed(()=>{const e=r.value,a=c();return p.value?.askDetails||!(a==="none"||a==="bot")?!1:e.staff||e.askDetails!=="never"}),personLabel:M.computed(()=>r.value.staff?"Talk to a person":"Leave a message"),canSend:M.computed(()=>!y.value&&S.value.trim().length>0&&!(E.value||c()==="closed")),rootClass:M.computed(()=>Y()?"is-still":""),statusText:M.computed(()=>{const e=r.value;switch(c()){case"waiting":return"Waiting for a person - they will reply here.";case"open":return"You are chatting with our team.";case"message":return"Message left - we will get back to you by email.";case"closed":return"Chat ended.";default:return e.bot?`${e.botName} answers straight away${e.staff&&e.staffOnline?" - a person is available too.":"."}`:e.staff?e.staffOnline?"Someone is available to chat.":"Nobody is available right now - leave a message.":""}})};t.innerHTML=re;const v=t.firstElementChild;v.setAttribute("aria-label",i),v.querySelector(".dm-chat-items").innerHTML=ce;const m=v.querySelector(".dm-chat-log"),d=v.querySelector(".dm-chat-input");function W(e){L.value=e,clearTimeout(A),A=setTimeout(()=>{n&&(L.value="")},se)}function F(e=!1){const a=m.scrollHeight-m.scrollTop-m.clientHeight<80;!e&&!a||requestAnimationFrame(()=>{m.scrollTop=m.scrollHeight})}function _(e){if(!n||!e)return;e.token&&(o=e.token,B.set(g,o)),e.state&&(p.value=e.state),typeof e.state?.staffOnline=="boolean"&&(r.value={...r.peek(),staffOnline:e.state.staffOnline});const a=(Array.isArray(e.messages)?e.messages:[]).filter(h=>h.n>k);a.length&&(k=Math.max(k,...a.map(h=>h.n)),b.value=[...b.peek(),...a.map(oe)],F(a.some(h=>h.from==="visitor"))),z()}function z(){if(clearTimeout(w),!n||!o)return;const e=ae[c()];e&&(w=setTimeout(P,e))}async function P(){if(!(!n||!o)){if(document.hidden||!v.isConnected){z();return}try{const e=await C("GET",`${f}/state?${T}&after=${k}`,null,o);if(!n)return;if(!e.state){q();return}_(e)}catch{clearTimeout(w),n&&(w=setTimeout(P,15e3))}}}function q(){o=null,B.remove(g),p.value=null,k=0,b.value=[O()]}async function x(e,a,{thinking:h=!1}={}){if(y.peek())return!1;y.value=!0,L.value="",h&&!Y()&&(D.value=!0);const ee=Date.now();try{const R=await C("POST",`${f}/${e}`,{launcher:s,after:k,...a},o);if(h&&!Y()){const J=450-(Date.now()-ee);J>0&&await new Promise(te=>setTimeout(te,J))}return _(R),!0}catch(R){return n&&W(R.message),!1}finally{n&&(y.value=!1,D.value=!1)}}async function I(){const e=S.peek().trim();return!e||y.peek()||E.peek()||await x("send",{text:e,page:location.pathname,_hp:$.peek(),_t:u},{thinking:!0})&&(S.value="",d.focus()),!1}const Z=M.applyBindings(Q,v,{methods:{send:()=>(I(),!1),sendDetails:()=>(x("details",{name:G.peek(),email:K.peek(),message:N.peek()}).then(e=>{e&&(N.value="")}),!1),askPerson:()=>x("person",{page:location.pathname,_hp:$.peek(),_t:u},{thinking:!0}),end:async()=>{o&&await x("end",{})&&(E.value=!0,clearTimeout(w))},restart:()=>{E.value=!1,q(),d.focus()}}});window.Domma?.icons?.scan?.(v);const U=e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),I())};d.addEventListener("keydown",U);const V=()=>{d.style.height="auto",d.style.height=Math.min(d.scrollHeight,120)+"px"};d.addEventListener("input",V);const X=e=>{const a=e.target.closest(".dm-chat-choice");!a||!m.contains(a)||x("pick",{n:Number(a.dataset.n),i:Number(a.dataset.i)},{thinking:!0})};m.addEventListener("click",X);const j=()=>{!document.hidden&&n&&o&&P()};return document.addEventListener("visibilitychange",j),b.value=[O()],(async()=>{try{const e=await C("GET",`${f}/config?${T}`);if(!n)return;r.value={...r.peek(),...e},p.peek()||(b.value=[O(),...b.peek().filter(a=>a.key!=="greet")])}catch(e){n&&W(e.message)}if(!(!o||!n))try{const e=await C("GET",`${f}/state?${T}&after=0`,null,o);if(!n)return;if(!e.state){q();return}_(e),F(!0)}catch{}})(),{destroy(){n&&(n=!1,clearTimeout(w),clearTimeout(A),d.removeEventListener("keydown",U),d.removeEventListener("input",V),m.removeEventListener("click",X),document.removeEventListener("visibilitychange",j),Z?.dispose?.(),t.innerHTML="")}}}
52
+ <div class="dm-chat-choices dm-chat-starters">{{#each starters key=key}}<button type="button" class="dm-chat-choice dm-chat-starter" data-text="{{text}}">{{text}}</button>{{/each}}</div>
53
+ </div>`;export function mountChat(t,{launcherId:c,title:o="Chat",chat:n={}}={}){if(!t||!c||!globalThis.M)return{destroy(){}};xe();const p=`chat:${c}`,r=Date.now(),l="/api/chat",w=`launcher=${encodeURIComponent(c)}`,i=M.observable({greeting:n.greeting||"Hi! How can we help?",botName:n.botName||"Assistant",bot:n.bot!==!1,staff:n.staff!==!1,askDetails:n.askDetails||"offline",staffOnline:!1,ai:!1,accent:n.accent||"",accentText:n.accentText||"",avatar:n.avatar||"",starters:Array.isArray(n.starters)?n.starters:[],personButton:n.personButton==="header"?"header":"below",times:["time","datetime","none"].includes(n.times)?n.times:"time"}),C=M.observable([]),v=M.observable(null),L=M.observable(""),$=M.observable(""),R=M.observable(!1),T=M.observable(!1),N=M.observable(""),A=M.observable(!1),ae=M.observable(""),se=M.observable(""),z=M.observable("");let f=ee.get(p),x=0,d=!0,E=0,G=0,Y=!1;const b=()=>v.value?.status||"none",K=()=>({key:"greet",n:0,from:"bot",fresh:!1,cls:M.observable("dm-chat-msg dm-chat-msg--bot"),name:i.value.botName,initial:te(i.value.botName),avatar:i.value.avatar||"",text:ye(i.value.greeting,{botName:i.value.botName,site:globalThis.__CMS_SITE__?.title||""}),html:"",links:[],choices:[],time:pe(new Date(r).toISOString(),i.value.times),starters:v.peek()?[]:(i.value.starters||[]).map((e,a)=>({key:`s${a}`,text:e}))}),B=e=>{C.value=Se(e)},h=t.closest?.(".dm-launcher-chat")?.querySelector(".dm-launcher-chat-head")||null,W=()=>{const e=i.value,a=b();return v.value?.askDetails||!(a==="none"||a==="bot")?!1:e.staff||e.askDetails!=="never"},fe=M.computed(W),D={items:C,draft:L,hp:$,typing:R,busy:T,error:N,detailsName:ae,detailsEmail:se,detailsMessage:z,ended:M.computed(()=>A.value||b()==="closed"),hasChat:M.computed(()=>!!v.value&&b()!=="closed"),showDetails:M.computed(()=>!!v.value?.askDetails&&b()!=="closed"),detailsWantsMessage:M.computed(()=>b()==="bot"),detailsIntro:M.computed(()=>b()==="waiting"?"So we can reach you if we get cut off:":"Leave your details and we will get back to you."),canAskPerson:fe,personLabel:M.computed(()=>i.value.staff?"Talk to a person":"Leave a message"),personBelow:M.computed(()=>W()&&!(h&&i.value.personButton==="header")),personInHead:M.computed(()=>W()&&!!h&&i.value.personButton==="header"),canSend:M.computed(()=>!T.value&&L.value.trim().length>0&&!(A.value||b()==="closed")),rootClass:M.computed(()=>[Z()?"is-still":"",v.value?"has-chat":""].filter(Boolean).join(" ")),inPanel:!!h,botInitial:M.computed(()=>te(i.value.botName)),botAvatar:M.computed(()=>i.value.avatar||""),footText:M.computed(()=>{const e=i.value;return!e.bot||!(b()==="none"||b()==="bot")?"":e.ai?`${e.botName} is an AI assistant and can get things wrong.`:`${e.botName} is an automated assistant.`}),online:M.computed(()=>{const e=i.value,a=b();return a==="open"?!0:a==="closed"||a==="message"?!1:e.bot||e.staff&&e.staffOnline}),statusText:M.computed(()=>{const e=i.value;switch(b()){case"waiting":return"Waiting for a person - they will reply here.";case"open":return"You are chatting with our team.";case"message":return"Message left - we will get back to you by email.";case"closed":return"Chat ended.";default:return e.bot?`${e.botName} answers straight away${e.staff&&e.staffOnline?" - a person is available too.":"."}`:e.staff?e.staffOnline?"Someone is available to chat.":"Nobody is available right now - leave a message.":""}})};t.innerHTML=Le;const g=t.firstElementChild;g.setAttribute("aria-label",o),g.querySelector(".dm-chat-items").innerHTML=Ae;const m=g.querySelector(".dm-chat-log"),y=g.querySelector(".dm-chat-input");function ne(e){N.value=e,clearTimeout(G),G=setTimeout(()=>{d&&(N.value="")},Me)}let O=!0;const ie=()=>m.scrollHeight-m.scrollTop-m.clientHeight<80;function oe(e=!1){!e&&!O&&!ie()||(O=!0,requestAnimationFrame(()=>{m.scrollTop=m.scrollHeight}))}function j(e){if(!d||!e)return;e.token&&(f=e.token,ee.set(p,f)),e.state&&(v.value=e.state),typeof e.state?.staffOnline=="boolean"&&(i.value={...i.peek(),staffOnline:e.state.staffOnline});const a=(Array.isArray(e.messages)?e.messages:[]).filter(s=>s.n>x);a.length&&(x=Math.max(x,...a.map(s=>s.n)),B([...C.peek(),...a.map(s=>Ee(s,Y,i.peek().avatar,i.peek().times))]),oe(a.some(s=>s.from==="visitor"))),re()}function re(){if(clearTimeout(E),!d||!f)return;const e=we[b()];e&&(E=setTimeout(F,e))}async function F(){if(!(!d||!f)){if(document.hidden||!g.isConnected){re();return}try{const e=await I("GET",`${l}/state?${w}&after=${x}`,null,f);if(!d)return;if(!e.state){U();return}j(e)}catch{clearTimeout(E),d&&(E=setTimeout(F,15e3))}}}function U(){f=null,ee.remove(p),v.value=null,x=0,B([K()])}async function S(e,a,{thinking:s=!1}={}){if(T.peek())return!1;T.value=!0,N.value="",s&&!Z()&&(R.value=!0);const k=Date.now();try{const u=await I("POST",`${l}/${e}`,{launcher:c,after:x,...a},f);if(s&&!Z()){const q=450-(Date.now()-k);q>0&&await new Promise(Q=>setTimeout(Q,q))}return j(u),!0}catch(u){return d&&ne(u.message),!1}finally{d&&(T.value=!1,R.value=!1)}}async function V(){const e=L.peek().trim();if(!e||T.peek()||A.peek())return!1;if(!f){const s=1700-(Date.now()-r);if(s>0&&await new Promise(k=>setTimeout(k,s)),!d)return!1}return await S("send",{text:e,page:location.pathname,_hp:$.peek(),_t:r},{thinking:!0})&&(L.value="",y.focus()),!1}const _=h?h.closest(".dm-launcher-chat"):g,X=M.effect(()=>{const e=ke(i.value);for(const[a,s]of[["--chat-accent",e.accent],["--chat-accent-text",e.accentText]])s?_.style.setProperty(a,s):_.style.removeProperty(a)}),be=M.applyBindings(D,g,{methods:{send:()=>(V(),!1),sendDetails:()=>(S("details",{name:ae.peek(),email:se.peek(),message:z.peek()}).then(e=>{e&&(z.value="")}),!1),askPerson:()=>S("person",{page:location.pathname,_hp:$.peek(),_t:r},{thinking:!0}),end:async()=>{f&&await S("end",{})&&(A.value=!0,clearTimeout(E))},restart:()=>{A.value=!1,U(),y.focus()}}});window.Domma?.icons?.scan?.(g);let P=null,le=[];if(h){const e=h.querySelector(".dm-launcher-chat-title"),a=document.createElement("span");a.className="dm-launcher-chat-avatar",a.setAttribute("aria-hidden","true"),a.innerHTML='<img class="dm-chat-avatar-img" alt="" data-bind-src="botAvatar.value"><span class="dm-chat-avatar-letter" data-bind-text="botInitial.value"></span>',a.setAttribute("data-bind-class","online.value ? 'is-online' : ''");const s=document.createElement("span");s.className="dm-launcher-chat-heading";const k=document.createElement("span");k.className="dm-launcher-chat-sub",k.setAttribute("data-bind-text","statusText.value"),h.insertBefore(a,h.firstChild),e?(h.insertBefore(s,e),s.appendChild(e)):h.insertBefore(s,a.nextSibling),s.appendChild(k);const u=document.createElement("button");u.type="button",u.className="dm-launcher-chat-person",u.setAttribute("data-bind-hidden","!personInHead.value"),u.setAttribute("data-bind-title","personLabel.value"),u.setAttribute("data-bind-aria-label","personLabel.value"),u.setAttribute("data-bind-disabled","busy.value"),u.innerHTML='<span data-icon="headphones" data-icon-size="18" aria-hidden="true"></span>',h.insertBefore(u,h.querySelector(".dm-launcher-chat-close")),u.addEventListener("click",()=>S("person",{page:location.pathname,_hp:$.peek(),_t:r},{thinking:!0})),window.Domma?.icons?.scan?.(u),le=[a,k,u],P=M.applyBindings(D,a)||null;const q=M.applyBindings(D,k),Q=M.applyBindings(D,u),ve=[P,q,Q];P={dispose:()=>ve.forEach(ge=>ge?.dispose?.())}}const ce=e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),V())};y.addEventListener("keydown",ce);const de=()=>{y.style.height="auto",y.style.height=Math.min(y.scrollHeight,120)+"px"};y.addEventListener("input",de);const ue=e=>{const a=e.target.closest(".dm-chat-starter");if(a&&m.contains(a)){L.value=a.dataset.text||"",V();return}const s=e.target.closest(".dm-chat-choice");!s||!m.contains(s)||S("pick",{n:Number(s.dataset.n),i:Number(s.dataset.i)},{thinking:!0})};m.addEventListener("click",ue);const me=()=>{O=ie()};m.addEventListener("scroll",me,{passive:!0});const J=typeof ResizeObserver=="function"?new ResizeObserver(()=>{O&&(m.scrollTop=m.scrollHeight)}):null;J?.observe(m),J?.observe(g.querySelector(".dm-chat-items"));const he=()=>{!document.hidden&&d&&f&&F()};return document.addEventListener("visibilitychange",he),B([K()]),(async()=>{try{const e=await I("GET",`${l}/config?${w}`);if(!d)return;i.value={...i.peek(),...e},v.peek()||B([K(),...C.peek().filter(a=>a.key!=="greet")])}catch(e){d&&ne(e.message)}if(!f||!d){Y=!0;return}try{const e=await I("GET",`${l}/state?${w}&after=0`,null,f);if(!d)return;if(!e.state){U();return}j(e),oe(!0)}catch{}Y=!0})(),{destroy(){d&&(d=!1,clearTimeout(E),clearTimeout(G),y.removeEventListener("keydown",ce),y.removeEventListener("input",de),m.removeEventListener("click",ue),m.removeEventListener("scroll",me),J?.disconnect(),document.removeEventListener("visibilitychange",he),be?.dispose?.(),P?.dispose?.(),X?.dispose?.(),typeof X=="function"&&X(),_.style.removeProperty("--chat-accent"),_.style.removeProperty("--chat-accent-text"),le.forEach(e=>e.remove()),t.innerHTML="")}}}
@@ -1,2 +1,6 @@
1
- import{cssClasses as x}from"./css-classes.mjs";export const LAUNCHER_POSITIONS=["TL","TC","TR","ML","MR","BL","BC","BR"],LAUNCHER_POSITION_LABEL={TL:"Top left",TC:"Top centre",TR:"Top right",ML:"Middle left",MR:"Middle right",BL:"Bottom left",BC:"Bottom centre",BR:"Bottom right"},LAUNCHER_TRIGGER_STYLES=["icon","icon-text"],LAUNCHER_TOOLTIP_MODES=["label","custom","off"],LAUNCHER_DEVICES=["all","desktop","phone"],LAUNCHER_AUDIENCES=["everyone","signed-in","signed-out"],LAUNCHER_PAGE_MODES=["all","only","except"],LAUNCHER_ACTIONS=["modal","slideover","chat"],LAUNCHER_MODAL_KINDS=["page","form","block"],LAUNCHER_SLIDEOVER_KINDS=["page","form","block"],LAUNCHER_MODAL_SIZES=["xs","sm","md","lg","xl","xxl","full","screen","custom"],LAUNCHER_MODAL_HEIGHTS=["auto","sm","md","lg","full","custom"],LAUNCHER_WIDTH_UNITS=["px","%"],LAUNCHER_HEIGHT_UNITS=["px","vh"],LAUNCHER_MODAL_WIDTH_CSS=Object.freeze({xs:"320px",sm:"400px",md:"600px",lg:"800px",xl:"1140px",xxl:"1400px",full:"90vw"}),LAUNCHER_MODAL_HEIGHT_CSS=Object.freeze({sm:"40vh",md:"60vh",lg:"80vh",full:"90vh"}),LAUNCHER_SLIDEOVER_WIDTHS=["sm","md","lg","xl"],LAUNCHER_SIDES=["left","right"],LAUNCHER_ASK_DETAILS=["offline","always","never"],LAUNCHER_TOKENS=["primary","secondary","success","danger","warning","info","surface","text","background"],LAUNCHER_LIMITS=Object.freeze({nameMax:60,labelMax:40,tooltipMax:120,titleMax:80,iconMax:40,idMax:40,sizeMin:32,sizeMax:96,offsetMax:500,pathsMax:50,pathMax:200,greetingMax:300,botNameMax:40,widthPx:[240,2400],widthPct:[20,100],heightPx:[160,2e3],heightVh:[20,100]}),LAUNCHER_DEFAULTS=Object.freeze({enabled:!0,showDisc:!0,name:"New launcher",label:"Open",tooltipMode:"label",tooltip:"",icon:"message-circle",triggerStyle:"icon",position:"BR",offsetX:32,offsetY:32,size:52,radius:26,devices:"all",phone:Object.freeze({override:!1,position:"BR",offsetX:16,offsetY:16,size:48}),colours:Object.freeze({background:"",text:""}),class:"",pages:Object.freeze({mode:"all",paths:Object.freeze([])}),audience:"everyone",action:Object.freeze({type:"modal",kind:"page",ref:"",title:"",size:"lg",side:"right",width:"md",customWidth:900,widthUnit:"px",height:"auto",customHeight:70,heightUnit:"vh"}),chat:Object.freeze({greeting:"Hi! How can we help?",botName:"Assistant",bot:!0,staff:!0,askDetails:"offline"})});const c=(e,t,o)=>t.includes(e)?e:o;function p(e,t,o,i){const s=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(s)?Math.min(i,Math.max(o,Math.round(s))):Math.min(i,Math.max(o,t))}function g(e,t,o=""){return typeof e!="string"?o:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||o}const l=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};export const LAUNCHER_ID_RE=/^[a-z0-9][a-z0-9-]{0,39}$/;const m=/^[a-z0-9][a-z0-9-]{0,39}$/,_=/^\/[A-Za-z0-9._~\-/]*$/,M=/^[a-z0-9][a-z0-9_-]{0,99}$/i;export function launcherColour(e){if(typeof e!="string")return"";const t=e.trim().toLowerCase();return LAUNCHER_TOKENS.includes(t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)?t:""}export function launcherColourCss(e){const t=launcherColour(e);return t?LAUNCHER_TOKENS.includes(t)?`var(--dm-${t})`:t:""}export function normaliseLauncherPath(e){if(typeof e!="string")return"";let t=e.trim().split(/[?#]/)[0].replace(/\s+/g,"");return!t||(t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/"),t.length>1&&(t=t.replace(/\/+$/,"")),t.length>LAUNCHER_LIMITS.pathMax||!/^\/[A-Za-z0-9._~\-/*]*$/.test(t))?"":t}export function launcherPathMatches(e,t){const o=normaliseLauncherPath(e||"/")||"/",i=normaliseLauncherPath(t);return i?i.endsWith("/*")&&o===(i.slice(0,-2)||"/")?!0:new RegExp("^"+i.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(o):!1}export function launcherShowsOn(e,t,o){if(!e||e.enabled===!1||e.audience==="signed-in"&&!o||e.audience==="signed-out"&&o)return!1;const i=e.pages.paths.some(s=>launcherPathMatches(t,s));return e.pages.mode==="only"?i:e.pages.mode==="except"?!i:!0}function b(e,t){const o=l(e);return{override:o.override===!0,position:c(o.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:p(o.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:p(o.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:p(o.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function L(e){const t=l(e),o=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),i=o==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,s=o==="chat"?"page":c(t.kind,i,"page");let n=typeof t.ref=="string"?t.ref.trim():"";s==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):M.test(n)||(n=""),o==="chat"&&(n="");const r=LAUNCHER_DEFAULTS.action,a=c(t.widthUnit,LAUNCHER_WIDTH_UNITS,r.widthUnit),f=c(t.heightUnit,LAUNCHER_HEIGHT_UNITS,r.heightUnit);return{type:o,kind:s,ref:n,title:g(t.title,LAUNCHER_LIMITS.titleMax),size:c(t.size,LAUNCHER_MODAL_SIZES,r.size),side:c(t.side,LAUNCHER_SIDES,r.side),width:c(t.width,LAUNCHER_SLIDEOVER_WIDTHS,r.width),customWidth:p(t.customWidth,a==="%"?90:r.customWidth,...a==="%"?LAUNCHER_LIMITS.widthPct:LAUNCHER_LIMITS.widthPx),widthUnit:a,height:c(t.height,LAUNCHER_MODAL_HEIGHTS,r.height),customHeight:p(t.customHeight,f==="px"?600:r.customHeight,...f==="px"?LAUNCHER_LIMITS.heightPx:LAUNCHER_LIMITS.heightVh),heightUnit:f}}export function launcherModalBox(e){const t=e||LAUNCHER_DEFAULTS.action;if(t.size==="screen")return{width:"100vw",height:"100vh",screen:!0};const o=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,i=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:o,height:i,screen:!1}}export function normaliseLauncherChat(e){const t=l(e),o=LAUNCHER_DEFAULTS.chat;return{greeting:typeof t.greeting=="string"?t.greeting.replace(/\r\n?/g,`
2
- `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").trim().slice(0,LAUNCHER_LIMITS.greetingMax):o.greeting,botName:g(t.botName,LAUNCHER_LIMITS.botNameMax,o.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,o.askDetails)}}export function normaliseLauncher(e){const t=l(e),o=LAUNCHER_DEFAULTS,i=p(t.size,o.size,LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax),s=Math.floor(i/2),n=l(t.pages),r=(Array.isArray(n.paths)?n.paths:typeof n.paths=="string"?n.paths.split(/[\n,]+/):[]).map(normaliseLauncherPath).filter(Boolean).filter((f,u,h)=>h.indexOf(f)===u).slice(0,LAUNCHER_LIMITS.pathsMax),a=l(t.colours);return{id:typeof t.id=="string"&&LAUNCHER_ID_RE.test(t.id)?t.id:"",enabled:t.enabled!==!1,showDisc:t.showDisc!==!1,name:g(t.name,LAUNCHER_LIMITS.nameMax,o.name),label:g(t.label,LAUNCHER_LIMITS.labelMax,o.label),tooltipMode:c(t.tooltipMode,LAUNCHER_TOOLTIP_MODES,o.tooltipMode),tooltip:g(t.tooltip,LAUNCHER_LIMITS.tooltipMax,""),icon:typeof t.icon=="string"&&m.test(t.icon.trim())?t.icon.trim():o.icon,triggerStyle:c(t.triggerStyle,LAUNCHER_TRIGGER_STYLES,o.triggerStyle),position:c(t.position,LAUNCHER_POSITIONS,o.position),offsetX:p(t.offsetX,o.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:p(t.offsetY,o.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:i,radius:Math.min(s,p(t.radius,o.radius,0,s)),devices:c(t.devices,LAUNCHER_DEVICES,o.devices),phone:b(t.phone,i),colours:{background:launcherColour(a.background),text:launcherColour(a.text)},class:x(typeof t.class=="string"?t.class:"").join(" "),pages:{mode:c(n.mode,LAUNCHER_PAGE_MODES,o.pages.mode),paths:r},audience:c(t.audience,LAUNCHER_AUDIENCES,o.audience),action:L(t.action),chat:normaliseLauncherChat(t.chat)}}export function launcherTooltip(e){return!e||e.tooltipMode==="off"?"":e.tooltipMode==="custom"?e.tooltip||e.label:e.triggerStyle==="icon-text"?"":e.label}export function launcherHref(e){return`#launcher-${e}`}export function newLauncherId(e=new Set,t=Math.random){for(let o=0;o<1e3;o++){const i="l-"+Math.floor(t()*2176782336).toString(36).padStart(6,"0");if(!e.has(i))return i}return"l-"+Date.now().toString(36)}export function normaliseLaunchers(e,t=Math.random){const o=Array.isArray(e)?e:Array.isArray(e?.launchers)?e.launchers:[],i=new Set;return o.filter(s=>s&&typeof s=="object"&&!Array.isArray(s)).map(s=>{const n=normaliseLauncher(s);return(!n.id||i.has(n.id))&&(n.id=newLauncherId(i,t)),i.add(n.id),n})}export function launcherReady(e){return e?e.action.type==="chat"?!0:!!e.action.ref:!1}export function publicLauncher(e){const t={id:e.id,disc:e.showDisc,label:e.label,tooltip:launcherTooltip(e),icon:e.icon,triggerStyle:e.triggerStyle,position:e.position,offsetX:e.offsetX,offsetY:e.offsetY,size:e.size,radius:e.radius,devices:e.devices,phone:e.phone,colours:{background:launcherColourCss(e.colours.background),text:launcherColourCss(e.colours.text)},class:e.class,action:{type:e.action.type,title:e.action.title||e.label,size:e.action.size,side:e.action.side,width:e.action.width,customWidth:e.action.customWidth,widthUnit:e.action.widthUnit,height:e.action.height,customHeight:e.action.customHeight,heightUnit:e.action.heightUnit}};return e.action.type==="chat"&&(t.chat={...e.chat}),t}export function launcherSpot(e,{w:t,h:o,vw:i,vh:s,offsetX:n,offsetY:r}){const a=e[1]==="L"?"L":e[1]==="R"?"R":"C",f=e[0],u=a==="L"?n:a==="R"?i-t-n:Math.round((i-t)/2+n),h=f==="T"?r:f==="B"?s-o-r:Math.round((s-o)/2+r);return{left:u,top:h}}const d=12,E=(e,t)=>e.left<t.right+d&&t.left<e.right+d&&e.top<t.bottom+d&&t.top<e.bottom+d;export function launcherStack(e,t,{w:o,h:i},s){const n=e[0]==="B";let r=t.top;for(let a=0;a<=s.length;a++){const f={left:t.left,top:r,right:t.left+o,bottom:r+i},u=s.find(h=>h&&h.right>h.left&&h.bottom>h.top&&E(f,h));if(!u)break;r=Math.round(n?u.top-d-i:u.bottom+d)}return{left:t.left,top:r}}
1
+ import{cssClasses as M}from"./css-classes.mjs";export const LAUNCHER_POSITIONS=["TL","TC","TR","ML","MR","BL","BC","BR"],LAUNCHER_POSITION_LABEL={TL:"Top left",TC:"Top centre",TR:"Top right",ML:"Middle left",MR:"Middle right",BL:"Bottom left",BC:"Bottom centre",BR:"Bottom right"},LAUNCHER_TRIGGER_STYLES=["icon","icon-text"],LAUNCHER_TOOLTIP_MODES=["label","custom","off"],LAUNCHER_DEVICES=["all","desktop","phone"],LAUNCHER_AUDIENCES=["everyone","signed-in","signed-out"],LAUNCHER_PAGE_MODES=["all","only","except"],LAUNCHER_ACTIONS=["modal","slideover","chat"],LAUNCHER_MODAL_KINDS=["page","form","block"],LAUNCHER_SLIDEOVER_KINDS=["page","form","block"],LAUNCHER_MODAL_SIZES=["xs","sm","md","lg","xl","xxl","full","screen","custom"],LAUNCHER_MODAL_HEIGHTS=["auto","sm","md","lg","full","custom"],LAUNCHER_WIDTH_UNITS=["px","%"],LAUNCHER_HEIGHT_UNITS=["px","vh"],LAUNCHER_MODAL_WIDTH_CSS=Object.freeze({xs:"320px",sm:"400px",md:"600px",lg:"800px",xl:"1140px",xxl:"1400px",full:"90vw"}),LAUNCHER_MODAL_HEIGHT_CSS=Object.freeze({sm:"40vh",md:"60vh",lg:"80vh",full:"90vh"}),LAUNCHER_SLIDEOVER_WIDTHS=["sm","md","lg","xl"],LAUNCHER_SIDES=["left","right"],LAUNCHER_ASK_DETAILS=["offline","always","never"],LAUNCHER_TOKENS=["primary","secondary","success","danger","warning","info","surface","text","background"],LAUNCHER_LIMITS=Object.freeze({nameMax:60,labelMax:40,tooltipMax:120,titleMax:80,iconMax:40,idMax:40,sizeMin:32,sizeMax:96,offsetMax:500,pathsMax:50,pathMax:200,greetingMax:300,botNameMax:40,aiContextMax:4e3,aiRulesMax:2e3,avatarMax:300,chatWidth:[300,720],chatHeight:[380,900],startersMax:4,starterMax:80,aiMaxPerChat:[0,100],keepDays:[0,730],widthPx:[240,2400],widthPct:[20,100],heightPx:[160,2e3],heightVh:[20,100]}),LAUNCHER_DEFAULTS=Object.freeze({enabled:!0,showDisc:!0,name:"New launcher",label:"Open",tooltipMode:"label",tooltip:"",icon:"message-circle",triggerStyle:"icon",position:"BR",offsetX:32,offsetY:32,size:52,radius:26,devices:"all",phone:Object.freeze({override:!1,position:"BR",offsetX:16,offsetY:16,size:48}),colours:Object.freeze({background:"",text:""}),class:"",pages:Object.freeze({mode:"all",paths:Object.freeze([])}),audience:"everyone",action:Object.freeze({type:"modal",kind:"page",ref:"",title:"",size:"lg",side:"right",width:"md",customWidth:900,widthUnit:"px",height:"auto",customHeight:70,heightUnit:"vh"}),chat:Object.freeze({greeting:"Hi! How can we help?",botName:"Della",bot:!0,staff:!0,askDetails:"offline",ai:!0,aiUseSite:!0,aiContext:"",aiRules:"",accent:"",accentText:"",avatar:"",size:"md",width:400,height:600,resizable:!0,starters:Object.freeze([]),aiMaxPerChat:20,personButton:"below",keepDays:0,times:"time"})});const c=(e,t,i)=>t.includes(e)?e:i;function f(e,t,i,o){const r=typeof e=="number"?e:typeof e=="string"&&e.trim()?Number(e):NaN;return Number.isFinite(r)?Math.min(o,Math.max(i,Math.round(r))):Math.min(o,Math.max(i,t))}function l(e,t,i=""){return typeof e!="string"?i:e.replace(/[\u0000-\u001f\u007f]/g," ").trim().replace(/\s+/g," ").slice(0,t)||i}const d=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{};export const LAUNCHER_ID_RE=/^[a-z0-9][a-z0-9-]{0,39}$/;const b=/^[a-z0-9][a-z0-9-]{0,39}$/,A=/^\/[A-Za-z0-9._~\-/]*$/,y=/^[a-z0-9][a-z0-9_-]{0,99}$/i;export function launcherColour(e){if(typeof e!="string")return"";const t=e.trim().toLowerCase();return LAUNCHER_TOKENS.includes(t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)?t:""}export function launcherColourCss(e){const t=launcherColour(e);return t?LAUNCHER_TOKENS.includes(t)?`var(--dm-${t})`:t:""}export function normaliseLauncherPath(e){if(typeof e!="string")return"";let t=e.trim().split(/[?#]/)[0].replace(/\s+/g,"");return!t||(t.startsWith("/")||(t="/"+t),t=t.replace(/\/{2,}/g,"/"),t.length>1&&(t=t.replace(/\/+$/,"")),t.length>LAUNCHER_LIMITS.pathMax||!/^\/[A-Za-z0-9._~\-/*]*$/.test(t))?"":t}export function launcherPathMatches(e,t){const i=normaliseLauncherPath(e||"/")||"/",o=normaliseLauncherPath(t);return o?o.endsWith("/*")&&i===(o.slice(0,-2)||"/")?!0:new RegExp("^"+o.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","i").test(i):!1}export function launcherShowsOn(e,t,i){if(!e||e.enabled===!1||e.audience==="signed-in"&&!i||e.audience==="signed-out"&&i)return!1;const o=e.pages.paths.some(r=>launcherPathMatches(t,r));return e.pages.mode==="only"?o:e.pages.mode==="except"?!o:!0}function C(e,t){const i=d(e);return{override:i.override===!0,position:c(i.position,LAUNCHER_POSITIONS,LAUNCHER_DEFAULTS.phone.position),offsetX:f(i.offsetX,LAUNCHER_DEFAULTS.phone.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(i.offsetY,LAUNCHER_DEFAULTS.phone.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:f(i.size,Math.min(t,LAUNCHER_DEFAULTS.phone.size),LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax)}}function E(e){const t=d(e),i=c(t.type,LAUNCHER_ACTIONS,LAUNCHER_DEFAULTS.action.type),o=i==="modal"?LAUNCHER_MODAL_KINDS:LAUNCHER_SLIDEOVER_KINDS,r=i==="chat"?"page":c(t.kind,o,"page");let n=typeof t.ref=="string"?t.ref.trim():"";r==="page"?(n=n?normaliseLauncherPath(n):"",n.includes("*")&&(n="")):y.test(n)||(n=""),i==="chat"&&(n="");const s=LAUNCHER_DEFAULTS.action,h=c(t.widthUnit,LAUNCHER_WIDTH_UNITS,s.widthUnit),a=c(t.heightUnit,LAUNCHER_HEIGHT_UNITS,s.heightUnit);return{type:i,kind:r,ref:n,title:l(t.title,LAUNCHER_LIMITS.titleMax),size:c(t.size,LAUNCHER_MODAL_SIZES,s.size),side:c(t.side,LAUNCHER_SIDES,s.side),width:c(t.width,LAUNCHER_SLIDEOVER_WIDTHS,s.width),customWidth:f(t.customWidth,h==="%"?90:s.customWidth,...h==="%"?LAUNCHER_LIMITS.widthPct:LAUNCHER_LIMITS.widthPx),widthUnit:h,height:c(t.height,LAUNCHER_MODAL_HEIGHTS,s.height),customHeight:f(t.customHeight,a==="px"?600:s.customHeight,...a==="px"?LAUNCHER_LIMITS.heightPx:LAUNCHER_LIMITS.heightVh),heightUnit:a}}export function launcherModalBox(e){const t=e||LAUNCHER_DEFAULTS.action;if(t.size==="screen")return{width:"100vw",height:"100vh",screen:!0};const i=t.size==="custom"?t.widthUnit==="%"?`${t.customWidth}vw`:`${t.customWidth}px`:LAUNCHER_MODAL_WIDTH_CSS[t.size]||LAUNCHER_MODAL_WIDTH_CSS.lg,o=t.height==="custom"?`${t.customHeight}${t.heightUnit==="px"?"px":"vh"}`:LAUNCHER_MODAL_HEIGHT_CSS[t.height]||"";return{width:i,height:o,screen:!1}}export function normaliseLauncherChat(e){const t=d(e),i=LAUNCHER_DEFAULTS.chat;return{greeting:typeof t.greeting=="string"?t.greeting.replace(/\r\n?/g,`
2
+ `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").trim().slice(0,LAUNCHER_LIMITS.greetingMax):i.greeting,botName:l(t.botName,LAUNCHER_LIMITS.botNameMax,i.botName),bot:t.bot!==!1,staff:t.staff!==!1,askDetails:c(t.askDetails,LAUNCHER_ASK_DETAILS,i.askDetails),ai:t.ai!==!1,aiUseSite:t.aiUseSite!==!1,aiContext:m(t.aiContext,LAUNCHER_LIMITS.aiContextMax),aiRules:m(t.aiRules,LAUNCHER_LIMITS.aiRulesMax),accent:launcherColour(t.accent),accentText:launcherColour(t.accentText),avatar:launcherAvatar(t.avatar),size:c(t.size,LAUNCHER_CHAT_SIZES,i.size),width:f(t.width,i.width,...LAUNCHER_LIMITS.chatWidth),height:f(t.height,i.height,...LAUNCHER_LIMITS.chatHeight),resizable:t.resizable!==!1,starters:(Array.isArray(t.starters)?t.starters:typeof t.starters=="string"?t.starters.split(`
3
+ `):[]).map(r=>l(r,LAUNCHER_LIMITS.starterMax)).filter(Boolean).slice(0,LAUNCHER_LIMITS.startersMax),aiMaxPerChat:f(t.aiMaxPerChat,i.aiMaxPerChat,...LAUNCHER_LIMITS.aiMaxPerChat),personButton:c(t.personButton,LAUNCHER_PERSON_BUTTON,i.personButton),keepDays:f(t.keepDays,i.keepDays,...LAUNCHER_LIMITS.keepDays),times:c(t.times,LAUNCHER_CHAT_TIMES,i.times)}}export const LAUNCHER_PERSON_BUTTON=["below","header"],LAUNCHER_CHAT_TIMES=["time","datetime","none"],GREETING_PLACEHOLDERS=["greeting","timeofday","day","date","time","botname","site"];export function fillGreeting(e,{now:t=new Date,botName:i="",site:o=""}={}){const r=t.getHours(),n=r<12?"morning":r<18?"afternoon":"evening",s={greeting:`Good ${n}`,timeofday:n,day:t.toLocaleDateString("en-GB",{weekday:"long"}),date:t.toLocaleDateString("en-GB",{day:"numeric",month:"long"}),time:t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),botname:i,site:o};return String(e??"").replace(/\{\s*([a-z]+)\s*\}/gi,(h,a)=>{const u=s[a.toLowerCase()];return u===void 0?h:u})}export const LAUNCHER_CHAT_SIZES=["sm","md","lg","custom"];const x={sm:[340,500],md:[400,600],lg:[480,720]};export function launcherChatBox(e={}){if(e.size==="custom")return{width:f(e.width,400,...LAUNCHER_LIMITS.chatWidth),height:f(e.height,600,...LAUNCHER_LIMITS.chatHeight)};const[t,i]=x[e.size]||x.md;return{width:t,height:i}}export function launcherAvatar(e){if(typeof e!="string")return"";const t=e.trim();return!t||t.length>LAUNCHER_LIMITS.avatarMax||t.startsWith("//")?"":/^\/[A-Za-z0-9._~\-/%]+$/.test(t)?t:""}export function launcherChatAccentCss(e={}){const t=launcherColourCss(e.accent);if(!t)return{accent:"",accentText:""};let i=launcherColourCss(e.accentText);if(!i){const o=launcherColour(e.accent);if(o.startsWith("#")){const r=o.length<=5?o.slice(1,4).split("").map(a=>a+a).join(""):o.slice(1,7),[n,s,h]=[0,2,4].map(a=>parseInt(r.slice(a,a+2),16)/255).map(a=>a<=.03928?a/12.92:((a+.055)/1.055)**2.4);i=.2126*n+.7152*s+.0722*h>.179?"#111111":"#ffffff"}else i=o==="primary"?"var(--dm-primary-text, #fff)":`var(--dm-${o}-text, #fff)`}return{accent:t,accentText:i}}function m(e,t){return typeof e=="string"?e.replace(/\r\n?/g,`
4
+ `).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").replace(/\n{3,}/g,`
5
+
6
+ `).trim().slice(0,t):""}export function normaliseLauncher(e){const t=d(e),i=LAUNCHER_DEFAULTS,o=f(t.size,i.size,LAUNCHER_LIMITS.sizeMin,LAUNCHER_LIMITS.sizeMax),r=Math.floor(o/2),n=d(t.pages),s=(Array.isArray(n.paths)?n.paths:typeof n.paths=="string"?n.paths.split(/[\n,]+/):[]).map(normaliseLauncherPath).filter(Boolean).filter((a,u,p)=>p.indexOf(a)===u).slice(0,LAUNCHER_LIMITS.pathsMax),h=d(t.colours);return{id:typeof t.id=="string"&&LAUNCHER_ID_RE.test(t.id)?t.id:"",enabled:t.enabled!==!1,showDisc:t.showDisc!==!1,name:l(t.name,LAUNCHER_LIMITS.nameMax,i.name),label:l(t.label,LAUNCHER_LIMITS.labelMax,i.label),tooltipMode:c(t.tooltipMode,LAUNCHER_TOOLTIP_MODES,i.tooltipMode),tooltip:l(t.tooltip,LAUNCHER_LIMITS.tooltipMax,""),icon:typeof t.icon=="string"&&b.test(t.icon.trim())?t.icon.trim():i.icon,triggerStyle:c(t.triggerStyle,LAUNCHER_TRIGGER_STYLES,i.triggerStyle),position:c(t.position,LAUNCHER_POSITIONS,i.position),offsetX:f(t.offsetX,i.offsetX,0,LAUNCHER_LIMITS.offsetMax),offsetY:f(t.offsetY,i.offsetY,0,LAUNCHER_LIMITS.offsetMax),size:o,radius:Math.min(r,f(t.radius,i.radius,0,r)),devices:c(t.devices,LAUNCHER_DEVICES,i.devices),phone:C(t.phone,o),colours:{background:launcherColour(h.background),text:launcherColour(h.text)},class:M(typeof t.class=="string"?t.class:"").join(" "),pages:{mode:c(n.mode,LAUNCHER_PAGE_MODES,i.pages.mode),paths:s},audience:c(t.audience,LAUNCHER_AUDIENCES,i.audience),action:E(t.action),chat:normaliseLauncherChat(t.chat)}}export function launcherTooltip(e){return!e||e.tooltipMode==="off"?"":e.tooltipMode==="custom"?e.tooltip||e.label:e.triggerStyle==="icon-text"?"":e.label}export function launcherHref(e){return`#launcher-${e}`}export function newLauncherId(e=new Set,t=Math.random){for(let i=0;i<1e3;i++){const o="l-"+Math.floor(t()*2176782336).toString(36).padStart(6,"0");if(!e.has(o))return o}return"l-"+Date.now().toString(36)}export function normaliseLaunchers(e,t=Math.random){const i=Array.isArray(e)?e:Array.isArray(e?.launchers)?e.launchers:[],o=new Set;return i.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)).map(r=>{const n=normaliseLauncher(r);return(!n.id||o.has(n.id))&&(n.id=newLauncherId(o,t)),o.add(n.id),n})}export function launcherReady(e){return e?e.action.type==="chat"?!0:!!e.action.ref:!1}export function publicLauncher(e){const t={id:e.id,disc:e.showDisc,label:e.label,tooltip:launcherTooltip(e),icon:e.icon,triggerStyle:e.triggerStyle,position:e.position,offsetX:e.offsetX,offsetY:e.offsetY,size:e.size,radius:e.radius,devices:e.devices,phone:e.phone,colours:{background:launcherColourCss(e.colours.background),text:launcherColourCss(e.colours.text)},class:e.class,action:{type:e.action.type,title:e.action.title||e.label,size:e.action.size,side:e.action.side,width:e.action.width,customWidth:e.action.customWidth,widthUnit:e.action.widthUnit,height:e.action.height,customHeight:e.action.customHeight,heightUnit:e.action.heightUnit}};if(e.action.type==="chat"){const{aiContext:i,aiRules:o,aiUseSite:r,aiMaxPerChat:n,keepDays:s,...h}=e.chat;t.chat=h}return t}export function launcherSpot(e,{w:t,h:i,vw:o,vh:r,offsetX:n,offsetY:s}){const h=e[1]==="L"?"L":e[1]==="R"?"R":"C",a=e[0],u=h==="L"?n:h==="R"?o-t-n:Math.round((o-t)/2+n),p=a==="T"?s:a==="B"?r-i-s:Math.round((r-i)/2+s);return{left:u,top:p}}const g=12,L=(e,t)=>e.left<t.right+g&&t.left<e.right+g&&e.top<t.bottom+g&&t.top<e.bottom+g;export function launcherStack(e,t,{w:i,h:o},r){const n=e[0]==="B";let s=t.top;for(let h=0;h<=r.length;h++){const a={left:t.left,top:s,right:t.left+i,bottom:s+o},u=r.find(p=>p&&p.right>p.left&&p.bottom>p.top&&L(a,p));if(!u)break;s=Math.round(n?u.top-g-o:u.bottom+g)}return{left:t.left,top:s}}
@@ -1,12 +1,12 @@
1
- import{launcherModalBox as ie,launcherSpot as se,launcherStack as le}from"/public/js/launcher-settings.mjs?v=20261031-launchers-links";const Y="(max-width: 640px)",G=[".site-search-floating-trigger","#back-to-top-btn","#go-to-bottom-btn",".dm-theme-switcher:not(.dm-ts-inline)","nav.dm-breadcrumbs",".dm-motion-fab"].join(","),V={sm:"360px",md:"480px",lg:"640px",xl:"860px"},re=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),J=()=>document.documentElement.classList.contains("dm-reduced-motion")||matchMedia("(prefers-reduced-motion: reduce)").matches,de=`
1
+ import{LAUNCHER_LIMITS as C,launcherChatBox as ut,launcherModalBox as mt,launcherSpot as pt,launcherStack as ft}from"/public/js/launcher-settings.mjs?v=20261110-chat-times-settings";const V=i=>`launcher-chat-size:${i}`,vt=i=>{try{const c=globalThis.S?.get?.(V(i));return c&&Number(c.width)&&Number(c.height)?c:null}catch{return null}},Z=(i,c)=>{try{globalThis.S?.set?.(V(i),c)}catch{}},J="(max-width: 640px)",Q=[".site-search-floating-trigger","#back-to-top-btn","#go-to-bottom-btn",".dm-theme-switcher:not(.dm-ts-inline)","nav.dm-breadcrumbs",".dm-motion-fab"].join(","),tt={sm:"360px",md:"480px",lg:"640px",xl:"860px"},gt=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),et=()=>document.documentElement.classList.contains("dm-reduced-motion")||matchMedia("(prefers-reduced-motion: reduce)").matches,bt=`
2
2
  <button type="button" class="dm-launcher" data-id="{{id}}" data-bind-class="cls" data-bind-style="style.value"
3
3
  data-bind-aria-expanded="expanded.value" data-bind-hidden="hidden.value" aria-haspopup="dialog" aria-label="{{label}}">
4
4
  <span class="dm-launcher-icon" data-icon="{{icon}}" aria-hidden="true"></span>
5
5
  <span class="dm-launcher-label" data-bind-hidden="!pill">{{label}}</span>
6
- </button>`,ue=`
6
+ </button>`,yt=`
7
7
  <div class="dm-launcher-chat-head">
8
8
  <strong class="dm-launcher-chat-title" data-bind-text="title"></strong>
9
9
  <button type="button" class="dm-launcher-chat-close" data-on-click="close" aria-label="Close"><span data-icon="x" aria-hidden="true"></span></button>
10
10
  </div>
11
11
  <div class="dm-launcher-chat-body"></div>
12
- <p class="dm-launcher-note" data-bind-hidden="!note.value" data-bind-text="note.value"></p>`;function he(i){const s=i.getBoundingClientRect();return getComputedStyle(i).opacity!=="0"||i.offsetParent!==null?s:{top:Math.min(s.top,i.offsetTop),left:Math.min(s.left,i.offsetLeft),right:Math.max(s.right,i.offsetLeft+i.offsetWidth),bottom:Math.max(s.bottom,i.offsetTop+i.offsetHeight)}}function Q(i){window.Domma?.icons?.scan&&window.Domma.icons.scan(i)}function Z(i,{fill:s}){const c=document.createElement("iframe");if(c.className="dm-launcher-frame"+(s?" is-fill":""),c.title=i.action.title,c.src=`/_launcher/${encodeURIComponent(i.id)}`,c.setAttribute("loading","eager"),!s){let d=null;c.addEventListener("load",()=>{const L=c.contentDocument;if(!L?.body)return;const y=L.querySelector(".site-content")||L.body,T=()=>{c.style.height=`${Math.ceil(y.getBoundingClientRect().height)}px`};T(),d?.disconnect(),d=new ResizeObserver(T),d.observe(y)})}return c}export function mountLaunchers(i){if(!Array.isArray(i)||!i.length||document.querySelector(".dm-launchers"))return null;const s=M.observable(matchMedia(Y).matches),c=document.createElement("div");c.className="dm-launchers";const d=i.map(e=>{const n=a=>a&&e.phone?.override?{...e,...e.phone}:e,t=e.triggerStyle==="icon-text",o=a=>{const u=n(a),f={"--launcher-size":`${u.size}px`,"--launcher-radius":`${t?999:Math.min(e.radius,Math.floor(u.size/2))}px`,"--launcher-glyph":`${Math.round(u.size*20/52)}px`};return e.colours.background&&(f["--launcher-bg"]=e.colours.background),e.colours.text&&(f["--launcher-fg"]=e.colours.text),f},l=M.observable(-9999),r=M.observable(-9999);return{id:e.id,label:e.label,icon:e.icon,pill:t,launcher:e,look:n,left:l,top:r,cls:["dm-launcher--"+e.action.type,t?"dm-launcher--pill":"",e.class].filter(Boolean).join(" "),style:M.computed(()=>({...o(s.value),left:`${l.value}px`,top:`${r.value}px`})),expanded:M.observable("false"),hidden:M.computed(()=>e.disc===!1||e.devices==="desktop"&&s.value||e.devices==="phone"&&!s.value)}});c.innerHTML='<div class="dm-launchers-list" data-each="rows.value key=id"></div>',c.firstElementChild.innerHTML=de;const L=M.applyBindings({rows:M.observable(d)},c);document.body.appendChild(c),Q(c);const y=e=>c.querySelector(`.dm-launcher[data-id="${CSS.escape(e)}"]`),T={TL:"right",ML:"right",BL:"right",TR:"left",MR:"left",BR:"left",TC:"bottom",BC:"top"},A=new Map;for(const e of d){const n=e.launcher.tooltip,t=y(e.id);if(!(!n||!t||typeof E.tooltip!="function"))try{A.set(e.id,E.tooltip(t,{content:n,position:T[e.launcher.position]||"top",trigger:"hover focus",className:"dm-launcher-tip"}))}catch{}}function z(){const e=document.documentElement.clientWidth,n=window.innerHeight,t=[...document.querySelectorAll(G)].filter(o=>!c.contains(o)&&getComputedStyle(o).position==="fixed"&&getComputedStyle(o).display!=="none").map(he);for(const o of d){const l=y(o.id);if(!l||l.hidden)continue;const r=o.look(s.peek()),a=l.offsetWidth,u=l.offsetHeight,f=se(r.position,{w:a,h:u,vw:e,vh:n,offsetX:r.offsetX,offsetY:r.offsetY}),v=le(r.position,f,{w:a,h:u},t),b=Math.max(0,Math.min(e-a,v.left)),C=Math.max(0,Math.min(n-u,v.top));o.left.value=b,o.top.value=C,t.push({left:b,top:C,right:b+a,bottom:C+u})}}let R=0;const g=()=>{cancelAnimationFrame(R),R=requestAnimationFrame(z)},P=new MutationObserver(e=>{e.some(n=>[...n.addedNodes].some(t=>t.nodeType===1&&t.matches?.(G)))&&g()});P.observe(document.body,{childList:!0});const H=matchMedia(Y),q=()=>{s.value=H.matches,g()};H.addEventListener?.("change",q),window.addEventListener("resize",g),window.addEventListener("load",g,{once:!0}),z();let m=null;const ee=M.effect(()=>{const e=d.some(n=>n.expanded.value==="true"&&(n.launcher.action.type!=="chat"||s.value));document.documentElement.classList.toggle("dm-launcher-covering",e)});function K(){const e=m;m=null,e&&(e.row.expanded.value="false",e.close())}function te(e){const n=e.launcher,t=ie(n.action),o=E.modal({title:n.action.title,size:t.width,content:Z(n,{fill:!!t.height}),className:"dm-launcher-modal",bodyClass:"dm-launcher-modal-body",buttons:[],animation:J()?!1:"fade",onClosed:()=>{m?.row===e&&(m=null,e.expanded.value="false"),setTimeout(()=>{try{o.destroy()}catch{}},0)}});return o.element?.classList.add("dm-launcher-modal",`dm-launcher-modal--${n.action.size}`),o.element?.style.setProperty("--launcher-modal-w",t.width),t.height&&(o.element?.classList.add("dm-launcher-modal--fixed"),o.element?.style.setProperty("--launcher-modal-h",t.height)),o.open(),()=>{try{o.close()}catch{}}}function ne(e){const n=e.launcher,t=E.slideover({title:re(n.action.title),position:n.action.side,size:s.peek()?"full":V[n.action.width]||V.md,content:Z(n,{fill:!0}),bodyClass:"dm-launcher-so-body",animation:!J(),onClosed:()=>{m?.row===e&&(m=null,e.expanded.value="false"),setTimeout(()=>{try{t.destroy?.()}catch{}t.element?.remove()},0)}});return t.element?.classList.add("dm-launcher-so"),t.open(),()=>{try{t.close()}catch{}}}function oe(e,n){const t=e.launcher,o=y(e.id),l=o&&!o.hidden?o:null,r=l||(n?.isConnected?n:null),a=document.createElement("div");a.className="dm-launcher-chat",a.setAttribute("role","dialog"),a.setAttribute("aria-label",t.action.title),a.innerHTML=ue;const u=M.observable("");let f=null,v=!1;const b=()=>{if(!v){v=!0;try{f?.destroy?.()}catch{}C.dispose?.(),a.remove(),document.removeEventListener("keydown",U),window.removeEventListener("resize",N),m?.row===e&&(m=null,e.expanded.value="false"),(r?.isConnected?r:null)?.focus()}},C=M.applyBindings({title:t.action.title,note:u,close:b},a),U=h=>{h.key!=="Escape"||h.defaultPrevented||!a.contains(document.activeElement)||(h.preventDefault(),b())},N=()=>{if(s.peek()){a.classList.add("is-full"),a.removeAttribute("style");return}a.classList.remove("is-full");const h=document.documentElement.clientWidth,D=window.innerHeight,w=Math.min(380,h-24),x=Math.min(560,D-24),I=O=>Math.max(12,Math.min(h-w-12,O)),_=O=>Math.max(12,Math.min(D-x-12,O));let S,k;if(!l){S=I(t.position[1]==="L"?24:h-w-24),k=_(D-x-24),Object.assign(a.style,{left:`${S}px`,top:`${k}px`,width:`${w}px`,height:`${x}px`});return}const p=l.getBoundingClientRect(),X=p.left+p.width/2>h/2;t.position[0]==="M"?(S=I(X?p.left-w-12:p.right+12),k=_(p.top+p.height/2-x/2)):(S=I(X?p.right-w:p.left),k=t.position[0]==="T"?_(p.bottom+12):_(p.top-x-12)),Object.assign(a.style,{left:`${S}px`,top:`${k}px`,width:`${w}px`,height:`${x}px`})};document.body.appendChild(a),N(),Q(a),document.addEventListener("keydown",U),window.addEventListener("resize",N);const ce=a.querySelector(".dm-launcher-chat-body");return import("/public/js/launcher-chat.mjs").then(h=>{if(!v){if(typeof h.mountChat!="function")throw new Error("no mountChat");f=h.mountChat(ce,{launcherId:t.id,title:t.action.title,chat:t.chat||{}})}}).catch(()=>{v||(u.value="Chat is unavailable right now. Please try again later.")}),a.querySelector(".dm-launcher-chat-close")?.focus(),b}function $(e,n=null){const t=d.find(a=>a.id===e);if(!t)return;const o=m?.row===t;if(K(),o)return;t.expanded.value="true";try{A.get(t.id)?.close()}catch{}const l=t.launcher.action.type,r=l==="chat"?oe(t,n):l==="slideover"?ne(t):te(t);m={row:t,close:r}}const F=e=>{const n=e.target.closest(".dm-launcher");n&&$(n.dataset.id)};c.addEventListener("click",F);const W=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,ae=e=>{const n=e.closest("[data-launcher]");if(n)return{el:n,id:n.dataset.launcher};const t=e.closest("a[href]"),o=t&&W.exec(t.getAttribute("href")||"");return o?{el:t,id:o[1]}:null},j=e=>{if(e.button>0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||c.contains(e.target))return;const n=e.target instanceof Element?ae(e.target):null;!n||!d.some(t=>t.id===n.id)||(e.preventDefault(),$(n.id,n.el))};document.addEventListener("click",j);const B=W.exec(location.hash);return B&&d.some(e=>e.id===B[1])&&(history.replaceState(history.state,"",location.pathname+location.search),setTimeout(()=>$(B[1]),0)),{place:z,launch:$,destroy(){K(),ee?.(),document.documentElement.classList.remove("dm-launcher-covering");for(const e of A.values())try{e.destroy()}catch{}A.clear(),cancelAnimationFrame(R),P.disconnect(),H.removeEventListener?.("change",q),window.removeEventListener("resize",g),window.removeEventListener("load",g),c.removeEventListener("click",F),document.removeEventListener("click",j),L?.dispose?.(),c.remove()}}}typeof window<"u"&&Array.isArray(window.__CMS_LAUNCHERS__)&&window.M&&window.E&&(window.DommaLaunchers=mountLaunchers(window.__CMS_LAUNCHERS__));
12
+ <p class="dm-launcher-note" data-bind-hidden="!note.value" data-bind-text="note.value"></p>`;function wt(i){const c=i.getBoundingClientRect();return getComputedStyle(i).opacity!=="0"||i.offsetParent!==null?c:{top:Math.min(c.top,i.offsetTop),left:Math.min(c.left,i.offsetLeft),right:Math.max(c.right,i.offsetLeft+i.offsetWidth),bottom:Math.max(c.bottom,i.offsetTop+i.offsetHeight)}}function nt(i){window.Domma?.icons?.scan&&window.Domma.icons.scan(i)}function ot(i,{fill:c}){const l=document.createElement("iframe");if(l.className="dm-launcher-frame"+(c?" is-fill":""),l.title=i.action.title,l.src=`/_launcher/${encodeURIComponent(i.id)}`,l.setAttribute("loading","eager"),!c){let f=null;l.addEventListener("load",()=>{const H=l.contentDocument;if(!H?.body)return;const $=H.querySelector(".site-content")||H.body,N=()=>{l.style.height=`${Math.ceil($.getBoundingClientRect().height)}px`};N(),f?.disconnect(),f=new ResizeObserver(N),f.observe($)})}return l}export function mountLaunchers(i){if(!Array.isArray(i)||!i.length||document.querySelector(".dm-launchers"))return null;const c=M.observable(matchMedia(J).matches),l=document.createElement("div");l.className="dm-launchers";const f=i.map(t=>{const n=o=>o&&t.phone?.override?{...t,...t.phone}:t,e=t.triggerStyle==="icon-text",a=o=>{const v=n(o),x={"--launcher-size":`${v.size}px`,"--launcher-radius":`${e?999:Math.min(t.radius,Math.floor(v.size/2))}px`,"--launcher-glyph":`${Math.round(v.size*20/52)}px`};return t.colours.background&&(x["--launcher-bg"]=t.colours.background),t.colours.text&&(x["--launcher-fg"]=t.colours.text),x},h=M.observable(-9999),u=M.observable(-9999);return{id:t.id,label:t.label,icon:t.icon,pill:e,launcher:t,look:n,left:h,top:u,cls:["dm-launcher--"+t.action.type,e?"dm-launcher--pill":"",t.class].filter(Boolean).join(" "),style:M.computed(()=>({...a(c.value),left:`${h.value}px`,top:`${u.value}px`})),expanded:M.observable("false"),hidden:M.computed(()=>t.disc===!1||t.devices==="desktop"&&c.value||t.devices==="phone"&&!c.value)}});l.innerHTML='<div class="dm-launchers-list" data-each="rows.value key=id"></div>',l.firstElementChild.innerHTML=bt;const H=M.applyBindings({rows:M.observable(f)},l);document.body.appendChild(l),nt(l);const $=t=>l.querySelector(`.dm-launcher[data-id="${CSS.escape(t)}"]`),N={TL:"right",ML:"right",BL:"right",TR:"left",MR:"left",BR:"left",TC:"bottom",BC:"top"},B=new Map;for(const t of f){const n=t.launcher.tooltip,e=$(t.id);if(!(!n||!e||typeof E.tooltip!="function"))try{B.set(t.id,E.tooltip(e,{content:n,position:N[t.launcher.position]||"top",trigger:"hover focus",className:"dm-launcher-tip"}))}catch{}}function O(){const t=document.documentElement.clientWidth,n=window.innerHeight,e=[...document.querySelectorAll(Q)].filter(a=>!l.contains(a)&&getComputedStyle(a).position==="fixed"&&getComputedStyle(a).display!=="none").map(wt);for(const a of f){const h=$(a.id);if(!h||h.hidden)continue;const u=a.look(c.peek()),o=h.offsetWidth,v=h.offsetHeight,x=pt(u.position,{w:o,h:v,vw:t,vh:n,offsetX:u.offsetX,offsetY:u.offsetY}),S=ft(u.position,x,{w:o,h:v},e),T=Math.max(0,Math.min(t-o,S.left)),R=Math.max(0,Math.min(n-v,S.top));a.left.value=T,a.top.value=R,e.push({left:T,top:R,right:T+o,bottom:R+v})}}let P=0;const A=()=>{cancelAnimationFrame(P),P=requestAnimationFrame(O)},K=new MutationObserver(t=>{t.some(n=>[...n.addedNodes].some(e=>e.nodeType===1&&e.matches?.(Q)))&&A()});K.observe(document.body,{childList:!0});const W=matchMedia(J),U=()=>{c.value=W.matches,A()};W.addEventListener?.("change",U),window.addEventListener("resize",A),window.addEventListener("load",A,{once:!0}),O();let b=null;const at=M.effect(()=>{const t=f.some(n=>n.expanded.value==="true"&&(n.launcher.action.type!=="chat"||c.value));document.documentElement.classList.toggle("dm-launcher-covering",t)});function Y(){const t=b;b=null,t&&(t.row.expanded.value="false",t.close())}function it(t){const n=t.launcher,e=mt(n.action),a=E.modal({title:n.action.title,size:e.width,content:ot(n,{fill:!!e.height}),className:"dm-launcher-modal",bodyClass:"dm-launcher-modal-body",buttons:[],animation:et()?!1:"fade",onClosed:()=>{b?.row===t&&(b=null,t.expanded.value="false"),setTimeout(()=>{try{a.destroy()}catch{}},0)}});return a.element?.classList.add("dm-launcher-modal",`dm-launcher-modal--${n.action.size}`),a.element?.style.setProperty("--launcher-modal-w",e.width),e.height&&(a.element?.classList.add("dm-launcher-modal--fixed"),a.element?.style.setProperty("--launcher-modal-h",e.height)),a.open(),()=>{try{a.close()}catch{}}}function ct(t){const n=t.launcher,e=E.slideover({title:gt(n.action.title),position:n.action.side,size:c.peek()?"full":tt[n.action.width]||tt.md,content:ot(n,{fill:!0}),bodyClass:"dm-launcher-so-body",animation:!et(),onClosed:()=>{b?.row===t&&(b=null,t.expanded.value="false"),setTimeout(()=>{try{e.destroy?.()}catch{}e.element?.remove()},0)}});return e.element?.classList.add("dm-launcher-so"),e.open(),()=>{try{e.close()}catch{}}}function st(t,n){const e=t.launcher,a=$(t.id),h=a&&!a.hidden?a:null,u=h||(n?.isConnected?n:null),o=document.createElement("div");o.className="dm-launcher-chat",o.setAttribute("role","dialog"),o.setAttribute("aria-label",e.action.title),o.innerHTML=yt;const v=M.observable("");let x=null,S=!1;const T=()=>{if(!S){S=!0;try{x?.destroy?.()}catch{}R.dispose?.(),o.remove(),document.removeEventListener("keydown",G),window.removeEventListener("resize",D),b?.row===t&&(b=null,t.expanded.value="false"),(u?.isConnected?u:null)?.focus()}},R=M.applyBindings({title:e.action.title,note:v,close:T},o),G=r=>{r.key!=="Escape"||r.defaultPrevented||!o.contains(document.activeElement)||(r.preventDefault(),T())},D=()=>{if(c.peek()){o.classList.add("is-full"),o.removeAttribute("style");return}o.classList.remove("is-full");const r=document.documentElement.clientWidth,s=window.innerHeight,_=e.chat?.resizable!==!1&&vt(e.id)||ut(e.chat||{}),y=Math.min(Math.max(C.chatWidth[0],Number(_.width)),C.chatWidth[1],r-24),w=Math.min(Math.max(C.chatHeight[0],Number(_.height)),C.chatHeight[1],s-24),m=L=>Math.max(12,Math.min(r-y-12,L)),d=L=>Math.max(12,Math.min(s-w-12,L));let g,z;if(!h){g=m(e.position[1]==="L"?24:r-y-24),z=d(s-w-24),Object.assign(o.style,{left:`${g}px`,top:`${z}px`,width:`${y}px`,height:`${w}px`});return}const p=h.getBoundingClientRect(),k=p.left+p.width/2>r/2;e.position[0]==="M"?(g=m(k?p.left-y-12:p.right+12),z=d(p.top+p.height/2-w/2)):(g=m(k?p.right-y:p.left),z=e.position[0]==="T"?d(p.bottom+12):d(p.top-w-12)),Object.assign(o.style,{left:`${g}px`,top:`${z}px`,width:`${y}px`,height:`${w}px`})};if(document.body.appendChild(o),D(),e.chat?.resizable!==!1){const r=document.createElement("div");r.className="dm-launcher-chat-grip",r.setAttribute("role","separator"),r.setAttribute("aria-label","Resize the chat"),r.title="Drag to resize",o.appendChild(r);let s=null;const _=m=>{if(!s)return;const d=document.documentElement.clientWidth,g=window.innerHeight,z=(m.clientX-s.x)*(s.fromLeft?-1:1),p=(m.clientY-s.y)*(s.fromTop?-1:1),k=Math.round(Math.min(Math.max(C.chatWidth[0],s.w+z),C.chatWidth[1],d-24)),L=Math.round(Math.min(Math.max(C.chatHeight[0],s.h+p),C.chatHeight[1],g-24)),dt=s.fromLeft?s.right-k:s.left,ht=s.fromTop?s.bottom-L:s.top;Object.assign(o.style,{width:`${k}px`,height:`${L}px`,left:`${Math.max(12,Math.min(d-k-12,dt))}px`,top:`${Math.max(12,Math.min(g-L-12,ht))}px`}),s.size={width:k,height:L}},y=()=>{s&&(s.size&&Z(e.id,s.size),s=null,o.classList.remove("is-resizing"),window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",y))},w=()=>{const[m,d]=String(e.position||"BR");r.dataset.corner=`${m==="T"?"b":"t"}${d==="L"?"r":"l"}`};w(),r.addEventListener("pointerdown",m=>{if(c.peek())return;m.preventDefault();const d=o.getBoundingClientRect(),g=r.dataset.corner;s={x:m.clientX,y:m.clientY,w:d.width,h:d.height,left:d.left,top:d.top,right:d.right,bottom:d.bottom,fromLeft:g[1]==="l",fromTop:g[0]==="t"},o.classList.add("is-resizing"),window.addEventListener("pointermove",_),window.addEventListener("pointerup",y)}),r.addEventListener("dblclick",()=>{Z(e.id,null),D(),w()})}nt(o),document.addEventListener("keydown",G),window.addEventListener("resize",D);const rt=o.querySelector(".dm-launcher-chat-body");return import("/public/js/launcher-chat.mjs").then(r=>{if(!S){if(typeof r.mountChat!="function")throw new Error("no mountChat");x=r.mountChat(rt,{launcherId:e.id,title:e.action.title,chat:e.chat||{}})}}).catch(()=>{S||(v.value="Chat is unavailable right now. Please try again later.")}),o.querySelector(".dm-launcher-chat-close")?.focus(),T}function I(t,n=null){const e=f.find(o=>o.id===t);if(!e)return;const a=b?.row===e;if(Y(),a)return;e.expanded.value="true";try{B.get(e.id)?.close()}catch{}const h=e.launcher.action.type,u=h==="chat"?st(e,n):h==="slideover"?ct(e):it(e);b={row:e,close:u}}const j=t=>{const n=t.target.closest(".dm-launcher");n&&I(n.dataset.id)};l.addEventListener("click",j);const F=/^#launcher-([a-z0-9][a-z0-9-]{0,39})$/,lt=t=>{const n=t.closest("[data-launcher]");if(n)return{el:n,id:n.dataset.launcher};const e=t.closest("a[href]"),a=e&&F.exec(e.getAttribute("href")||"");return a?{el:e,id:a[1]}:null},X=t=>{if(t.button>0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||l.contains(t.target))return;const n=t.target instanceof Element?lt(t.target):null;!n||!f.some(e=>e.id===n.id)||(t.preventDefault(),I(n.id,n.el))};document.addEventListener("click",X);const q=F.exec(location.hash);return q&&f.some(t=>t.id===q[1])&&(history.replaceState(history.state,"",location.pathname+location.search),setTimeout(()=>I(q[1]),0)),{place:O,launch:I,destroy(){Y(),at?.(),document.documentElement.classList.remove("dm-launcher-covering");for(const t of B.values())try{t.destroy()}catch{}B.clear(),cancelAnimationFrame(P),K.disconnect(),W.removeEventListener?.("change",U),window.removeEventListener("resize",A),window.removeEventListener("load",A),l.removeEventListener("click",j),document.removeEventListener("click",X),H?.dispose?.(),l.remove()}}}typeof window<"u"&&Array.isArray(window.__CMS_LAUNCHERS__)&&window.M&&window.E&&(window.DommaLaunchers=mountLaunchers(window.__CMS_LAUNCHERS__));
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import {chatLauncher} from '../../services/chat/launcher-bridge.js';
24
24
  import {readChatSettings} from '../../services/chat/settings.js';
25
+ import {aiAvailable} from '../../services/chat/ai.js';
25
26
  import {
26
27
  createSession, getSession, knowledgeIndex, messagesAfter, sessionByToken, staffAvailable
27
28
  } from '../../services/chat/store.js';
@@ -117,8 +118,9 @@ export async function chatPublicRoutes(fastify) {
117
118
  fastify.get('/config', limit(60), async (request, reply) => {
118
119
  const launcher = await launcherOf(request, reply);
119
120
  if (!launcher) return;
120
- const {greeting, botName, bot, staff, askDetails} = launcher.chat;
121
- return {greeting, botName, bot, staff, askDetails, staffOnline: staff && staffAvailable().length > 0};
121
+ const {greeting, botName, bot, staff, askDetails, accent, accentText, avatar, starters, personButton, times} = launcher.chat;
122
+ return {greeting, botName, bot, staff, askDetails, accent, accentText, avatar, starters, personButton, times, ai: bot && launcher.chat.ai && aiAvailable(),
123
+ staffOnline: staff && staffAvailable().length > 0};
122
124
  });
123
125
 
124
126
  fastify.get('/state', limit(90), async (request, reply) => {
@@ -10,16 +10,21 @@
10
10
  * POST /api/chats/knowledge/test - {text}: what the bot would answer, with scores
11
11
  * GET /api/chats/unanswered - questions the bot could not answer
12
12
  * GET /api/chats/settings - site-wide chat settings
13
+ * GET /api/chats/saved - chats saved for a closer look
14
+ * GET /api/chats/saved/:sid - one, with its messages
13
15
  * chats.reply:
14
16
  * POST /api/chats/presence - {available}: "I can take chats" (sent every 30s by the inbox)
15
17
  * POST /api/chats/:id/reply - {text}
16
18
  * POST /api/chats/:id/close
19
+ * POST /api/chats/:id/save - {note}: keep a copy in Saved Chats (the chat-saved collection)
20
+ * PUT /api/chats/saved/:sid - {note?, outcome?}
17
21
  * chats.manage:
18
22
  * DELETE /api/chats/:id
19
23
  * POST /api/chats/knowledge, PUT/DELETE /api/chats/knowledge/:id
20
24
  * POST /api/chats/knowledge/remove-examples
21
25
  * POST /api/chats/unanswered/:id/done {done}, DELETE /api/chats/unanswered/:id
22
26
  * PUT /api/chats/settings
27
+ * DELETE /api/chats/saved/:sid
23
28
  */
24
29
  import {authenticate as defaultAuthenticate, requirePermission as defaultRequirePermission} from '../../middleware/auth.js';
25
30
  import {ago, clip, plural} from '../../services/sidebarBadges.js';
@@ -34,6 +39,7 @@ import {
34
39
  } from '../../services/chat/conversation.js';
35
40
  import {CHAT_DEFAULTS, readChatSettings, saveChatSettings} from '../../services/chat/settings.js';
36
41
  import {chatLauncherSummary} from '../../services/chat/launcher-bridge.js';
42
+ import {getSaved, listSaved, removeSaved, saveChat, updateSaved} from '../../services/chat/saved.js';
37
43
  import {CONFIDENCE} from '../../services/chat/matcher.js';
38
44
 
39
45
  const ID = /^[A-Za-z0-9_-]{1,64}$/;
@@ -187,6 +193,28 @@ export async function chatsRoutes(fastify, opts = {}) {
187
193
 
188
194
  fastify.put('/settings', can('manage'), async (request) => ({settings: saveChatSettings(request.body || {})}));
189
195
 
196
+ // ---- Saved chats -----------------------------------------------------------
197
+
198
+ fastify.get('/saved', can('read'), async () => ({items: await listSaved()}));
199
+
200
+ fastify.get('/saved/:sid', can('read'), async (request, reply) => {
201
+ const item = ID.test(request.params.sid) ? await getSaved(request.params.sid) : null;
202
+ return item ? {item} : reply.code(404).send({error: 'Saved chat not found'});
203
+ });
204
+
205
+ fastify.put('/saved/:sid', can('reply'), async (request, reply) => {
206
+ if (!ID.test(request.params.sid)) return reply.code(404).send({error: 'Saved chat not found'});
207
+ const {item, error, missing} = await updateSaved(request.params.sid, request.body || {});
208
+ if (missing) return reply.code(404).send({error: 'Saved chat not found'});
209
+ if (error) return reply.code(400).send({error});
210
+ return {item};
211
+ });
212
+
213
+ fastify.delete('/saved/:sid', can('manage'), async (request, reply) => {
214
+ if (!ID.test(request.params.sid) || !await removeSaved(request.params.sid)) return reply.code(404).send({error: 'Saved chat not found'});
215
+ return {ok: true};
216
+ });
217
+
190
218
  // ---- One chat (after the static paths) -----------------------------------
191
219
 
192
220
  fastify.get('/:id', can('read'), async (request, reply) => {
@@ -224,6 +252,15 @@ export async function chatsRoutes(fastify, opts = {}) {
224
252
  return {chat: staffSummary(result.session)};
225
253
  });
226
254
 
255
+ fastify.post('/:id/save', can('reply'), async (request, reply) => {
256
+ const {id} = request.params;
257
+ if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
258
+ const user = {id: userId(request), name: request.user?.name || request.user?.username || ''};
259
+ const result = await saveChat(id, request.body || {}, user);
260
+ if (result.error) return reply.code(result.code || 400).send({error: result.error});
261
+ return reply.code(201).send({item: result.item});
262
+ });
263
+
227
264
  fastify.delete('/:id', can('manage'), async (request, reply) => {
228
265
  const {id} = request.params;
229
266
  if (!ID.test(id)) return reply.code(404).send({error: 'Chat not found'});
@@ -22,6 +22,7 @@ import {normaliseAdminPath} from '../../services/roles.js';
22
22
  import {cssClassProblems} from '../../../public/js/css-classes.mjs';
23
23
  import {motionFooterMirror, normaliseMotionSettings} from '../../services/motionSettings.js';
24
24
  import {invalidateMeasurementId, measurementIdOf, normaliseMeasurementId} from '../../services/googleAnalytics.js';
25
+ import {assistantProblem, normaliseAssistant} from '../../services/assistant.js';
25
26
 
26
27
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
28
  const CUSTOM_CSS_FILE = path.resolve(__dirname, '../../../content/custom.css');
@@ -127,7 +128,9 @@ export async function settingsRoutes(fastify) {
127
128
  // Google Analytics (Site Settings > Analytics) - services/googleAnalytics.js.
128
129
  'googleAnalytics',
129
130
  // The "Reduce motion" control (Site Settings > Reduce motion) - services/motionSettings.js.
130
- 'motion'
131
+ 'motion',
132
+ // What every AI answer knows about the site and the rules it keeps (services/assistant.js).
133
+ 'assistant'
131
134
  ]);
132
135
  const unknownKeys = Object.keys(data).filter(k => !ALLOWED_KEYS.has(k));
133
136
  if (unknownKeys.length > 0) {
@@ -167,6 +170,13 @@ export async function settingsRoutes(fastify) {
167
170
  if (raw && !id) return reply.status(400).send({error: 'Google Analytics: a measurement ID looks like G-XXXXXXXXXX.'});
168
171
  data.googleAnalytics = {measurementId: id};
169
172
  }
173
+ if ('assistant' in data) {
174
+ const a = data.assistant;
175
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return reply.status(400).send({error: 'AI assistant: send {context, rules}.'});
176
+ const problem = assistantProblem(a);
177
+ if (problem) return reply.status(400).send({error: `AI assistant: ${problem}`});
178
+ data.assistant = normaliseAssistant(a);
179
+ }
170
180
  if ('adminHome' in data) {
171
181
  // An admin route, or blank for the built-in dashboard.
172
182
  const home = data.adminHome == null || data.adminHome === '' ? '/' : normaliseAdminPath(data.adminHome);
@@ -0,0 +1,67 @@
1
+ /**
2
+ * What every AI answer on a site knows and keeps to - one place for the Launcher chat bot (Della) and any
3
+ * AI feature that talks to visitors after it.
4
+ *
5
+ * Site-wide (site.json `assistant`, Site Settings > General > AI assistant):
6
+ * context facts about the business in the owner's words - what you do, where, hours, prices, tone
7
+ * rules what an answer must never do or say - "never quote prices", "do not discuss competitors"
8
+ * Per use (a chat launcher's `chat.aiContext` / `chat.aiRules`): the same two, for that launcher only,
9
+ * added after the site's own. A launcher's rules add to the site's; they never lift one. A launcher may leave
10
+ * out the site's CONTEXT (`chat.aiUseSite: false`, for a chat about something else), but never its rules:
11
+ * the site's rules apply to every AI answer on the site, and nothing in a launcher or a chat can override them.
12
+ *
13
+ * Both are the owner's instructions, so they go to Claude as instructions (the system prompt), while what a
14
+ * visitor types goes as the visitor's message and is never obeyed as an instruction.
15
+ *
16
+ * @module services/assistant
17
+ */
18
+ import {getConfig} from '../config.js';
19
+
20
+ export const CONTEXT_MAX = 4000;
21
+ export const RULES_MAX = 2000;
22
+
23
+ const clean = (v, max) => String(v ?? '').replace(/\r\n?/g, '\n')
24
+ // eslint-disable-next-line no-control-regex
25
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').replace(/\n{3,}/g, '\n\n').trim().slice(0, max);
26
+
27
+ /** What is wrong with an `assistant` block as sent, or ''. */
28
+ export function assistantProblem(a = {}) {
29
+ for (const [key, max, label] of [['context', CONTEXT_MAX, 'About the business'], ['rules', RULES_MAX, 'Rules']]) {
30
+ if (a[key] !== undefined && a[key] !== null && typeof a[key] !== 'string') return `${label} must be text.`;
31
+ if (String(a[key] ?? '').length > max) return `${label} is limited to ${max} characters.`;
32
+ }
33
+ return '';
34
+ }
35
+
36
+ /** The block as stored. */
37
+ export function normaliseAssistant(a = {}) {
38
+ const r = a && typeof a === 'object' && !Array.isArray(a) ? a : {};
39
+ return {context: clean(r.context, CONTEXT_MAX), rules: clean(r.rules, RULES_MAX)};
40
+ }
41
+
42
+ /** The site's own block, read now (never cached: Site Settings saves take effect on the next answer). */
43
+ export function siteAssistant() {
44
+ try {
45
+ const site = getConfig('site') || {};
46
+ return {...normaliseAssistant(site.assistant), name: clean(site.title, 120), tagline: clean(site.tagline, 200)};
47
+ } catch {
48
+ return {context: '', rules: '', name: '', tagline: ''};
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The context and rules for one use: the site's, then the launcher's.
54
+ *
55
+ * @param {{aiContext?: string, aiRules?: string, aiUseSite?: boolean}} [extra]
56
+ * @returns {{site: {name: string, tagline: string}, context: string, rules: string}}
57
+ */
58
+ export function assistantBrief(extra = {}) {
59
+ const all = siteAssistant();
60
+ const s = extra.aiUseSite === false ? {...all, context: ''} : all;
61
+ const more = normaliseAssistant({context: extra.aiContext, rules: extra.aiRules});
62
+ return {
63
+ site: {name: s.name, tagline: s.tagline},
64
+ context: [s.context, more.context].filter(Boolean).join('\n\n'),
65
+ rules: [s.rules, more.rules].filter(Boolean).join('\n')
66
+ };
67
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Della's AI answers - what the chat bot says when the Knowledge has no answer.
3
+ *
4
+ * Included in the Pro plan on hosted sites, so a site holds no Claude key: the question goes to the Manager
5
+ * that runs the site (MANAGER_URL + FLEET_TOKEN, POST /api/fleet/launcher-chat), which checks the licence and
6
+ * the month's allowance and asks Claude from a short-lived job that alone reads the key. On dcm, which is the
7
+ * Manager, the same code is reached in this process (globalThis[Symbol.for('domma.launcher-chat')]). A site
8
+ * with neither has no AI answers, and the bot answers from the Knowledge alone, as before.
9
+ *
10
+ * What Claude is given: the site's name, Site Settings > AI assistant and the launcher's own context and rules
11
+ * (services/assistant.js), the enabled Knowledge, the last few messages of this chat and the question. It
12
+ * answers only from those, or says it does not know - then the chat goes on as before ("Sorry, I do not
13
+ * know", the offer of a person).
14
+ *
15
+ * @module services/chat/ai
16
+ */
17
+ import {assistantBrief} from '../assistant.js';
18
+ import {knowledgeIndex, messagesAfter} from './store.js';
19
+
20
+ const REGISTRY = Symbol.for('domma.launcher-chat');
21
+ /** What a visitor will wait for an answer. */
22
+ const ASK_MS = 25_000;
23
+ /** Knowledge and chat sent at most: a reply is a few sentences, the prompt need not be a book. */
24
+ export const KNOWLEDGE_CHARS = 16_000;
25
+ export const HISTORY_MESSAGES = 10;
26
+ /** After the Manager says no (no licence, the month's answers used), ask again only after this. */
27
+ const BACKOFF_MS = {403: 10 * 60_000, 429: 30 * 60_000, other: 60_000};
28
+
29
+ let restUntil = 0;
30
+ export function _resetAi() { restUntil = 0; }
31
+
32
+ /** Whether this site has someone to ask. */
33
+ export function aiAvailable(env = process.env, at = Date.now()) {
34
+ if (at < restUntil) return false;
35
+ return Boolean(globalThis[REGISTRY] || (env.MANAGER_URL && env.FLEET_TOKEN));
36
+ }
37
+
38
+ const plain = (md) => String(md || '').replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[*_`#>]/g, '').replace(/\n{3,}/g, '\n\n').trim();
39
+
40
+ /** The enabled Knowledge as question and answer pairs, most used first, within KNOWLEDGE_CHARS. */
41
+ export function knowledgeForAi(entries) {
42
+ const out = [];
43
+ let used = 0;
44
+ const list = [...entries].filter(k => k.enabled !== false && !k.sample).sort((a, b) => (b.hits || 0) - (a.hits || 0));
45
+ for (const k of list) {
46
+ const pair = {q: [k.question, ...String(k.alternatives || '').split('\n')].map(s => s.trim()).filter(Boolean).join(' / '), a: plain(k.answer)};
47
+ const size = pair.q.length + pair.a.length;
48
+ if (used + size > KNOWLEDGE_CHARS) break;
49
+ used += size;
50
+ out.push(pair);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /** The chat before the question, as {from, text}: visitor and bot only (staff never answer while the bot does). */
56
+ export function historyForAi(messages, question) {
57
+ const rows = messages.filter(m => m.data?.from === 'visitor' || m.data?.from === 'bot')
58
+ .map(m => ({from: m.data.from, text: String(m.data.text || '').slice(0, 600)}));
59
+ // The question itself was written just before this asks: it goes separately.
60
+ if (rows.length && rows[rows.length - 1].from === 'visitor' && rows[rows.length - 1].text === question) rows.pop();
61
+ return rows.slice(-HISTORY_MESSAGES);
62
+ }
63
+
64
+ async function ask(payload, {env, fetchFn}) {
65
+ const local = globalThis[REGISTRY];
66
+ if (local) return local.answer(payload);
67
+ const res = await fetchFn(`${String(env.MANAGER_URL).replace(/\/+$/, '')}/api/fleet/launcher-chat`, {
68
+ method: 'POST',
69
+ headers: {authorization: `Bearer ${env.FLEET_TOKEN}`, 'content-type': 'application/json'},
70
+ body: JSON.stringify(payload),
71
+ signal: AbortSignal.timeout(ASK_MS)
72
+ });
73
+ return {status: res.status, body: await res.json().catch(() => ({}))};
74
+ }
75
+
76
+ /**
77
+ * Ask for an answer to `question` in chat `id`.
78
+ *
79
+ * @param {string} id - the chat
80
+ * @param {string} question - what the visitor just wrote
81
+ * @param {{botName: string, aiContext?: string, aiRules?: string}} chat - the launcher's chat block
82
+ * @returns {Promise<string>} the answer, or '' (no answer: carry on without)
83
+ */
84
+ export async function aiAnswer(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
85
+ if (!aiAvailable(env)) return '';
86
+ try {
87
+ const brief = assistantBrief(chat);
88
+ const {byId} = await knowledgeIndex();
89
+ const count = (await messagesAfter(id, 0)).slice(-(HISTORY_MESSAGES + 1));
90
+ const payload = {
91
+ botName: chat.botName,
92
+ site: {name: brief.site.name, description: brief.site.tagline},
93
+ context: brief.context,
94
+ rules: brief.rules,
95
+ knowledge: knowledgeForAi([...byId.values()]),
96
+ history: historyForAi(count, question),
97
+ question
98
+ };
99
+ const {status, body} = await ask(payload, {env, fetchFn});
100
+ if (status === 200) return typeof body?.answer === 'string' ? body.answer.trim() : '';
101
+ restUntil = Date.now() + (BACKOFF_MS[status] || BACKOFF_MS.other);
102
+ if (status !== 429) log.warn?.(`[chat] AI answers unavailable (${status}): ${String(body?.error || '').slice(0, 120)}`);
103
+ return '';
104
+ } catch (err) {
105
+ restUntil = Date.now() + BACKOFF_MS.other;
106
+ log.warn?.(`[chat] AI answer failed: ${err.message}`);
107
+ return '';
108
+ }
109
+ }