domma-cms 1.49.2 → 1.51.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.
- package/CHANGELOG.md +13 -0
- package/admin/js/lib/chats-arrange.js +2 -2
- package/admin/js/lib/launchers-arrange.js +5 -2
- package/admin/js/lib/site-settings-arrange.js +3 -3
- package/admin/js/templates/chats.html +26 -2
- package/admin/js/templates/docs/usage-chat.html +51 -5
- package/admin/js/templates/docs/usage-launchers.html +2 -0
- package/admin/js/templates/launchers.html +4 -0
- package/admin/js/templates/settings.html +34 -0
- package/admin/js/views/chats.js +5 -5
- package/admin/js/views/launchers.js +107 -33
- package/docs/DommaFeatures.md +4 -0
- package/docs/screenshots/builder-character-site-settings.png +0 -0
- package/docs/screenshots/launcher-della-settings.png +0 -0
- package/docs/screenshots/site-settings-characters.png +0 -0
- package/package.json +2 -1
- package/public/css/characters.css +1 -0
- package/public/css/launcher-chat.css +1 -1
- package/public/css/launchers.css +1 -1
- package/public/images/characters/daisy-poses.png +0 -0
- package/public/images/characters/della-poses.png +0 -0
- package/public/images/characters/dot-poses.png +0 -0
- package/public/js/builder-character.mjs +2 -0
- package/public/js/character-view.mjs +1 -0
- package/public/js/characters.mjs +1 -0
- package/public/js/launcher-chat.mjs +20 -10
- package/public/js/launcher-settings.mjs +6 -2
- package/public/js/launchers.mjs +3 -3
- package/scripts/build.js +1 -0
- package/server/routes/api/chat.js +4 -2
- package/server/routes/api/chats.js +37 -0
- package/server/routes/api/settings.js +36 -2
- package/server/services/assistant.js +67 -0
- package/server/services/chat/ai.js +109 -0
- package/server/services/chat/conversation.js +37 -2
- package/server/services/chat/launcher-bridge.js +3 -1
- package/server/services/chat/saved.js +117 -0
- package/server/services/chat/settings.js +31 -4
- package/server/services/chat/store.js +1 -1
- package/server/services/collectionAccess.js +2 -1
- package/server/services/launchers.js +7 -2
- package/server/services/presetCollections.js +24 -2
- package/server/services/siteGitignore.js +1 -1
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
|
|
1
|
+
import{fillGreeting as Ce,launcherChatAccentCss as Ae}from"/public/js/launcher-settings.mjs?v=20261110-builder-characters";import{CHARACTERS as Ne,characterId as ae,normaliseCharacterSettings as G,chatCharacterState as $e}from"./characters.mjs?v=20261110-builder-characters";import{mountCharacter as we}from"./character-view.mjs?v=20261110-builder-characters";const De={waiting:3e3,open:3e3,bot:9e3,message:2e4},Be=6e3,He="/public/css/launcher-chat.css?v=20261110-builder-characters",se=()=>document.documentElement.classList.contains("dm-reduced-motion")||!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function Oe(){if(document.querySelector("link[data-dm-chat-css]"))return;const t=document.createElement("link");t.rel="stylesheet",t.href=He,t.dataset.dmChatCss="",document.head.appendChild(t)}const ne={get:t=>{try{return globalThis.S?.get?.(t)??null}catch{return null}},set:(t,d)=>{try{globalThis.S?.set?.(t,d)}catch{}},remove:t=>{try{globalThis.S?.remove?globalThis.S.remove(t):globalThis.S?.set?.(t,null)}catch{}}};async function Y(t,d,o,n){const f=n?{"X-Chat-Token":n}:{};let i;try{i=t==="GET"?await H.get(d,{headers:f}):await H.post(d,o,{headers:f})}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(i&&i.error)throw new Error(i.error);return i}const Me=(t,d="time")=>{if(d==="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 d!=="datetime"?n:`${new Date().toDateString()===o.toDateString()?"Today":o.toLocaleDateString([],{day:"numeric",month:"short"})}, ${n}`},re=t=>(String(t||"").trim().match(/[\p{L}\p{N}]/u)?.[0]||"?").toUpperCase();function Pe(t,d=!1,o="",n="time"){const f=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"}]:[],i=t.from==="visitor"?"You":t.name||(t.from==="system"?"":"The team");return{key:`m${t.n}`,n:t.n,from:t.from,fresh:d,cls:M.observable(`dm-chat-msg dm-chat-msg--${t.from}`),name:i,initial:re(i),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:f,starters:[],time:Me(t.at,n)}}function _e(t){const d=o=>o?`${o.from}|${o.name}`:"";return t.forEach((o,n)=>{const f=l=>l&&l.from!=="system"&&d(l)===d(o),i=[`dm-chat-msg dm-chat-msg--${o.from}`];o.from!=="system"&&f(t[n-1])&&i.push("is-cont"),o.from!=="system"&&f(t[n+1])&&i.push("has-next"),o.fresh&&i.push("is-new"),o.cls.value=i.join(" ")}),t}const qe=`
|
|
2
2
|
<div class="dm-chat" data-bind-class="rootClass.value">
|
|
3
|
-
<
|
|
3
|
+
<div class="dm-chat-character" hidden>
|
|
4
|
+
<span class="dm-chat-character-stage"></span>
|
|
5
|
+
<span class="dm-chat-character-copy"><strong data-bind-text="botName.value"></strong><span data-bind-text="characterStatus.value"></span></span>
|
|
6
|
+
</div>
|
|
7
|
+
<p class="dm-chat-status" data-bind-text="statusText.value" data-bind-hidden="inPanel"></p>
|
|
4
8
|
<div class="dm-chat-log" role="log" aria-live="polite" aria-relevant="additions" tabindex="0">
|
|
5
9
|
<div class="dm-chat-items" data-each="items.value key=key"></div>
|
|
6
10
|
<div class="dm-chat-msg dm-chat-msg--bot dm-chat-typing" data-bind-hidden="!typing.value" aria-hidden="true">
|
|
11
|
+
<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
12
|
<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
13
|
</div>
|
|
9
14
|
</div>
|
|
@@ -26,22 +31,27 @@ const ae={waiting:3e3,open:3e3,bot:9e3,message:2e4},se=6e3,ne="/public/css/launc
|
|
|
26
31
|
</div>
|
|
27
32
|
|
|
28
33
|
<div class="dm-chat-actions" data-bind-hidden="ended.value">
|
|
29
|
-
<button type="button" class="dm-chat-action" data-bind-hidden="!
|
|
30
|
-
data-bind-disabled="busy.value" data-bind-text="personLabel.value"></button>
|
|
34
|
+
<button type="button" class="dm-chat-action" data-bind-hidden="!personBelow.value" data-on-click="askPerson"
|
|
35
|
+
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
36
|
<button type="button" class="dm-chat-action dm-chat-action--end" data-bind-hidden="!hasChat.value" data-on-click="end"
|
|
32
37
|
data-bind-disabled="busy.value">End chat</button>
|
|
33
38
|
</div>
|
|
34
39
|
|
|
35
40
|
<form class="dm-chat-compose" data-bind-hidden="ended.value" data-on-submit="send">
|
|
36
41
|
<input type="text" name="website" class="dm-chat-hp" tabindex="-1" autocomplete="off" aria-hidden="true" data-model="hp.value">
|
|
37
|
-
<
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
42
|
+
<div class="dm-chat-field-wrap">
|
|
43
|
+
<textarea class="form-input dm-chat-input" rows="1" maxlength="1000" placeholder="Type your message\u2026"
|
|
44
|
+
aria-label="Your message" data-model="draft.value" data-bind-disabled="ended.value"></textarea>
|
|
45
|
+
<button type="submit" class="btn btn-primary dm-chat-send" aria-label="Send" title="Send"
|
|
46
|
+
data-bind-disabled="!canSend.value"><span data-icon="send" data-icon-size="16" aria-hidden="true"></span></button>
|
|
47
|
+
</div>
|
|
41
48
|
</form>
|
|
42
|
-
|
|
49
|
+
<p class="dm-chat-foot" data-bind-hidden="ended.value" data-bind-text="footText.value"></p>
|
|
50
|
+
</div>`,Ie=`<div data-bind-class="cls.value" data-n="{{n}}">
|
|
51
|
+
<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
52
|
<div class="dm-chat-who"><span>{{name}}</span> <time>{{time}}</time></div>
|
|
44
53
|
<div class="dm-chat-bubble"><span class="dm-chat-text">{{text}}</span><div class="dm-chat-html">{{{html}}}</div></div>
|
|
45
54
|
<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
55
|
<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
|
-
|
|
56
|
+
<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>
|
|
57
|
+
</div>`;export function mountChat(t,{launcherId:d,title:o="Chat",chat:n={}}={}){if(!t||!d||!globalThis.M)return{destroy(){}};Oe();const f=`chat:${d}`,i=Date.now(),l="/api/chat",w=`launcher=${encodeURIComponent(d)}`,r=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||"",character:ae(n.character),characterOptions:G(n.characterOptions),starters:Array.isArray(n.starters)?n.starters:[],personButton:n.personButton==="header"?"header":"below",times:["time","datetime","none"].includes(n.times)?n.times:"time"}),D=M.observable([]),y=M.observable(null),B=M.observable(""),P=M.observable(""),K=M.observable(!1),T=M.observable(!1),O=M.observable(""),S=M.observable(!1),oe=M.observable(""),ie=M.observable(""),W=M.observable("");let b=ne.get(f),L=0,u=!0,C=0,j=0,F=!1;const m=()=>y.value?.status||"none",U=()=>({key:"greet",n:0,from:"bot",fresh:!1,cls:M.observable("dm-chat-msg dm-chat-msg--bot"),name:r.value.botName,initial:re(r.value.botName),avatar:r.value.avatar||"",text:Ce(r.value.greeting,{botName:r.value.botName,site:globalThis.__CMS_SITE__?.title||""}),html:"",links:[],choices:[],time:Me(new Date(i).toISOString(),r.value.times),starters:y.peek()?[]:(r.value.starters||[]).map((e,a)=>({key:`s${a}`,text:e}))}),_=e=>{D.value=_e(e)},h=t.closest?.(".dm-launcher-chat")?.querySelector(".dm-launcher-chat-head")||null,V=()=>{const e=r.value,a=m();return y.value?.askDetails||!(a==="none"||a==="bot")?!1:e.staff||e.askDetails!=="never"},Te=M.computed(V),le=()=>{const e=r.value;return!!(e.bot&&ae(e.character)&&G(e.characterOptions).enabled&&G(e.characterOptions).chats&&!["open","waiting"].includes(m()))},ce=()=>$e({busy:T.value,error:O.value,ended:S.value||m()==="closed",status:m(),askDetails:y.value?.askDetails,replied:D.value.some(e=>e.from==="bot"&&e.n>0)}),q={items:D,draft:B,hp:P,typing:K,busy:T,error:O,detailsName:oe,detailsEmail:ie,detailsMessage:W,ended:M.computed(()=>S.value||m()==="closed"),hasChat:M.computed(()=>!!y.value&&m()!=="closed"),showDetails:M.computed(()=>!!y.value?.askDetails&&m()!=="closed"),detailsWantsMessage:M.computed(()=>m()==="bot"),detailsIntro:M.computed(()=>m()==="waiting"?"So we can reach you if we get cut off:":"Leave your details and we will get back to you."),canAskPerson:Te,personLabel:M.computed(()=>r.value.staff?"Talk to a person":"Leave a message"),personBelow:M.computed(()=>V()&&!(h&&r.value.personButton==="header")),personInHead:M.computed(()=>V()&&!!h&&r.value.personButton==="header"),canSend:M.computed(()=>!T.value&&B.value.trim().length>0&&!(S.value||m()==="closed")),rootClass:M.computed(()=>[se()?"is-still":"",y.value?"has-chat":"",le()?"has-character":""].filter(Boolean).join(" ")),inPanel:!!h,botName:M.computed(()=>r.value.botName),characterStatus:M.computed(()=>({greeting:"Hello. How can I help?",ready:"Here when you need me.",thinking:"Taking a moment to think.",help:"A little input from you, please.",success:"Thank you for chatting."})[ce()]||"Here to help."),botInitial:M.computed(()=>re(r.value.botName)),botAvatar:M.computed(()=>r.value.avatar||""),footText:M.computed(()=>{const e=r.value;return!e.bot||!(m()==="none"||m()==="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=r.value,a=m();return a==="open"?!0:a==="closed"||a==="message"?!1:e.bot||e.staff&&e.staffOnline}),statusText:M.computed(()=>{const e=r.value;switch(m()){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=qe;const v=t.firstElementChild;v.setAttribute("aria-label",o),v.querySelector(".dm-chat-items").innerHTML=Ie;const p=v.querySelector(".dm-chat-log"),k=v.querySelector(".dm-chat-input");function de(e){O.value=e,clearTimeout(j),j=setTimeout(()=>{u&&(O.value="")},Be)}let I=!0;const ue=()=>p.scrollHeight-p.scrollTop-p.clientHeight<80;function me(e=!1){!e&&!I&&!ue()||(I=!0,requestAnimationFrame(()=>{p.scrollTop=p.scrollHeight}))}function X(e){if(!u||!e)return;e.token&&(b=e.token,ne.set(f,b)),e.state&&(y.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(s=>s.n>L);a.length&&(L=Math.max(L,...a.map(s=>s.n)),_([...D.peek(),...a.map(s=>Pe(s,F,r.peek().avatar,r.peek().times))]),me(a.some(s=>s.from==="visitor"))),he()}function he(){if(clearTimeout(C),!u||!b)return;const e=De[m()];e&&(C=setTimeout(J,e))}async function J(){if(!(!u||!b)){if(document.hidden||!v.isConnected){he();return}try{const e=await Y("GET",`${l}/state?${w}&after=${L}`,null,b);if(!u)return;if(!e.state){Q();return}X(e)}catch{clearTimeout(C),u&&(C=setTimeout(J,15e3))}}}function Q(){b=null,ne.remove(f),y.value=null,L=0,_([U()])}async function A(e,a,{thinking:s=!1}={}){if(T.peek())return!1;T.value=!0,O.value="",s&&!se()&&(K.value=!0);const g=Date.now();try{const c=await Y("POST",`${l}/${e}`,{launcher:d,after:L,...a},b);if(s&&!se()){const x=450-(Date.now()-g);x>0&&await new Promise(E=>setTimeout(E,x))}return X(c),!0}catch(c){return u&&de(c.message),!1}finally{u&&(T.value=!1,K.value=!1)}}async function Z(){const e=B.peek().trim();if(!e||T.peek()||S.peek())return!1;if(!b){const s=1700-(Date.now()-i);if(s>0&&await new Promise(g=>setTimeout(g,s)),!u)return!1}return await A("send",{text:e,page:location.pathname,_hp:P.peek(),_t:i},{thinking:!0})&&(B.value="",k.focus()),!1}const R=h?h.closest(".dm-launcher-chat"):v,ee=M.effect(()=>{const e=Ae(r.value);for(const[a,s]of[["--chat-accent",e.accent],["--chat-accent-text",e.accentText]])s?R.style.setProperty(a,s):R.style.removeProperty(a)}),xe=M.applyBindings(q,v,{methods:{send:()=>(Z(),!1),sendDetails:()=>(A("details",{name:oe.peek(),email:ie.peek(),message:W.peek()}).then(e=>{e&&(W.value="")}),!1),askPerson:()=>A("person",{page:location.pathname,_hp:P.peek(),_t:i},{thinking:!0}),end:async()=>{b&&await A("end",{})&&(S.value=!0,clearTimeout(C))},restart:()=>{S.value=!1,Q(),k.focus()}}});window.Domma?.icons?.scan?.(v);let z=null,pe=[];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 g=document.createElement("span");g.className="dm-launcher-chat-sub",g.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(g);const c=document.createElement("button");c.type="button",c.className="dm-launcher-chat-person",c.setAttribute("data-bind-hidden","!personInHead.value"),c.setAttribute("data-bind-title","personLabel.value"),c.setAttribute("data-bind-aria-label","personLabel.value"),c.setAttribute("data-bind-disabled","busy.value"),c.innerHTML='<span data-icon="headphones" data-icon-size="18" aria-hidden="true"></span>',h.insertBefore(c,h.querySelector(".dm-launcher-chat-close")),c.addEventListener("click",()=>A("person",{page:location.pathname,_hp:P.peek(),_t:i},{thinking:!0})),window.Domma?.icons?.scan?.(c),pe=[a,g,c],z=M.applyBindings(q,a)||null;const x=M.applyBindings(q,g),E=M.applyBindings(q,c),Se=[z,x,E];z={dispose:()=>Se.forEach(Le=>Le?.dispose?.())}}let N=[],fe="",$=null;const Ee=M.effect(()=>{const e=r.value,a=le(),s=a?ae(e.character):"",g=G(e.characterOptions),c=ce(),x=v.querySelector(".dm-chat-character");x.hidden=!a,s!==fe&&(N.forEach(E=>E.destroy()),N=[],$?.classList.remove("dm-character-avatar"),fe=s,s?(N.push(we(x.querySelector(".dm-chat-character-stage"),{id:s,animated:g.animated})),$=h?.querySelector(".dm-launcher-chat-avatar"),$&&($.classList.add("dm-character-avatar"),N.push(we($,{id:s,portrait:!0,animated:!1}))),v.style.setProperty("--dm-character-art",`url("${Ne[s].artwork}")`)):v.style.removeProperty("--dm-character-art")),N.forEach(E=>E.setState(c,g.animated))}),be=e=>{e.key==="Enter"&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),Z())};k.addEventListener("keydown",be);const ve=()=>{k.style.height="auto",k.style.height=Math.min(k.scrollHeight,120)+"px"};k.addEventListener("input",ve);const ge=e=>{const a=e.target.closest(".dm-chat-starter");if(a&&p.contains(a)){B.value=a.dataset.text||"",Z();return}const s=e.target.closest(".dm-chat-choice");!s||!p.contains(s)||A("pick",{n:Number(s.dataset.n),i:Number(s.dataset.i)},{thinking:!0})};p.addEventListener("click",ge);const ye=()=>{I=ue()};p.addEventListener("scroll",ye,{passive:!0});const te=typeof ResizeObserver=="function"?new ResizeObserver(()=>{I&&(p.scrollTop=p.scrollHeight)}):null;te?.observe(p),te?.observe(v.querySelector(".dm-chat-items"));const ke=()=>{!document.hidden&&u&&b&&J()};return document.addEventListener("visibilitychange",ke),_([U()]),(async()=>{try{const e=await Y("GET",`${l}/config?${w}`);if(!u)return;r.value={...r.peek(),...e},y.peek()||_([U(),...D.peek().filter(a=>a.key!=="greet")])}catch(e){u&&de(e.message)}if(!b||!u){F=!0;return}try{const e=await Y("GET",`${l}/state?${w}&after=0`,null,b);if(!u)return;if(!e.state){Q();return}X(e),me(!0)}catch{}F=!0})(),{destroy(){u&&(u=!1,clearTimeout(C),clearTimeout(j),k.removeEventListener("keydown",be),k.removeEventListener("input",ve),p.removeEventListener("click",ge),p.removeEventListener("scroll",ye),te?.disconnect(),document.removeEventListener("visibilitychange",ke),xe?.dispose?.(),z?.dispose?.(),Ee?.(),N.forEach(e=>e.destroy()),$?.classList.remove("dm-character-avatar"),ee?.dispose?.(),typeof ee=="function"&&ee(),R.style.removeProperty("--chat-accent"),R.style.removeProperty("--chat-accent-text"),pe.forEach(e=>e.remove()),t.innerHTML="")}}}
|
|
@@ -1,2 +1,6 @@
|
|
|
1
|
-
import{cssClasses as
|
|
2
|
-
`).replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g," ").trim().slice(0,LAUNCHER_LIMITS.greetingMax):
|
|
1
|
+
import{cssClasses as M}from"./css-classes.mjs";import{characterId as b}from"./characters.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:"",character:"",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 y=/^[a-z0-9][a-z0-9-]{0,39}$/,R=/^\/[A-Za-z0-9._~\-/]*$/,C=/^[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 E(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 L(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="")):C.test(n)||(n=""),i==="chat"&&(n="");const a=LAUNCHER_DEFAULTS.action,h=c(t.widthUnit,LAUNCHER_WIDTH_UNITS,a.widthUnit),s=c(t.heightUnit,LAUNCHER_HEIGHT_UNITS,a.heightUnit);return{type:i,kind:r,ref:n,title:l(t.title,LAUNCHER_LIMITS.titleMax),size:c(t.size,LAUNCHER_MODAL_SIZES,a.size),side:c(t.side,LAUNCHER_SIDES,a.side),width:c(t.width,LAUNCHER_SLIDEOVER_WIDTHS,a.width),customWidth:f(t.customWidth,h==="%"?90:a.customWidth,...h==="%"?LAUNCHER_LIMITS.widthPct:LAUNCHER_LIMITS.widthPx),widthUnit:h,height:c(t.height,LAUNCHER_MODAL_HEIGHTS,a.height),customHeight:f(t.customHeight,s==="px"?600:a.customHeight,...s==="px"?LAUNCHER_LIMITS.heightPx:LAUNCHER_LIMITS.heightVh),heightUnit:s}}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),character:b(t.character),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",a={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,s)=>{const u=a[s.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(s=>s+s).join(""):o.slice(1,7),[n,a,h]=[0,2,4].map(s=>parseInt(r.slice(s,s+2),16)/255).map(s=>s<=.03928?s/12.92:((s+.055)/1.055)**2.4);i=.2126*n+.7152*a+.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),a=(Array.isArray(n.paths)?n.paths:typeof n.paths=="string"?n.paths.split(/[\n,]+/):[]).map(normaliseLauncherPath).filter(Boolean).filter((s,u,p)=>p.indexOf(s)===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"&&y.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:E(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:a},audience:c(t.audience,LAUNCHER_AUDIENCES,i.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 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:a,...h}=e.chat;t.chat=h}return t}export function launcherSpot(e,{w:t,h:i,vw:o,vh:r,offsetX:n,offsetY:a}){const h=e[1]==="L"?"L":e[1]==="R"?"R":"C",s=e[0],u=h==="L"?n:h==="R"?o-t-n:Math.round((o-t)/2+n),p=s==="T"?a:s==="B"?r-i-a:Math.round((r-i)/2+a);return{left:u,top:p}}const g=12,_=(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 a=t.top;for(let h=0;h<=r.length;h++){const s={left:t.left,top:a,right:t.left+i,bottom:a+o},u=r.find(p=>p&&p.right>p.left&&p.bottom>p.top&&_(s,p));if(!u)break;a=Math.round(n?u.top-g-o:u.bottom+g)}return{left:t.left,top:a}}
|
package/public/js/launchers.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{launcherModalBox as
|
|
1
|
+
import{LAUNCHER_LIMITS as C,launcherChatBox as mt,launcherModalBox as pt,launcherSpot as ft,launcherStack as vt}from"/public/js/launcher-settings.mjs?v=20261110-builder-characters";const V=i=>`launcher-chat-size:${i}`,bt=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{}};import{mountCharacter as gt}from"./character-view.mjs?v=20261110-builder-characters";const 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"},yt=i=>String(i??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),et=()=>document.documentElement.classList.contains("dm-reduced-motion")||matchMedia("(prefers-reduced-motion: reduce)").matches,wt=`
|
|
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>`,
|
|
6
|
+
</button>`,xt=`
|
|
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 Mt(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 r=document.createElement("iframe");if(r.className="dm-launcher-frame"+(c?" is-fill":""),r.title=i.action.title,r.src=`/_launcher/${encodeURIComponent(i.id)}`,r.setAttribute("loading","eager"),!c){let u=null;r.addEventListener("load",()=>{const H=r.contentDocument;if(!H?.body)return;const S=H.querySelector(".site-content")||H.body,R=()=>{r.style.height=`${Math.ceil(S.getBoundingClientRect().height)}px`};R(),u?.disconnect(),u=new ResizeObserver(R),u.observe(S)})}return r}export function mountLaunchers(i){if(!Array.isArray(i)||!i.length||document.querySelector(".dm-launchers"))return null;const c=M.observable(matchMedia(J).matches),r=document.createElement("div");r.className="dm-launchers";const u=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},d=M.observable(-9999),m=M.observable(-9999);return{id:t.id,label:t.label,icon:t.icon,pill:e,launcher:t,look:n,left:d,top:m,cls:["dm-launcher--"+t.action.type,e?"dm-launcher--pill":"",t.class].filter(Boolean).join(" "),style:M.computed(()=>({...a(c.value),left:`${d.value}px`,top:`${m.value}px`})),expanded:M.observable("false"),hidden:M.computed(()=>t.disc===!1||t.devices==="desktop"&&c.value||t.devices==="phone"&&!c.value)}});r.innerHTML='<div class="dm-launchers-list" data-each="rows.value key=id"></div>',r.firstElementChild.innerHTML=wt;const H=M.applyBindings({rows:M.observable(u)},r);document.body.appendChild(r),nt(r);const S=t=>r.querySelector(`.dm-launcher[data-id="${CSS.escape(t)}"]`),R=[];for(const t of u){const n=t.launcher.chat;if(!n?.bot||!n.character||n.characterOptions?.enabled===!1||n.characterOptions?.launchers===!1)continue;const e=S(t.id);if(!e)continue;e.classList.add("dm-character-disc");const a=e.querySelector(".dm-launcher-label"),d=gt(e,{id:n.character,portrait:!0,animated:!1});a&&e.appendChild(a),R.push(d)}const at={TL:"right",ML:"right",BL:"right",TR:"left",MR:"left",BR:"left",TC:"bottom",BC:"top"},B=new Map;for(const t of u){const n=t.launcher.tooltip,e=S(t.id);if(!(!n||!e||typeof E.tooltip!="function"))try{B.set(t.id,E.tooltip(e,{content:n,position:at[t.launcher.position]||"top",trigger:"hover focus",className:"dm-launcher-tip"}))}catch{}}function D(){const t=document.documentElement.clientWidth,n=window.innerHeight,e=[...document.querySelectorAll(Q)].filter(a=>!r.contains(a)&&getComputedStyle(a).position==="fixed"&&getComputedStyle(a).display!=="none").map(Mt);for(const a of u){const d=S(a.id);if(!d||d.hidden)continue;const m=a.look(c.peek()),o=d.offsetWidth,v=d.offsetHeight,x=ft(m.position,{w:o,h:v,vw:t,vh:n,offsetX:m.offsetX,offsetY:m.offsetY}),T=vt(m.position,x,{w:o,h:v},e),z=Math.max(0,Math.min(t-o,T.left)),_=Math.max(0,Math.min(n-v,T.top));a.left.value=z,a.top.value=_,e.push({left:z,top:_,right:z+o,bottom:_+v})}}let q=0;const A=()=>{cancelAnimationFrame(q),q=requestAnimationFrame(D)},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 P=matchMedia(J),U=()=>{c.value=P.matches,A()};P.addEventListener?.("change",U),window.addEventListener("resize",A),window.addEventListener("load",A,{once:!0}),D();let g=null;const it=M.effect(()=>{const t=u.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=g;g=null,t&&(t.row.expanded.value="false",t.close())}function ct(t){const n=t.launcher,e=pt(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:()=>{g?.row===t&&(g=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 st(t){const n=t.launcher,e=E.slideover({title:yt(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:()=>{g?.row===t&&(g=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 rt(t,n){const e=t.launcher,a=S(t.id),d=a&&!a.hidden?a:null,m=d||(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=xt;const v=M.observable("");let x=null,T=!1;const z=()=>{if(!T){T=!0;try{x?.destroy?.()}catch{}_.dispose?.(),o.remove(),document.removeEventListener("keydown",G),window.removeEventListener("resize",O),g?.row===t&&(g=null,t.expanded.value="false"),(m?.isConnected?m:null)?.focus()}},_=M.applyBindings({title:e.action.title,note:v,close:z},o),G=l=>{l.key!=="Escape"||l.defaultPrevented||!o.contains(document.activeElement)||(l.preventDefault(),z())},O=()=>{if(c.peek()){o.classList.add("is-full"),o.removeAttribute("style");return}o.classList.remove("is-full");const l=document.documentElement.clientWidth,s=window.innerHeight,N=e.chat?.resizable!==!1&&bt(e.id)||mt(e.chat||{}),y=Math.min(Math.max(C.chatWidth[0],Number(N.width)),C.chatWidth[1],l-24),w=Math.min(Math.max(C.chatHeight[0],Number(N.height)),C.chatHeight[1],s-24),p=L=>Math.max(12,Math.min(l-y-12,L)),h=L=>Math.max(12,Math.min(s-w-12,L));let b,k;if(!d){b=p(e.position[1]==="L"?24:l-y-24),k=h(s-w-24),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`});return}const f=d.getBoundingClientRect(),$=f.left+f.width/2>l/2;e.position[0]==="M"?(b=p($?f.left-y-12:f.right+12),k=h(f.top+f.height/2-w/2)):(b=p($?f.right-y:f.left),k=e.position[0]==="T"?h(f.bottom+12):h(f.top-w-12)),Object.assign(o.style,{left:`${b}px`,top:`${k}px`,width:`${y}px`,height:`${w}px`})};if(document.body.appendChild(o),O(),e.chat?.resizable!==!1){const l=document.createElement("div");l.className="dm-launcher-chat-grip",l.setAttribute("role","separator"),l.setAttribute("aria-label","Resize the chat"),l.title="Drag to resize",o.appendChild(l);let s=null;const N=p=>{if(!s)return;const h=document.documentElement.clientWidth,b=window.innerHeight,k=(p.clientX-s.x)*(s.fromLeft?-1:1),f=(p.clientY-s.y)*(s.fromTop?-1:1),$=Math.round(Math.min(Math.max(C.chatWidth[0],s.w+k),C.chatWidth[1],h-24)),L=Math.round(Math.min(Math.max(C.chatHeight[0],s.h+f),C.chatHeight[1],b-24)),ht=s.fromLeft?s.right-$:s.left,ut=s.fromTop?s.bottom-L:s.top;Object.assign(o.style,{width:`${$}px`,height:`${L}px`,left:`${Math.max(12,Math.min(h-$-12,ht))}px`,top:`${Math.max(12,Math.min(b-L-12,ut))}px`}),s.size={width:$,height:L}},y=()=>{s&&(s.size&&Z(e.id,s.size),s=null,o.classList.remove("is-resizing"),window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",y))},w=()=>{const[p,h]=String(e.position||"BR");l.dataset.corner=`${p==="T"?"b":"t"}${h==="L"?"r":"l"}`};w(),l.addEventListener("pointerdown",p=>{if(c.peek())return;p.preventDefault();const h=o.getBoundingClientRect(),b=l.dataset.corner;s={x:p.clientX,y:p.clientY,w:h.width,h:h.height,left:h.left,top:h.top,right:h.right,bottom:h.bottom,fromLeft:b[1]==="l",fromTop:b[0]==="t"},o.classList.add("is-resizing"),window.addEventListener("pointermove",N),window.addEventListener("pointerup",y)}),l.addEventListener("dblclick",()=>{Z(e.id,null),O(),w()})}nt(o),document.addEventListener("keydown",G),window.addEventListener("resize",O);const dt=o.querySelector(".dm-launcher-chat-body");return import("/public/js/launcher-chat.mjs?v=20261110-builder-characters").then(l=>{if(!T){if(typeof l.mountChat!="function")throw new Error("no mountChat");x=l.mountChat(dt,{launcherId:e.id,title:e.action.title,chat:e.chat||{}})}}).catch(()=>{T||(v.value="Chat is unavailable right now. Please try again later.")}),o.querySelector(".dm-launcher-chat-close")?.focus(),z}function I(t,n=null){const e=u.find(o=>o.id===t);if(!e)return;const a=g?.row===e;if(Y(),a)return;e.expanded.value="true";try{B.get(e.id)?.close()}catch{}const d=e.launcher.action.type,m=d==="chat"?rt(e,n):d==="slideover"?st(e):ct(e);g={row:e,close:m}}const j=t=>{const n=t.target.closest(".dm-launcher");n&&I(n.dataset.id)};r.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||r.contains(t.target))return;const n=t.target instanceof Element?lt(t.target):null;!n||!u.some(e=>e.id===n.id)||(t.preventDefault(),I(n.id,n.el))};document.addEventListener("click",X);const W=F.exec(location.hash);return W&&u.some(t=>t.id===W[1])&&(history.replaceState(history.state,"",location.pathname+location.search),setTimeout(()=>I(W[1]),0)),{place:D,launch:I,destroy(){Y(),it?.(),document.documentElement.classList.remove("dm-launcher-covering"),R.forEach(t=>t.destroy());for(const t of B.values())try{t.destroy()}catch{}B.clear(),cancelAnimationFrame(q),K.disconnect(),P.removeEventListener?.("change",U),window.removeEventListener("resize",A),window.removeEventListener("load",A),r.removeEventListener("click",j),document.removeEventListener("click",X),H?.dispose?.(),r.remove()}}}typeof window<"u"&&Array.isArray(window.__CMS_LAUNCHERS__)&&window.M&&window.E&&(window.DommaLaunchers=mountLaunchers(window.__CMS_LAUNCHERS__));
|
package/scripts/build.js
CHANGED
|
@@ -28,6 +28,7 @@ const COPY_AS_IS = [
|
|
|
28
28
|
'public/js/celebrations/licenses',
|
|
29
29
|
// Third-party browser files, shipped byte-for-byte as their authors built them.
|
|
30
30
|
'public/js/vendor',
|
|
31
|
+
'public/images/characters',
|
|
31
32
|
'public/examples/new-celebrations.html',
|
|
32
33
|
'CLAUDE.md',
|
|
33
34
|
'LICENSE',
|
|
@@ -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,
|
|
121
|
+
const {greeting, botName, bot, staff, askDetails, accent, accentText, avatar, starters, personButton, times, character, characterOptions} = launcher.chat;
|
|
122
|
+
return {greeting, botName, bot, staff, askDetails, accent, accentText, avatar, starters, personButton, times, character, characterOptions, 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'});
|
|
@@ -18,10 +18,13 @@ import fs from 'fs/promises';
|
|
|
18
18
|
import path from 'path';
|
|
19
19
|
import {fileURLToPath} from 'url';
|
|
20
20
|
import * as cache from '../../services/cache/index.js';
|
|
21
|
-
import {normaliseAdminPath} from '../../services/roles.js';
|
|
21
|
+
import {normaliseAdminPath, getPermissionsFor} from '../../services/roles.js';
|
|
22
|
+
import {getEffectiveRoles} from '../../services/userRoles.js';
|
|
22
23
|
import {cssClassProblems} from '../../../public/js/css-classes.mjs';
|
|
23
24
|
import {motionFooterMirror, normaliseMotionSettings} from '../../services/motionSettings.js';
|
|
24
25
|
import {invalidateMeasurementId, measurementIdOf, normaliseMeasurementId} from '../../services/googleAnalytics.js';
|
|
26
|
+
import {assistantProblem, normaliseAssistant} from '../../services/assistant.js';
|
|
27
|
+
import {normaliseCharacterSettings} from '../../../public/js/characters.mjs';
|
|
25
28
|
|
|
26
29
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
27
30
|
const CUSTOM_CSS_FILE = path.resolve(__dirname, '../../../content/custom.css');
|
|
@@ -93,6 +96,24 @@ export async function settingsRoutes(fastify) {
|
|
|
93
96
|
}
|
|
94
97
|
});
|
|
95
98
|
|
|
99
|
+
// Tools may read presentation preferences without access to SMTP or other site settings.
|
|
100
|
+
fastify.get('/characters', {preHandler: [authenticate]}, async (request) => ({
|
|
101
|
+
settings: normaliseCharacterSettings(getConfig('site').characters),
|
|
102
|
+
canUpdate: getEffectiveRoles(request.user).some(role => getPermissionsFor('settings', 'update').includes(role))
|
|
103
|
+
}));
|
|
104
|
+
fastify.put('/characters/:id', canUpdate, async (request, reply) => {
|
|
105
|
+
const id = request.params.id;
|
|
106
|
+
if (!['dot', 'daisy'].includes(id)) return reply.code(404).send({error: 'No such builder character.'});
|
|
107
|
+
if (!request.body || typeof request.body.enabled !== 'boolean' || Object.keys(request.body).some(key => key !== 'enabled')) {
|
|
108
|
+
return reply.code(400).send({error: 'Send an enabled checkbox value.'});
|
|
109
|
+
}
|
|
110
|
+
const site = getConfig('site');
|
|
111
|
+
site.characters = normaliseCharacterSettings({...site.characters, [id]: request.body.enabled});
|
|
112
|
+
saveConfig('site', site);
|
|
113
|
+
await cache.invalidateTags(['site']);
|
|
114
|
+
return {settings: site.characters, canUpdate: true};
|
|
115
|
+
});
|
|
116
|
+
|
|
96
117
|
fastify.get('/settings', canRead, async (request, reply) => {
|
|
97
118
|
const config = getConfig('site');
|
|
98
119
|
const safeConfig = { ...config };
|
|
@@ -127,7 +148,9 @@ export async function settingsRoutes(fastify) {
|
|
|
127
148
|
// Google Analytics (Site Settings > Analytics) - services/googleAnalytics.js.
|
|
128
149
|
'googleAnalytics',
|
|
129
150
|
// The "Reduce motion" control (Site Settings > Reduce motion) - services/motionSettings.js.
|
|
130
|
-
'motion'
|
|
151
|
+
'motion',
|
|
152
|
+
// What every AI answer knows about the site and the rules it keeps (services/assistant.js).
|
|
153
|
+
'assistant', 'characters'
|
|
131
154
|
]);
|
|
132
155
|
const unknownKeys = Object.keys(data).filter(k => !ALLOWED_KEYS.has(k));
|
|
133
156
|
if (unknownKeys.length > 0) {
|
|
@@ -167,6 +190,16 @@ export async function settingsRoutes(fastify) {
|
|
|
167
190
|
if (raw && !id) return reply.status(400).send({error: 'Google Analytics: a measurement ID looks like G-XXXXXXXXXX.'});
|
|
168
191
|
data.googleAnalytics = {measurementId: id};
|
|
169
192
|
}
|
|
193
|
+
if ('characters' in data && (!data.characters || typeof data.characters !== 'object' || Array.isArray(data.characters))) {
|
|
194
|
+
return reply.status(400).send({error: 'Builders and Bots: send an object.'});
|
|
195
|
+
}
|
|
196
|
+
if ('assistant' in data) {
|
|
197
|
+
const a = data.assistant;
|
|
198
|
+
if (!a || typeof a !== 'object' || Array.isArray(a)) return reply.status(400).send({error: 'AI assistant: send {context, rules}.'});
|
|
199
|
+
const problem = assistantProblem(a);
|
|
200
|
+
if (problem) return reply.status(400).send({error: `AI assistant: ${problem}`});
|
|
201
|
+
data.assistant = normaliseAssistant(a);
|
|
202
|
+
}
|
|
170
203
|
if ('adminHome' in data) {
|
|
171
204
|
// An admin route, or blank for the built-in dashboard.
|
|
172
205
|
const home = data.adminHome == null || data.adminHome === '' ? '/' : normaliseAdminPath(data.adminHome);
|
|
@@ -190,6 +223,7 @@ export async function settingsRoutes(fastify) {
|
|
|
190
223
|
// The Reduce motion control: stored whitelisted, with the footer keys it used to live
|
|
191
224
|
// under kept in step for older readers. A client that still writes only those footer
|
|
192
225
|
// keys (fleet tooling) moves the block with them, so its change is not overruled.
|
|
226
|
+
if ('characters' in data) merged.characters = normaliseCharacterSettings(merged.characters);
|
|
193
227
|
if ('motion' in data) {
|
|
194
228
|
if (data.motion !== null && (typeof data.motion !== 'object' || Array.isArray(data.motion))) {
|
|
195
229
|
return reply.status(400).send({error: 'Reduce motion: send an object.'});
|
|
@@ -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
|
+
}
|