domma-cms 1.59.0 → 1.61.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/admin/css/admin.css +1 -1
  3. package/admin/index.html +7 -1
  4. package/admin/js/app.js +7 -2
  5. package/admin/js/lib/ai-assist-settings-arrange.js +1 -0
  6. package/admin/js/lib/ai-assist.js +1 -0
  7. package/admin/js/lib/chat-presence.js +1 -0
  8. package/admin/js/lib/chat-toast.js +2 -2
  9. package/admin/js/lib/notifications-arrange.js +1 -1
  10. package/admin/js/lib/site-settings-arrange.js +3 -3
  11. package/admin/js/templates/ai-assist-builders.html +29 -0
  12. package/admin/js/templates/ai-assist-settings.html +80 -0
  13. package/admin/js/templates/chats.html +1 -1
  14. package/admin/js/templates/docs/usage-chat.html +20 -7
  15. package/admin/js/templates/settings.html +7 -27
  16. package/admin/js/views/ai-assist-builders.js +1 -0
  17. package/admin/js/views/ai-assist-settings.js +1 -0
  18. package/admin/js/views/chat-knowledge.js +6 -6
  19. package/admin/js/views/chats.js +4 -4
  20. package/admin/js/views/index.js +1 -1
  21. package/admin/js/views/login.js +1 -1
  22. package/admin/js/views/settings.js +3 -3
  23. package/docs/DommaFeatures.md +1 -1
  24. package/docs/plugin-development.md +26 -0
  25. package/package.json +1 -1
  26. package/server/routes/api/admin-assistant.js +14 -1
  27. package/server/routes/api/auth.js +4 -1
  28. package/server/routes/api/theme.js +2 -6
  29. package/server/server.js +12 -0
  30. package/server/services/aiAssist.js +79 -0
  31. package/server/services/chat/ai.js +1 -1
  32. package/server/services/chat/conversation.js +12 -4
  33. package/server/services/plugins.js +9 -1
  34. package/server/services/themeSettings.js +11 -0
@@ -0,0 +1 @@
1
+ import{apiRequest as L}from"../api.js";import{helpPopovers as B}from"../lib/help-popover.js";import{SHAPES as j,whileLoading as D}from"../lib/loading.js";import{openMenuAt as $,viewLifetime as N}from"../lib/tool-kit.js";import{fmtDateTime as P}from"../lib/dates.js";import{builderChatRows as R,mountAiAssistTabs as T,rememberAiAssistState as K}from"../lib/ai-assist.js";const U=/^#\/ai-assist\/builders\b/,d=N(U);async function z(s){try{const n=await L(s.list.replace(/^\/api(?=\/)/,""));return{builder:s,rows:R(n,s),error:""}}catch(n){const i=String(n?.message||"");return{builder:s,rows:[],error:/403|permission|not allowed/i.test(i)?"Not available to you.":"Could not load its chats just now."}}}function o(s,n,i){const l=document.createElement(s);return n&&(l.className=n),i!==void 0&&(l.textContent=i),l}export const aiAssistBuildersView={templateUrl:"/admin/js/templates/ai-assist-builders.html",async onMount(s){d.reset();const n=s.get(0),i=n.querySelector(".aib")||n;let l=!1;d.add(()=>{l=!0});const x=()=>!l&&i.isConnected,w=M.observable(!0),y=M.observable([]),O=M.applyBindings({loading:w,groups:y},i);d.add(()=>O.dispose()),d.add(B(i,{position:"bottom"}));let u=[];try{u=await D(i.querySelector(".dm-loading-slot"),(async()=>{const e=await L("/ai-assist");return K(e),Promise.all((e?.builders||[]).map(z))})(),j.rows)}catch{u=[]}if(!x())return;T(n,"builders");const r=i.querySelector(".aib-groups");r.replaceChildren();const p=new Map;for(const e of u){const t=o("section","card aib-group"),c=o("div","aib-head"),f=o("span");f.dataset.icon="sparkles",f.dataset.iconSize="16";const v=o("a","btn btn-sm btn-outline",`Open ${e.builder.label}`);v.href=e.builder.url,c.append(f,o("h3","",e.builder.label),v),t.append(c),e.error?t.append(o("p","aib-note",e.error)):e.rows.length||t.append(o("p","aib-note","No chats yet. Open the builder to start one."));const A=o("div","aib-list");for(const a of e.rows){const S=`${e.builder.plugin}:${a.id}`;p.set(S,{row:a,builder:e.builder});const b=o("div","aib-row");b.tabIndex=0,b.dataset.key=S,b.setAttribute("role","link");const C=o("div");C.append(o("div","aib-title",a.title),o("div","aib-meta",[a.when?P(a.when):"",a.who].filter(Boolean).join(" \xB7 ")));const h=o("button","aib-kebab","\u22EE");h.type="button",h.setAttribute("aria-label",`Actions for ${a.title}`),b.append(C,a.status?o("span","aib-chip",a.status):o("span"),h),A.append(b)}t.append(A),r.append(t)}y.value=u,w.value=!1;const m=e=>{const t=p.get(e);t&&(location.hash=t.row.href)},g=e=>{const t=e.target.closest(".aib-kebab");if(t){$(t);return}const c=e.target.closest(".aib-row");c&&m(c.dataset.key)},k=e=>{const t=e.target.closest(".aib-row");t&&(e.key==="Enter"&&(e.preventDefault(),m(t.dataset.key)),e.key==="F10"&&e.shiftKey&&(e.preventDefault(),$(t)))};r.addEventListener("click",g),r.addEventListener("keydown",k),d.add(()=>{r.removeEventListener("click",g),r.removeEventListener("keydown",k)});const q=E.contextMenu?.(r,{cursor:"glyph",match:".aib-row",inherit:!1,density:"compact",items:e=>{const t=p.get(e?.dataset?.key);return t?[{header:t.row.title},{label:`Open in ${t.builder.label}`,icon:"external-link",action:()=>m(e.dataset.key)},{label:`Open ${t.builder.label}`,icon:"sparkles",action:()=>{location.hash=t.builder.url}}]:[]}});d.add(()=>q?.destroy?.()),I.scan(i)}};
@@ -0,0 +1 @@
1
+ import{apiRequest as l}from"../api.js";import{addBannerAction as z}from"../lib/plugin-chrome.js";import{helpPopovers as G}from"../lib/help-popover.js";import{SHAPES as Q,whileLoading as X}from"../lib/loading.js";import{mountAiAssistTabs as x}from"../lib/ai-assist.js";import{characterOptions as Z,checkForm as P,formFromSettings as T,LIMITS as K,payloadFromForm as N,snapshot as k}from"../lib/ai-assist-settings-arrange.js";import{CHARACTERS as _}from"../../../public/js/characters.mjs";const C=/^\/ai-assist\/settings(\?.*)?$/;let n=null,U=!1;function ee(){U||!window.R?.use||(U=!0,R.use((r,i,o)=>!(C.test(i?.path||"")&&!C.test(r?.path||""))||!n?.dirty()?o():E.confirm("You have unsaved AI Assist settings. Leave anyway?").then(c=>{c?o():history.replaceState(null,"","#/ai-assist/settings")})),M.subscribe("router:afterChange",({to:r}={})=>{if(n&&!C.test(r?.path||"")){const i=n;n=null,i.dispose()}}))}export const aiAssistSettingsView={templateUrl:"/admin/js/templates/ai-assist-settings.html",async onMount(r){if(ee(),n){const e=n;n=null,e.dispose()}const i=[],o=e=>(i.push(e),e);let p=!1;const c=r.get(0),a=c.querySelector(".aia")||c,m=()=>!p&&a.isConnected;x(c,"settings");const O=M.observable(!0);let u={},f=[],v={chats:!0};try{[u,f,v]=await X(a.querySelector(".dm-loading-slot"),Promise.all([l("/settings"),l("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]),l("/ai-assist").catch(()=>({chats:!0}))]),Q.rows)}catch(e){if(!m())return;a.querySelector(".dm-loading-slot").textContent=`Could not load the settings: ${e.message||e}`;return}if(!m())return;const h=f.includes("settings")||f.includes("settings.update");v?.chats===!1&&x(c,"settings",{chats:!1});const g=M.observable(T(u)),A=g.peek(),s=Object.fromEntries(Object.entries(A).map(([e,t])=>[e,M.observable(t)])),y=()=>Object.fromEntries(Object.entries(s).map(([e,t])=>[e,t.peek()])),j=()=>Object.fromEntries(Object.entries(s).map(([e,t])=>[e,t.value])),L=M.observable(k(A)),d=M.observable(!1),b=M.computed(()=>k(j())!==L.value),B=M.computed(()=>P(j())),D=M.computed(()=>`${s.aiContext.value.length} / ${K.context}`),H=M.computed(()=>`${s.aiRules.value.length} / ${K.rules}`),F=a.querySelector("#aia-admin-character");for(const e of Z(_))F.append(new Option(e.label,e.value));F.value=s.adminCharacter.peek();async function w(){if(d.peek()||!h)return;const e=P(y());if(e){E.toast(e,{type:"error"});return}d.value=!0;try{await l("/settings",{method:"PUT",body:JSON.stringify(N(y()))});const t=await l("/settings").catch(()=>({...u,...N(y())}));if(!m())return;u=t;const S=T(t);for(const[W,Y]of Object.entries(S))s[W].value=Y;g.value=S,L.value=k(S),window.dispatchEvent(new Event("admin-assistant:settings")),E.toast("AI Assist settings saved",{type:"success"})}catch(t){E.toast(`Not saved: ${t.message||t}`,{type:"error"})}finally{d.value=!1}}function V(){for(const[e,t]of Object.entries(g.peek()))s[e].value=t}O.value=!1;const J=M.applyBindings({...s,loading:O,dirty:b,saving:d,problem:B,contextCount:D,rulesCount:H,canEdit:h,chatsOn:v?.chats!==!1},a,{methods:{save:()=>w(),discard:()=>V()}});o(()=>J.dispose()),o(G(a,{position:"bottom"})),h&&z(r,{id:"ai-assist-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>w()});const $=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),w())};document.addEventListener("keydown",$,!0),o(()=>document.removeEventListener("keydown",$,!0));const q=e=>{b.peek()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",q),o(()=>window.removeEventListener("beforeunload",q)),n={dirty:()=>b.peek(),dispose(){p=!0,i.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(a)}};
@@ -1,16 +1,16 @@
1
- import{apiRequest as ce}from"../api.js";import{helpPopovers as W}from"../lib/help-popover.js";import{onceClosed as de,openMenuAt as H,viewLifetime as ue}from"../lib/tool-kit.js";import{arrangeKnowledge as pe,describeTest as F,linksToRows as ke,mayDo as be,rowsToLinks as Y}from"../lib/chats-arrange.js";const he=/^#\/launchers\/knowledge\b/,c=(f,l="GET",g)=>ce(f,{method:l,...g!==void 0?{body:JSON.stringify(g)}:{}});function ve(f){const l=document.createElement("template");return l.innerHTML=f.trim(),l.content.firstElementChild}const me=`
1
+ import{apiRequest as ue}from"../api.js";import{helpPopovers as Y}from"../lib/help-popover.js";import{onceClosed as pe,openMenuAt as z,viewLifetime as be}from"../lib/tool-kit.js";import{arrangeKnowledge as ke,describeTest as X,linksToRows as he,mayDo as me,rowsToLinks as Z}from"../lib/chats-arrange.js";import{chatsBaseFor as ve,mountAiAssistTabs as ye}from"../lib/ai-assist.js";const fe=/^#\/(launchers|ai-assist)\/knowledge\b/,c=(w,l="GET",g)=>ue(w,{method:l,...g!==void 0?{body:JSON.stringify(g)}:{}});function we(w){const l=document.createElement("template");return l.innerHTML=w.trim(),l.content.firstElementChild}const ge=`
2
2
  <article class="ck-card" data-id="{{id}}" tabindex="0" data-bind-class="off && 'is-off'">
3
3
  <h3 class="ck-q">{{question}}</h3>
4
4
  <p class="ck-a">{{preview}}</p>
5
5
  <div class="ck-meta"><span>{{meta}}</span><span>{{waysText}}</span>
6
6
  <span class="ck-chip ck-chip--warn" data-bind-hidden="!sample">Example</span><span class="ck-chip" data-bind-hidden="!off">Off</span></div>
7
7
  <button type="button" class="ck-kebab" aria-label="Entry actions" title="Actions">\u22EE</button>
8
- </article>`,ye=`
8
+ </article>`,Ee=`
9
9
  <article class="ck-card ck-uq" data-id="{{id}}" tabindex="0">
10
10
  <h3 class="ck-q">{{text}}</h3>
11
11
  <div class="ck-meta"><span>{{asked}}</span><span>{{bestText}}</span></div>
12
12
  <button type="button" class="ck-kebab" aria-label="Question actions" title="Actions">\u22EE</button>
13
- </article>`,k=ue(he);export const chatKnowledgeView={templateUrl:"/admin/js/templates/chat-knowledge.html",async onMount(f){k.reset();const l=f.get(0);let g=!1;k.add(()=>{g=!0});const v=()=>!g&&l.isConnected,X=await c("/auth/permissions").then(t=>t.permissions||[]).catch(()=>[]);if(!v())return;const p=be(X,"chats","manage"),i=M.observable([]),b=M.observable([]),q=M.observable(/[?&]tab=unanswered/.test(location.hash)?"unanswered":"knowledge"),x=M.observable(""),z=M.observable("question"),T=M.observable(!0),S=M.observable(""),$=M.observable(""),L=M.observable(""),O=M.observable([]);k.add(M.effect(()=>{O.value=pe(i.value,{query:x.value,sort:z.value}).map(t=>({...t,waysText:t.ways?`${t.ways} other way${t.ways===1?"":"s"} of asking`:""}))}));const U=M.observable([]);k.add(M.effect(()=>{const t=x.value.trim().toLowerCase();U.value=b.value.filter(e=>!t||e.text.toLowerCase().includes(t)).map(e=>({id:e.id,text:e.text,asked:`asked ${e.count} time${e.count===1?"":"s"}${e.lastAt?`, last ${D(e.lastAt).fromNow()}`:""}`,bestText:e.best?`closest: ${e.best}`:"nothing close"}))}));const Z={tab:q,query:x,sort:z,loading:T,loadError:S,tryText:$,tryOut:L,entries:O,questions:U,canManage:p,knowledgeCount:M.computed(()=>String(i.value.length)),unansweredCount:M.computed(()=>String(b.value.length)),sampleNote:M.computed(()=>{const t=i.value.filter(e=>e.sample).length;return t?`${t} example entr${t===1?"y was":"ies were"} added to show how this works. Change them, or remove them.`:""}),emptyText:M.computed(()=>T.value||S.value?"":q.value==="knowledge"?O.value.length?"":x.value.trim()?"No entries match.":"The bot knows nothing yet. Add an entry, or turn an unanswered question into one.":U.value.length?"":x.value.trim()?"No questions match.":"Nothing unanswered. Questions the bot cannot answer appear here.")};l.querySelector(".ck-items").innerHTML=me,l.querySelector(".ck-qs").innerHTML=ye;const _=W(l,{position:"bottom"});k.add(_);async function A(){try{const[t,e]=await Promise.all([c("/chats/knowledge"),c("/chats/unanswered")]);if(!v())return;i.value=t.items||[],b.value=e.items||[],S.value=""}catch{v()&&(S.value="Could not load the Knowledge.")}finally{v()&&(T.value=!1)}}async function ee(t,e){try{const a=await c(`/chats/knowledge/${encodeURIComponent(t)}`,"PUT",{enabled:e});i.value=i.peek().map(o=>o.id===t?a:o),E.toast(e?"Entry switched on":"Entry switched off - the bot will not use it",{type:"success"})}catch(a){E.toast(a?.message||"Could not change the entry",{type:"error"})}}async function te(t){if(await E.confirm("Delete this entry? The bot stops using it at once."))try{await c(`/chats/knowledge/${encodeURIComponent(t)}`,"DELETE"),i.value=i.peek().filter(e=>e.id!==t),E.toast("Entry deleted",{type:"success"})}catch(e){E.toast(e?.message||"Could not delete the entry",{type:"error"})}}async function K(t,e=!1){try{e?await c(`/chats/unanswered/${encodeURIComponent(t)}`,"DELETE"):await c(`/chats/unanswered/${encodeURIComponent(t)}/done`,"POST",{done:!0}),b.value=b.peek().filter(a=>a.id!==t)}catch(a){E.toast(a?.message||"Could not change the list",{type:"error"})}}let m=null;function y(t,{fromUnanswered:e=null,question:a=""}={}){if(!p)return;if(m){m.so.close();return}const o=!t,d=E.slideover({title:o?"New Knowledge entry":"Edit entry",size:"md",position:"right"});m={so:d};const r=ve(`
13
+ </article>`,b=be(fe);export const chatKnowledgeView={templateUrl:"/admin/js/templates/chat-knowledge.html",async onMount(w){b.reset();const l=w.get(0);let g=!1;b.add(()=>{g=!0});const m=()=>!g&&l.isConnected,_=await c("/auth/permissions").then(t=>t.permissions||[]).catch(()=>[]);if(!m())return;const p=me(_,"chats","manage"),i=M.observable([]),k=M.observable([]),q=M.observable(/[?&]tab=unanswered/.test(location.hash)?"unanswered":"knowledge"),x=M.observable(""),Q=M.observable("question"),T=M.observable(!0),S=M.observable(""),$=M.observable(""),L=M.observable(""),A=M.observable([]);b.add(M.effect(()=>{A.value=ke(i.value,{query:x.value,sort:Q.value}).map(t=>({...t,waysText:t.ways?`${t.ways} other way${t.ways===1?"":"s"} of asking`:""}))}));const O=M.observable([]);b.add(M.effect(()=>{const t=x.value.trim().toLowerCase();O.value=k.value.filter(e=>!t||e.text.toLowerCase().includes(t)).map(e=>({id:e.id,text:e.text,asked:`asked ${e.count} time${e.count===1?"":"s"}${e.lastAt?`, last ${D(e.lastAt).fromNow()}`:""}`,bestText:e.best?`closest: ${e.best}`:"nothing close"}))}));const ee={tab:q,query:x,sort:Q,loading:T,loadError:S,tryText:$,tryOut:L,entries:A,questions:O,canManage:p,knowledgeCount:M.computed(()=>String(i.value.length)),unansweredCount:M.computed(()=>String(k.value.length)),sampleNote:M.computed(()=>{const t=i.value.filter(e=>e.sample).length;return t?`${t} example entr${t===1?"y was":"ies were"} added to show how this works. Change them, or remove them.`:""}),emptyText:M.computed(()=>T.value||S.value?"":q.value==="knowledge"?A.value.length?"":x.value.trim()?"No entries match.":"The bot knows nothing yet. Add an entry, or turn an unanswered question into one.":O.value.length?"":x.value.trim()?"No questions match.":"Nothing unanswered. Questions the bot cannot answer appear here.")},V=ve(location.hash);ye(l,"knowledge");const U=l.querySelector('a[href="#/launchers/chats"]');U&&(V==="#/ai-assist"?U.remove():U.setAttribute("href",`${V}/chats`)),l.querySelector(".ck-items").innerHTML=ge,l.querySelector(".ck-qs").innerHTML=Ee;const te=Y(l,{position:"bottom"});b.add(te);async function K(){try{const[t,e]=await Promise.all([c("/chats/knowledge"),c("/chats/unanswered")]);if(!m())return;i.value=t.items||[],k.value=e.items||[],S.value=""}catch{m()&&(S.value="Could not load the Knowledge.")}finally{m()&&(T.value=!1)}}async function ae(t,e){try{const a=await c(`/chats/knowledge/${encodeURIComponent(t)}`,"PUT",{enabled:e});i.value=i.peek().map(o=>o.id===t?a:o),E.toast(e?"Entry switched on":"Entry switched off - the bot will not use it",{type:"success"})}catch(a){E.toast(a?.message||"Could not change the entry",{type:"error"})}}async function se(t){if(await E.confirm("Delete this entry? The bot stops using it at once."))try{await c(`/chats/knowledge/${encodeURIComponent(t)}`,"DELETE"),i.value=i.peek().filter(e=>e.id!==t),E.toast("Entry deleted",{type:"success"})}catch(e){E.toast(e?.message||"Could not delete the entry",{type:"error"})}}async function N(t,e=!1){try{e?await c(`/chats/unanswered/${encodeURIComponent(t)}`,"DELETE"):await c(`/chats/unanswered/${encodeURIComponent(t)}/done`,"POST",{done:!0}),k.value=k.peek().filter(a=>a.id!==t)}catch(a){E.toast(a?.message||"Could not change the list",{type:"error"})}}let v=null;function y(t,{fromUnanswered:e=null,question:a=""}={}){if(!p)return;if(v){v.so.close();return}const o=!t,d=E.slideover({title:o?"New Knowledge entry":"Edit entry",size:"md",position:"right"});v={so:d};const r=we(`
14
14
  <div class="ck-panel">
15
15
  <div>
16
16
  <label class="form-label" for="ck-ed-q">Question</label>
@@ -53,8 +53,8 @@ import{apiRequest as ce}from"../api.js";import{helpPopovers as W}from"../lib/hel
53
53
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="saving.value">
54
54
  <span data-icon="save" data-icon-size="13"></span> Save</button>
55
55
  </div>
56
- </div>`),u={question:t?.question||a||"",alternatives:t?.alternatives||"",keywords:t?.keywords||"",answer:t?.answer||"",enabled:t?t.enabled:!0,links:JSON.stringify(t?.links||[])},n={question:M.observable(u.question),alternatives:M.observable(u.alternatives),keywords:M.observable(u.keywords),answer:M.observable(u.answer),enabled:M.observable(u.enabled),links:M.observable(ke(t?.links)),saving:M.observable(!1),tested:M.observable("")},J=()=>n.question.peek()!==u.question||n.alternatives.peek()!==u.alternatives||n.keywords.peek()!==u.keywords||n.answer.peek()!==u.answer||n.enabled.peek()!==u.enabled||JSON.stringify(Y(C()))!==u.links;r.querySelector(".ck-links").innerHTML=`<div class="ck-link-row" data-key="{{key}}">
56
+ </div>`),u={question:t?.question||a||"",alternatives:t?.alternatives||"",keywords:t?.keywords||"",answer:t?.answer||"",enabled:t?t.enabled:!0,links:JSON.stringify(t?.links||[])},s={question:M.observable(u.question),alternatives:M.observable(u.alternatives),keywords:M.observable(u.keywords),answer:M.observable(u.answer),enabled:M.observable(u.enabled),links:M.observable(he(t?.links)),saving:M.observable(!1),tested:M.observable("")},F=()=>s.question.peek()!==u.question||s.alternatives.peek()!==u.alternatives||s.keywords.peek()!==u.keywords||s.answer.peek()!==u.answer||s.enabled.peek()!==u.enabled||JSON.stringify(Z(C()))!==u.links;r.querySelector(".ck-links").innerHTML=`<div class="ck-link-row" data-key="{{key}}">
57
57
  <input type="text" class="form-input ck-link-label" placeholder="Label" maxlength="60" value="{{label}}" aria-label="Button label">
58
58
  <input type="text" class="form-input ck-link-url" placeholder="/contact or https://\u2026" maxlength="500" value="{{url}}" aria-label="Button link">
59
- <button type="button" class="btn btn-xs btn-ghost ck-link-x" aria-label="Remove this button" style="opacity:.6"><span data-icon="x" data-icon-size="12"></span></button></div>`;const C=()=>[...r.querySelectorAll(".ck-link-row")].map(s=>({key:s.dataset.key,label:s.querySelector(".ck-link-label").value,url:s.querySelector(".ck-link-url").value})),j=async()=>{if(n.saving.peek())return;n.saving.value=!0;const s={question:n.question.peek(),alternatives:n.alternatives.peek(),keywords:n.keywords.peek(),answer:n.answer.peek(),enabled:n.enabled.peek(),links:Y(C()),...e&&{fromUnanswered:e}};try{const h=o?await c("/chats/knowledge","POST",s):await c(`/chats/knowledge/${encodeURIComponent(t.id)}`,"PUT",s);if(!v())return;i.value=o?[...i.peek(),h]:i.peek().map(w=>w.id===h.id?h:w),e&&(b.value=b.peek().filter(w=>w.id!==e)),E.toast(o?"Entry added - the bot uses it now":"Entry saved",{type:"success"}),B=!0,d.close()}catch(h){E.toast(h?.message||"Could not save the entry",{type:"error"})}finally{n.saving.value=!1}};let B=!1;d.element.appendChild(r);const oe=M.applyBindings(n,r,{methods:{save:j,cancel:()=>d.close(),addLink:()=>{n.links.value=[...C(),{key:`l${Date.now()}`,label:"",url:""}],I.scan(r)},test:async()=>{try{const s=await c("/chats/knowledge/test","POST",{text:n.question.peek()});n.tested.value=`Asked "${n.question.peek()}": ${F(s)}${o||n.answer.peek()!==u.answer?" (Unsaved changes are not in the test yet.)":""}`}catch{n.tested.value="Could not ask the bot."}}}});r.addEventListener("click",s=>{const h=s.target.closest(".ck-link-x");if(!h)return;const w=h.closest(".ck-link-row").dataset.key;n.links.value=C().filter(re=>re.key!==w)}),r.addEventListener("keydown",s=>{(s.ctrlKey||s.metaKey)&&s.key==="Enter"&&(s.preventDefault(),j())});const le=W(r);de(d,()=>{oe.dispose(),le(),window.removeEventListener("beforeunload",G),m?.so===d&&(m=null)});const ie=d.close;d.close=async(...s)=>!B&&!k.leaving&&J()&&!await E.confirm("Discard the changes to this entry?")?!1:ie(...s);const G=s=>{!B&&J()&&(s.preventDefault(),s.returnValue="")};window.addEventListener("beforeunload",G),I.scan(r),d.open(),setTimeout(()=>r.querySelector(n.question.peek()?"#ck-ed-ans":"#ck-ed-q")?.focus(),60)}k.add(()=>m?.so.close());function N(t=$.peek()){const e=String(t||"").trim();e&&($.value=e,c("/chats/knowledge/test","POST",{text:e}).then(a=>{v()&&(L.value=`"${e}": ${F(a)}`)}).catch(()=>{v()&&(L.value="Could not ask the bot.")}),l.querySelector(".ck-try")?.scrollIntoView({block:"nearest"}))}const ae=M.applyBindings(Z,l,{methods:{retry:()=>{T.value=!0,A()},showKnowledge:()=>{q.value="knowledge"},showUnanswered:()=>{q.value="unanswered"},create:()=>y(null),tryIt:()=>(N(),!1),removeExamples:async()=>{if(await E.confirm("Remove the example entries? Entries you have edited are kept."))try{const t=await c("/chats/knowledge/remove-examples","POST",{});E.toast(`${t.removed} example${t.removed===1?"":"s"} removed`,{type:"success"}),A()}catch(t){E.toast(t?.message||"Could not remove them",{type:"error"})}}}});k.add(()=>ae.dispose());const Q=t=>i.peek().find(e=>e.id===t),R=l.querySelector(".ck-list"),P=l.querySelector(".ck-unanswered"),ne=E.contextMenu(R,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=Q(t.dataset.id);return e?[{label:p?"Edit":"View",icon:"edit",action:()=>y(e),disabled:!p},{label:"Try its question",icon:"message-circle",action:()=>N(e.question)},...p?[{label:e.enabled?"Switch off":"Switch on",icon:e.enabled?"eye-off":"eye",action:()=>ee(e.id,!e.enabled)},{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>te(e.id)}]:[]]:[]}});k.add(()=>ne?.destroy?.());const se=E.contextMenu(P,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=b.peek().find(o=>o.id===t.dataset.id);if(!e)return[];const a=e.best?i.peek().find(o=>o.question===e.best):null;return[{label:"Make an entry",icon:"plus",disabled:!p,action:()=>y(null,{question:e.text,fromUnanswered:e.id})},...a?[{label:`Add to "${a.question.slice(0,40)}"`,icon:"corner-down-right",disabled:!p,action:async()=>{try{const o=[a.alternatives,e.text].filter(Boolean).join(`
60
- `),d=await c(`/chats/knowledge/${encodeURIComponent(a.id)}`,"PUT",{alternatives:o});i.value=i.peek().map(r=>r.id===d.id?d:r),await K(e.id),E.toast("Added as another way of asking",{type:"success"})}catch(o){E.toast(o?.message||"Could not add it",{type:"error"})}}}]:[],{label:"Try it",icon:"message-circle",action:()=>N(e.text)},{type:"divider"},{label:"Dismiss",icon:"check",disabled:!p,action:()=>K(e.id)},{label:"Delete",icon:"trash",danger:!0,disabled:!p,action:()=>K(e.id,!0)}]}});k.add(()=>se?.destroy?.()),R.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(e){if(t.target.closest(".ck-kebab")){H(e);return}y(Q(e.dataset.id))}}),P.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(!e)return;if(t.target.closest(".ck-kebab")){H(e);return}const a=b.peek().find(o=>o.id===e.dataset.id);a&&p?y(null,{question:a.text,fromUnanswered:a.id}):a&&H(e)});for(const t of[R,P])t.addEventListener("keydown",e=>{const a=e.target.closest?.(".ck-card");a&&e.key==="Enter"&&e.target===a&&a.click()});const V=t=>{t.ctrlKey||t.metaKey||t.altKey||t.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(t.key==="/"?(t.preventDefault(),l.querySelector(".ck-search input")?.focus()):(t.key==="n"||t.key==="N")&&p&&(t.preventDefault(),y(null)))};document.addEventListener("keydown",V),k.add(()=>document.removeEventListener("keydown",V)),I.scan(l),await A()}};
59
+ <button type="button" class="btn btn-xs btn-ghost ck-link-x" aria-label="Remove this button" style="opacity:.6"><span data-icon="x" data-icon-size="12"></span></button></div>`;const C=()=>[...r.querySelectorAll(".ck-link-row")].map(n=>({key:n.dataset.key,label:n.querySelector(".ck-link-label").value,url:n.querySelector(".ck-link-url").value})),G=async()=>{if(s.saving.peek())return;s.saving.value=!0;const n={question:s.question.peek(),alternatives:s.alternatives.peek(),keywords:s.keywords.peek(),answer:s.answer.peek(),enabled:s.enabled.peek(),links:Z(C()),...e&&{fromUnanswered:e}};try{const h=o?await c("/chats/knowledge","POST",n):await c(`/chats/knowledge/${encodeURIComponent(t.id)}`,"PUT",n);if(!m())return;i.value=o?[...i.peek(),h]:i.peek().map(f=>f.id===h.id?h:f),e&&(k.value=k.peek().filter(f=>f.id!==e)),E.toast(o?"Entry added - the bot uses it now":"Entry saved",{type:"success"}),H=!0,d.close()}catch(h){E.toast(h?.message||"Could not save the entry",{type:"error"})}finally{s.saving.value=!1}};let H=!1;d.element.appendChild(r);const ie=M.applyBindings(s,r,{methods:{save:G,cancel:()=>d.close(),addLink:()=>{s.links.value=[...C(),{key:`l${Date.now()}`,label:"",url:""}],I.scan(r)},test:async()=>{try{const n=await c("/chats/knowledge/test","POST",{text:s.question.peek()});s.tested.value=`Asked "${s.question.peek()}": ${X(n)}${o||s.answer.peek()!==u.answer?" (Unsaved changes are not in the test yet.)":""}`}catch{s.tested.value="Could not ask the bot."}}}});r.addEventListener("click",n=>{const h=n.target.closest(".ck-link-x");if(!h)return;const f=h.closest(".ck-link-row").dataset.key;s.links.value=C().filter(de=>de.key!==f)}),r.addEventListener("keydown",n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),G())});const re=Y(r);pe(d,()=>{ie.dispose(),re(),window.removeEventListener("beforeunload",W),v?.so===d&&(v=null)});const ce=d.close;d.close=async(...n)=>!H&&!b.leaving&&F()&&!await E.confirm("Discard the changes to this entry?")?!1:ce(...n);const W=n=>{!H&&F()&&(n.preventDefault(),n.returnValue="")};window.addEventListener("beforeunload",W),I.scan(r),d.open(),setTimeout(()=>r.querySelector(s.question.peek()?"#ck-ed-ans":"#ck-ed-q")?.focus(),60)}b.add(()=>v?.so.close());function R(t=$.peek()){const e=String(t||"").trim();e&&($.value=e,c("/chats/knowledge/test","POST",{text:e}).then(a=>{m()&&(L.value=`"${e}": ${X(a)}`)}).catch(()=>{m()&&(L.value="Could not ask the bot.")}),l.querySelector(".ck-try")?.scrollIntoView({block:"nearest"}))}const ne=M.applyBindings(ee,l,{methods:{retry:()=>{T.value=!0,K()},showKnowledge:()=>{q.value="knowledge"},showUnanswered:()=>{q.value="unanswered"},create:()=>y(null),tryIt:()=>(R(),!1),removeExamples:async()=>{if(await E.confirm("Remove the example entries? Entries you have edited are kept."))try{const t=await c("/chats/knowledge/remove-examples","POST",{});E.toast(`${t.removed} example${t.removed===1?"":"s"} removed`,{type:"success"}),K()}catch(t){E.toast(t?.message||"Could not remove them",{type:"error"})}}}});b.add(()=>ne.dispose());const J=t=>i.peek().find(e=>e.id===t),P=l.querySelector(".ck-list"),B=l.querySelector(".ck-unanswered"),oe=E.contextMenu(P,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=J(t.dataset.id);return e?[{label:p?"Edit":"View",icon:"edit",action:()=>y(e),disabled:!p},{label:"Try its question",icon:"message-circle",action:()=>R(e.question)},...p?[{label:e.enabled?"Switch off":"Switch on",icon:e.enabled?"eye-off":"eye",action:()=>ae(e.id,!e.enabled)},{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>se(e.id)}]:[]]:[]}});b.add(()=>oe?.destroy?.());const le=E.contextMenu(B,{cursor:"glyph",match:".ck-card",inherit:!1,density:"compact",items:t=>{const e=k.peek().find(o=>o.id===t.dataset.id);if(!e)return[];const a=e.best?i.peek().find(o=>o.question===e.best):null;return[{label:"Make an entry",icon:"plus",disabled:!p,action:()=>y(null,{question:e.text,fromUnanswered:e.id})},...a?[{label:`Add to "${a.question.slice(0,40)}"`,icon:"corner-down-right",disabled:!p,action:async()=>{try{const o=[a.alternatives,e.text].filter(Boolean).join(`
60
+ `),d=await c(`/chats/knowledge/${encodeURIComponent(a.id)}`,"PUT",{alternatives:o});i.value=i.peek().map(r=>r.id===d.id?d:r),await N(e.id),E.toast("Added as another way of asking",{type:"success"})}catch(o){E.toast(o?.message||"Could not add it",{type:"error"})}}}]:[],{label:"Try it",icon:"message-circle",action:()=>R(e.text)},{type:"divider"},{label:"Dismiss",icon:"check",disabled:!p,action:()=>N(e.id)},{label:"Delete",icon:"trash",danger:!0,disabled:!p,action:()=>N(e.id,!0)}]}});b.add(()=>le?.destroy?.()),P.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(e){if(t.target.closest(".ck-kebab")){z(e);return}y(J(e.dataset.id))}}),B.addEventListener("click",t=>{const e=t.target.closest(".ck-card");if(!e)return;if(t.target.closest(".ck-kebab")){z(e);return}const a=k.peek().find(o=>o.id===e.dataset.id);a&&p?y(null,{question:a.text,fromUnanswered:a.id}):a&&z(e)});for(const t of[P,B])t.addEventListener("keydown",e=>{const a=e.target.closest?.(".ck-card");a&&e.key==="Enter"&&e.target===a&&a.click()});const j=t=>{t.ctrlKey||t.metaKey||t.altKey||t.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(t.key==="/"?(t.preventDefault(),l.querySelector(".ck-search input")?.focus()):(t.key==="n"||t.key==="N")&&p&&(t.preventDefault(),y(null)))};document.addEventListener("keydown",j),b.add(()=>document.removeEventListener("keydown",j)),I.scan(l),await K()}};
@@ -1,4 +1,4 @@
1
- import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib/plugin-chrome.js";import{helpPopovers as ce}from"../lib/help-popover.js";import{onceClosed as Ae,openMenuAt as ie,sidebarCount as V,viewLifetime as He}from"../lib/tool-kit.js";import{arrangeChats as Le,arrangeSaved as Oe,mayDo as de,OUTCOME as ue,STATUS as Ie,threadRow as he}from"../lib/chats-arrange.js";const Pe=/^#\/launchers\/chats\b/,pe=5e3,me=3e3,Ue=3e4,ve="chats.drafts",i=(h,l="GET",$)=>De(h,{method:l,...$!==void 0?{body:JSON.stringify($)}:{}});function qe(h){const l=document.createElement("template");return l.innerHTML=h.trim(),l.content.firstElementChild}const Be=()=>{try{const h=S.get(ve);return h&&typeof h=="object"?h:{}}catch{return{}}},fe=h=>{try{S.set(ve,h)}catch{}},Ke=`
1
+ import{apiRequest as De}from"../api.js";import{addBannerAction as Ae}from"../lib/plugin-chrome.js";import{helpPopovers as ce}from"../lib/help-popover.js";import{onceClosed as Re,openMenuAt as de,sidebarCount as _,viewLifetime as Le}from"../lib/tool-kit.js";import{arrangeChats as He,arrangeSaved as Oe,mayDo as ue,OUTCOME as he,STATUS as qe,threadRow as pe}from"../lib/chats-arrange.js";import{chatsBaseFor as Be,mountAiAssistTabs as Pe}from"../lib/ai-assist.js";import{onPresence as Ue,setAvailable as Ie}from"../lib/chat-presence.js";const Ke=/^#\/(launchers|ai-assist)\/chats\b/,me=5e3,ve=3e3,fe="chats.drafts",u=(h,l="GET",A)=>De(h,{method:l,...A!==void 0?{body:JSON.stringify(A)}:{}});function Fe(h){const l=document.createElement("template");return l.innerHTML=h.trim(),l.content.firstElementChild}const je=()=>{try{const h=S.get(fe);return h&&typeof h=="object"?h:{}}catch{return{}}},ye=h=>{try{S.set(fe,h)}catch{}},Ve=`
2
2
  <div class="chat-row" data-id="{{id}}" tabindex="0" role="button" data-bind-class="$root.openId.value === id && 'is-open'">
3
3
  <span class="chat-row-who">{{who}}</span>
4
4
  <span data-bind-class="chipClass">{{chip}}</span>
@@ -6,12 +6,12 @@ import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib
6
6
  <span class="chat-row-meta">{{meta}}</span>
7
7
  <span class="chat-row-unread" aria-label="unread">{{unreadText}}</span>
8
8
  <button type="button" class="chat-row-kebab" aria-label="Chat actions" title="Actions">\u22EE</button>
9
- </div>`,je=`
9
+ </div>`,_e=`
10
10
  <div data-bind-class="cls">
11
11
  <span class="chat-msg-who">{{who}} \xB7 {{time}}</span>
12
12
  <div class="chat-msg-text">{{text}}</div>
13
13
  <span class="chat-msg-note">{{note}}</span>
14
- </div>`,r=He(Pe);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(h){r.reset();const l=h.get(0);let $=!1;r.add(()=>{$=!0});const n=()=>!$&&l.isConnected,Z=await i("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!n())return;const b=de(Z,"chats","reply"),z=de(Z,"chats","manage"),m=M.observable([]),O=M.observable(""),d=M.observable("active"),y=M.observable(!0),g=M.observable(""),o=M.observable(location.hash.match(/^#\/launchers\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),u=M.observable(null),k=M.observable([]),v=M.observable(""),P=M.observable(!1),R=M.observable(!1),Q=M.observable([]),X=M.observable({installed:!0,count:1}),f=M.observable([]),p=M.observable(null),U=M.observable(""),q=M.observable("to look at");let A=0,ee=!1;const G=M.observable([]);r.add(M.effect(()=>{G.value=d.value==="saved"?Oe(f.value,{query:O.value}):Le(m.value,{query:O.value})}));const ye={query:O,view:d,loading:y,loadError:g,rows:G,openId:o,thread:k,reply:v,available:R,canReply:b,savedOpen:p,savedNote:U,savedOutcome:q,savedDirty:M.computed(()=>!!p.value&&(U.value!==(p.value.note||"")||q.value!==p.value.outcome)),isEmpty:M.computed(()=>!y.value&&!g.value&&G.value.length===0),emptyText:M.computed(()=>O.value.trim()?"No chats match.":d.value==="active"?"No chats right now. They appear here as visitors start them.":d.value==="saved"?"No saved chats. Right-click a chat and choose Save for a closer look to keep a copy here.":"No ended chats."),countText:M.computed(()=>{if(y.value)return"";if(d.value==="saved"){const a=f.value.length,s=f.value.filter(c=>c.outcome!=="done").length;return`${a} saved${s?` \xB7 ${s} to finish`:""}`}const e=m.value.filter(a=>a.status==="waiting").length,t=m.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=Q.value;return R.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=X.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=p.value;if(e){const c=ue[e.outcome]||ue["to look at"],L=e.savedAt?`saved ${D(e.savedAt).fromNow()}${e.savedBy?` by ${e.savedBy}`:""}`:"";return{who:e.name||"Visitor",chip:c.label,chipClass:`chat-chip chat-chip--${c.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",L].filter(Boolean).join(" \xB7 ")}}const t=u.value;if(!t)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const a=Ie[t.status]||{label:t.status,tone:"muted"},s=t.startedAt?`started ${D(t.startedAt).fromNow()}`:"";return{who:t.name||"Visitor",chip:a.label,chipClass:`chat-chip chat-chip--${a.tone}`,email:t.email,mailto:t.email?`mailto:${t.email}`:"",meta:[t.page?`on ${t.page}`:"",s].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>b&&!!u.value&&u.value.status!=="closed"),canSend:M.computed(()=>b&&!P.value&&v.value.trim().length>0&&!!u.value&&u.value.status!=="closed"),replyHint:M.computed(()=>u.value?.status==="closed"?"This chat has ended.":u.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let T=Be();r.add(M.effect(()=>{const e=o.peek(),t=v.value;e&&(t?T[e]=t:delete T[e],fe(T))}));const te=e=>{v.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",te),r.add(()=>window.removeEventListener("beforeunload",te)),l.querySelector(".chats-list").innerHTML=Ke,l.querySelector(".chats-msgs").innerHTML=je;const W=l.querySelector(".chats-list"),x=l.querySelector(".chats-messages"),be=ce(l,{position:"bottom"});r.add(be);let B=0,H=0,ae=0;r.add(()=>{clearTimeout(B),clearTimeout(H),clearInterval(ae)});async function w(){if(clearTimeout(B),d.peek()==="saved")return ge();try{const e=await i(`/chats?view=${d.peek()}`);if(!n())return;m.value=e.items||[],Q.value=e.available||[],X.value=e.launchers||{installed:!0,count:1},g.value=""}catch{if(!n())return;y.peek()&&(g.value="Could not load the chats.")}finally{n()&&(y.value=!1,B=setTimeout(se(w),pe))}}async function ge(){try{const e=await i("/chats/saved");if(!n()||d.peek()!=="saved")return;f.value=e.items||[],g.value=""}catch{n()&&(g.value="Could not load the saved chats.")}finally{n()&&(y.value=!1)}}async function ne(e){if(!(!e||p.peek()?.id===e)){clearTimeout(H),u.value=null,v.value="",o.value=e,k.value=[];try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e)}`);if(!n()||o.peek()!==e)return;p.value=t,U.value=t.note||"",q.value=t.outcome,k.value=(t.messages||[]).map(he),requestAnimationFrame(()=>{x.scrollTop=0})}catch(t){if(!n())return;E.toast(t?.message||"Could not open the saved chat",{type:"error"}),C()}}}async function ke(){const e=p.peek();if(e)try{const{item:t}=await i(`/chats/saved/${encodeURIComponent(e.id)}`,"PUT",{note:U.peek(),outcome:q.peek()});if(!n())return;p.value={...e,...t},f.value=f.peek().map(a=>a.id===t.id?t:a),E.toast("Saved",{type:"success"})}catch(t){E.toast(t?.message||"Could not save",{type:"error"})}}async function we(e){const t=await E.prompt("Save a copy of this chat for a closer look. Why are you saving it? (optional)");if(!(t==null||!n()))try{if(await i(`/chats/${encodeURIComponent(e)}/save`,"POST",{note:String(t)}),!n())return;E.toast("Saved - find it under Saved",{type:"success"})}catch(a){E.toast(a?.message||"Could not save the chat",{type:"error"})}}async function Ee(e){if(!(!await E.confirm("Delete this saved copy? The chat itself is not affected. This cannot be undone.")||!n()))try{await i(`/chats/saved/${encodeURIComponent(e)}`,"DELETE"),o.peek()===e&&C(),f.value=f.peek().filter(a=>a.id!==e),E.toast("Saved copy deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete it",{type:"error"})}}const se=e=>()=>{if(document.hidden){B=setTimeout(se(e),pe);return}e()};async function K(e=!1){clearTimeout(H);const t=o.peek();if(t){e&&(A=0,k.value=[]);try{const a=await i(`/chats/${encodeURIComponent(t)}?after=${A}`);if(!n()||o.peek()!==t)return;u.value=a.chat;const s=(a.messages||[]).filter(c=>c.n>A);if(s.length){const c=x.scrollHeight-x.scrollTop-x.clientHeight<80;A=Math.max(A,...s.map(L=>L.n)),k.value=[...k.peek(),...s.map(he)],(e||c)&&requestAnimationFrame(()=>{x.scrollTop=x.scrollHeight}),V("#/launchers/chats")}m.value=m.peek().map(c=>c.id===t?{...c,...a.chat}:c)}catch(a){if(!n()||o.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),C();return}}n()&&o.peek()===t&&(H=setTimeout(()=>K(),document.hidden?me*4:me))}}function j(e){if(d.peek()==="saved"){ne(e);return}!e||o.peek()===e||(o.value=e,u.value=m.peek().find(t=>t.id===e)||null,v.value=T[e]||"",history.replaceState(null,"",`#/launchers/chats/${e}`),K(!0))}function C(){clearTimeout(H),o.value="",u.value=null,p.value=null,k.value=[],v.value="",history.replaceState(null,"","#/launchers/chats")}async function oe(){const e=o.peek(),t=v.peek().trim();if(!(!e||!t||P.peek())){P.value=!0;try{if(await i(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!n())return;v.value="",await K(),w(),V("#/launchers/chats")}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{n()&&(P.value=!1)}}}async function Me(e){try{await i(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),o.peek()===e&&K(),w(),V("#/launchers/chats")}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function Ce(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!n()))try{await i(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete T[e],fe(T),o.peek()===e&&C(),m.value=m.peek().filter(a=>a.id!==e),V("#/launchers/chats"),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}async function F(e=!1){if(b)try{const t=await i("/chats/presence","POST",e?{leaving:!0}:{available:R.peek()});!e&&n()&&typeof t?.online=="number"&&w()}catch{}}b&&(R.value=!0,F(),ae=setInterval(()=>F(),Ue),r.add(M.effect(()=>{if(R.value,!ee){ee=!0;return}F()})),r.add(()=>F(!0)));function J(e){if(d.peek()===e)return;const t=d.peek()==="saved"||e==="saved";d.value=e,t&&o.peek()&&C(),y.value=!0,w()}const Te=M.applyBindings(ye,l,{methods:{retry:()=>{y.value=!0,g.value="",w()},showActive:()=>{J("active")},showClosed:()=>{J("closed")},showSaved:()=>{J("saved")},saveSavedNote:()=>ke(),sendReply:()=>(oe(),!1),back:()=>C()}});r.add(()=>Te.dispose()),l.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),oe())});const le=e=>{if(d.peek()==="saved"){const a=f.peek().find(s=>s.id===e)||(p.peek()?.id===e?p.peek():null);return a?[{label:"Open",icon:"message-circle",action:()=>ne(e)},...a.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${a.email}`}}]:[],...a.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(a.page,"_blank","noopener")}]:[],...z?[{type:"divider"},{label:"Delete saved copy",icon:"trash",danger:!0,action:()=>Ee(e)}]:[]]:[]}const t=m.peek().find(a=>a.id===e)||(u.peek()?.id===e?u.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>j(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...b?[{type:"divider"},{label:"Save for a closer look\u2026",icon:"bookmark",action:()=>we(e)}]:[],...b&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>Me(e)}]:[],...z?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>Ce(e)}]:[]]:[]},Se=E.contextMenu(W,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>le(e.dataset.id)});r.add(()=>Se?.destroy?.());const Y=l.querySelector(".chats-head-kebab"),xe=E.contextMenu(Y,{cursor:"glyph",inherit:!1,density:"compact",items:()=>le(o.peek())});r.add(()=>xe?.destroy?.()),Y.addEventListener("click",()=>ie(Y)),W.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){ie(t);return}j(t.dataset.id)}}),W.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),j(t.dataset.id))});let N=null;async function Ne(){if(N)return;let e;try{e=(await i("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!n()||N)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});N=t;const a=qe(`
14
+ </div>`,r=Le(Ke);export const chatsView={templateUrl:"/admin/js/templates/chats.html",async onMount(h){r.reset();const l=h.get(0);let A=!1;r.add(()=>{A=!0});const s=()=>!A&&l.isConnected,z=Be(location.hash),b=`${z}/chats`,X=await u("/auth/permissions").then(e=>e.permissions||[]).catch(()=>[]);if(!s())return;const T=ue(X,"chats","reply"),G=ue(X,"chats","manage"),m=M.observable([]),q=M.observable(""),c=M.observable("active"),y=M.observable(!0),g=M.observable(""),o=M.observable(location.hash.match(/^#\/(?:launchers|ai-assist)\/chats\/([A-Za-z0-9_-]+)/)?.[1]||""),d=M.observable(null),k=M.observable([]),v=M.observable(""),B=M.observable(!1),R=M.observable(!1),ee=M.observable([]),te=M.observable({installed:!0,count:1}),f=M.observable([]),p=M.observable(null),P=M.observable(""),U=M.observable("to look at");let L=0;const W=M.observable([]);r.add(M.effect(()=>{W.value=c.value==="saved"?Oe(f.value,{query:q.value}):He(m.value,{query:q.value})}));const be={query:q,view:c,loading:y,loadError:g,rows:W,openId:o,thread:k,reply:v,available:R,canReply:T,savedOpen:p,savedNote:P,savedOutcome:U,savedDirty:M.computed(()=>!!p.value&&(P.value!==(p.value.note||"")||U.value!==p.value.outcome)),isEmpty:M.computed(()=>!y.value&&!g.value&&W.value.length===0),emptyText:M.computed(()=>q.value.trim()?"No chats match.":c.value==="active"?"No chats right now. They appear here as visitors start them.":c.value==="saved"?"No saved chats. Right-click a chat and choose Save for a closer look to keep a copy here.":"No ended chats."),countText:M.computed(()=>{if(y.value)return"";if(c.value==="saved"){const a=f.value.length,n=f.value.filter(i=>i.outcome!=="done").length;return`${a} saved${n?` \xB7 ${n} to finish`:""}`}const e=m.value.filter(a=>a.status==="waiting").length,t=m.value.length;return`${t} chat${t===1?"":"s"}${e?` \xB7 ${e} waiting`:""}`}),availText:M.computed(()=>{const e=ee.value;return R.value?e.length>1?`Available (${e.length} of you)`:"Available for chats":e.length?`Not available \xB7 ${e.length} other${e.length===1?"":"s"} available`:"Not available"}),noLauncherNote:M.computed(()=>{const e=te.value;return e.installed&&!e.count?"No chat launcher is switched on yet, so visitors cannot start a chat. Add a launcher with the Chat action in Launchers.":""}),head:M.computed(()=>{const e=p.value;if(e){const i=he[e.outcome]||he["to look at"],O=e.savedAt?`saved ${D(e.savedAt).fromNow()}${e.savedBy?` by ${e.savedBy}`:""}`:"";return{who:e.name||"Visitor",chip:i.label,chipClass:`chat-chip chat-chip--${i.tone}`,email:e.email,mailto:e.email?`mailto:${e.email}`:"",meta:[e.page?`on ${e.page}`:"",O].filter(Boolean).join(" \xB7 ")}}const t=d.value;if(!t)return{who:"",chip:"",chipClass:"chat-chip",email:"",mailto:"",meta:""};const a=qe[t.status]||{label:t.status,tone:"muted"},n=t.startedAt?`started ${D(t.startedAt).fromNow()}`:"";return{who:t.name||"Visitor",chip:a.label,chipClass:`chat-chip chat-chip--${a.tone}`,email:t.email,mailto:t.email?`mailto:${t.email}`:"",meta:[t.page?`on ${t.page}`:"",n].filter(Boolean).join(" \xB7 ")}}),canWrite:M.computed(()=>T&&!!d.value&&d.value.status!=="closed"),canSend:M.computed(()=>T&&!B.value&&v.value.trim().length>0&&!!d.value&&d.value.status!=="closed"),replyHint:M.computed(()=>d.value?.status==="closed"?"This chat has ended.":d.value?.status==="message"?"Reply here (they see it if they come back) - or email them.":"Type a reply\u2026 (Ctrl+Enter sends)")};let x=je();r.add(M.effect(()=>{const e=o.peek(),t=v.value;e&&(t?x[e]=t:delete x[e],ye(x))}));const ae=e=>{v.peek().trim()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",ae),r.add(()=>window.removeEventListener("beforeunload",ae)),l.querySelector(".chats-list").innerHTML=Ve,l.querySelector(".chats-msgs").innerHTML=_e;const J=l.querySelector(".chats-list"),$=l.querySelector(".chats-messages"),ge=ce(l,{position:"bottom"});r.add(ge);let K=0,H=0;r.add(()=>{clearTimeout(K),clearTimeout(H)});async function w(){if(clearTimeout(K),c.peek()==="saved")return ke();try{const e=await u(`/chats?view=${c.peek()}`);if(!s())return;m.value=e.items||[],ee.value=e.available||[],te.value=e.launchers||{installed:!0,count:1},g.value=""}catch{if(!s())return;y.peek()&&(g.value="Could not load the chats.")}finally{s()&&(y.value=!1,K=setTimeout(ne(w),me))}}async function ke(){try{const e=await u("/chats/saved");if(!s()||c.peek()!=="saved")return;f.value=e.items||[],g.value=""}catch{s()&&(g.value="Could not load the saved chats.")}finally{s()&&(y.value=!1)}}async function se(e){if(!(!e||p.peek()?.id===e)){clearTimeout(H),d.value=null,v.value="",o.value=e,k.value=[];try{const{item:t}=await u(`/chats/saved/${encodeURIComponent(e)}`);if(!s()||o.peek()!==e)return;p.value=t,P.value=t.note||"",U.value=t.outcome,k.value=(t.messages||[]).map(pe),requestAnimationFrame(()=>{$.scrollTop=0})}catch(t){if(!s())return;E.toast(t?.message||"Could not open the saved chat",{type:"error"}),C()}}}async function we(){const e=p.peek();if(e)try{const{item:t}=await u(`/chats/saved/${encodeURIComponent(e.id)}`,"PUT",{note:P.peek(),outcome:U.peek()});if(!s())return;p.value={...e,...t},f.value=f.peek().map(a=>a.id===t.id?t:a),E.toast("Saved",{type:"success"})}catch(t){E.toast(t?.message||"Could not save",{type:"error"})}}async function Ee(e){const t=await E.prompt("Save a copy of this chat for a closer look. Why are you saving it? (optional)");if(!(t==null||!s()))try{if(await u(`/chats/${encodeURIComponent(e)}/save`,"POST",{note:String(t)}),!s())return;E.toast("Saved - find it under Saved",{type:"success"})}catch(a){E.toast(a?.message||"Could not save the chat",{type:"error"})}}async function Me(e){if(!(!await E.confirm("Delete this saved copy? The chat itself is not affected. This cannot be undone.")||!s()))try{await u(`/chats/saved/${encodeURIComponent(e)}`,"DELETE"),o.peek()===e&&C(),f.value=f.peek().filter(a=>a.id!==e),E.toast("Saved copy deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete it",{type:"error"})}}const ne=e=>()=>{if(document.hidden){K=setTimeout(ne(e),me);return}e()};async function F(e=!1){clearTimeout(H);const t=o.peek();if(t){e&&(L=0,k.value=[]);try{const a=await u(`/chats/${encodeURIComponent(t)}?after=${L}`);if(!s()||o.peek()!==t)return;d.value=a.chat;const n=(a.messages||[]).filter(i=>i.n>L);if(n.length){const i=$.scrollHeight-$.scrollTop-$.clientHeight<80;L=Math.max(L,...n.map(O=>O.n)),k.value=[...k.peek(),...n.map(pe)],(e||i)&&requestAnimationFrame(()=>{$.scrollTop=$.scrollHeight}),_(b)}m.value=m.peek().map(i=>i.id===t?{...i,...a.chat}:i)}catch(a){if(!s()||o.peek()!==t)return;if(/not found/i.test(a?.message||"")){E.toast("That chat no longer exists",{type:"warning"}),C();return}}s()&&o.peek()===t&&(H=setTimeout(()=>F(),document.hidden?ve*4:ve))}}function j(e){if(c.peek()==="saved"){se(e);return}!e||o.peek()===e||(o.value=e,d.value=m.peek().find(t=>t.id===e)||null,v.value=x[e]||"",history.replaceState(null,"",`${b}/${e}`),F(!0))}function C(){clearTimeout(H),o.value="",d.value=null,p.value=null,k.value=[],v.value="",history.replaceState(null,"",b)}async function oe(){const e=o.peek(),t=v.peek().trim();if(!(!e||!t||B.peek())){B.value=!0;try{if(await u(`/chats/${encodeURIComponent(e)}/reply`,"POST",{text:t}),!s())return;v.value="",await F(),w(),_(b)}catch(a){E.toast(a?.message||"The reply was not sent",{type:"error"})}finally{s()&&(B.value=!1)}}}async function Ce(e){try{await u(`/chats/${encodeURIComponent(e)}/close`,"POST",{}),E.toast("Chat ended",{type:"success"}),o.peek()===e&&F(),w(),_(b)}catch(t){E.toast(t?.message||"Could not end the chat",{type:"error"})}}async function Te(e){if(!(!await E.confirm("Delete this chat and all its messages? This cannot be undone.")||!s()))try{await u(`/chats/${encodeURIComponent(e)}`,"DELETE"),delete x[e],ye(x),o.peek()===e&&C(),m.value=m.peek().filter(a=>a.id!==e),_(b),E.toast("Chat deleted",{type:"success"})}catch(a){E.toast(a?.message||"Could not delete the chat",{type:"error"})}}if(T){let e=!1;r.add(Ue(({available:t})=>{R.peek()!==t&&(e=!0,R.value=t,e=!1,s()&&setTimeout(()=>{s()&&w()},400))})),r.add(M.effect(()=>{const t=R.value;e||Ie(t)}))}function Y(e){if(c.peek()===e)return;const t=c.peek()==="saved"||e==="saved";c.value=e,t&&o.peek()&&C(),y.value=!0,w()}const Se=M.applyBindings(be,l,{methods:{retry:()=>{y.value=!0,g.value="",w()},showActive:()=>{Y("active")},showClosed:()=>{Y("closed")},showSaved:()=>{Y("saved")},saveSavedNote:()=>we(),sendReply:()=>(oe(),!1),back:()=>C()}});r.add(()=>Se.dispose()),l.querySelector(".chats-reply textarea")?.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.key==="Enter"&&(e.preventDefault(),oe())});const le=e=>{if(c.peek()==="saved"){const a=f.peek().find(n=>n.id===e)||(p.peek()?.id===e?p.peek():null);return a?[{label:"Open",icon:"message-circle",action:()=>se(e)},...a.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${a.email}`}}]:[],...a.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(a.page,"_blank","noopener")}]:[],...G?[{type:"divider"},{label:"Delete saved copy",icon:"trash",danger:!0,action:()=>Me(e)}]:[]]:[]}const t=m.peek().find(a=>a.id===e)||(d.peek()?.id===e?d.peek():null);return t?[{label:"Open",icon:"message-circle",action:()=>j(e)},...t.email?[{label:"Email the visitor",icon:"mail",action:()=>{location.href=`mailto:${t.email}`}},{label:"Copy email address",icon:"copy",action:()=>navigator.clipboard?.writeText(t.email).then(()=>E.toast("Copied",{type:"success"})).catch(()=>{})}]:[],...t.page?[{label:"Open the page they were on",icon:"external-link",action:()=>window.open(t.page,"_blank","noopener")}]:[],...T?[{type:"divider"},{label:"Save for a closer look\u2026",icon:"bookmark",action:()=>Ee(e)}]:[],...T&&t.status!=="closed"?[{type:"divider"},{label:"End chat",icon:"x-circle",action:()=>Ce(e)}]:[],...G?[{type:"divider"},{label:"Delete",icon:"trash",danger:!0,action:()=>Te(e)}]:[]]:[]},xe=E.contextMenu(J,{cursor:"glyph",match:".chat-row",inherit:!1,density:"compact",items:e=>le(e.dataset.id)});r.add(()=>xe?.destroy?.());const Z=l.querySelector(".chats-head-kebab"),$e=E.contextMenu(Z,{cursor:"glyph",inherit:!1,density:"compact",items:()=>le(o.peek())});r.add(()=>$e?.destroy?.()),Z.addEventListener("click",()=>de(Z)),J.addEventListener("click",e=>{const t=e.target.closest(".chat-row");if(t){if(e.target.closest(".chat-row-kebab")){de(t);return}j(t.dataset.id)}}),J.addEventListener("keydown",e=>{const t=e.target.closest?.(".chat-row");t&&(e.key==="Enter"||e.key===" ")&&e.target===t&&(e.preventDefault(),j(t.dataset.id))});let N=null;async function re(){if(N)return;let e;try{e=(await u("/chats/settings")).settings}catch{E.toast("Could not read the chat settings",{type:"error"});return}if(!s()||N)return;const t=E.slideover({title:"Chat settings",size:"sm",position:"right"});N=t;const a=Fe(`
15
15
  <div class="chats-settings" style="display:flex;flex-direction:column;gap:1rem;padding:.25rem">
16
16
  <div>
17
17
  <label class="form-label" for="chat-set-conf">How sure the bot must be
@@ -50,4 +50,4 @@ import{apiRequest as De}from"../api.js";import{addBannerAction as Re}from"../lib
50
50
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
51
51
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-hidden="!canManage" data-bind-disabled="!dirty.value">Save</button>
52
52
  </div>
53
- </div>`),s={canManage:z,confidence:M.observable(e.confidence),staffName:M.observable(e.staffName),retentionDays:M.observable(String(e.retentionDays)),maxNewChatsPerHour:M.observable(String(e.maxNewChatsPerHour))};s.dirty=M.computed(()=>s.confidence.value!==e.confidence||s.staffName.value!==e.staffName||Number(s.retentionDays.value)!==e.retentionDays||Number(s.maxNewChatsPerHour.value)!==e.maxNewChatsPerHour),t.element.appendChild(a);const c=ce(a),L=M.applyBindings(s,a,{methods:{cancel:()=>t.close(),save:async()=>{try{e=(await i("/chats/settings","PUT",{confidence:s.confidence.peek(),staffName:s.staffName.peek(),retentionDays:Number(s.retentionDays.peek()),maxNewChatsPerHour:Number(s.maxNewChatsPerHour.peek())})).settings,E.toast("Chat settings saved",{type:"success"}),t.close()}catch(_){E.toast(_?.message||"Could not save",{type:"error"})}}}});Ae(t,()=>{L.dispose(),c(),N===t&&(N=null)});const $e=t.close;t.close=async(..._)=>s.dirty.peek()&&!r.leaving&&!await E.confirm("Discard your changes to the chat settings?")?!1:$e(..._),t.open()}r.add(()=>N?.close()),Re(h,{id:"chats-settings",icon:"settings",title:"Chat settings",onClick:Ne});const re=e=>{e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(e.key==="/"&&(e.preventDefault(),l.querySelector(".chats-search input")?.focus()),e.key==="Escape"&&o.peek()&&C())};if(document.addEventListener("keydown",re),r.add(()=>document.removeEventListener("keydown",re)),I.scan(l),await w(),n()&&o.peek()){const e=o.peek();o.value="",j(e)}}};
53
+ </div>`),n={canManage:G,confidence:M.observable(e.confidence),staffName:M.observable(e.staffName),retentionDays:M.observable(String(e.retentionDays)),maxNewChatsPerHour:M.observable(String(e.maxNewChatsPerHour))};n.dirty=M.computed(()=>n.confidence.value!==e.confidence||n.staffName.value!==e.staffName||Number(n.retentionDays.value)!==e.retentionDays||Number(n.maxNewChatsPerHour.value)!==e.maxNewChatsPerHour),t.element.appendChild(a);const i=ce(a),O=M.applyBindings(n,a,{methods:{cancel:()=>t.close(),save:async()=>{try{e=(await u("/chats/settings","PUT",{confidence:n.confidence.peek(),staffName:n.staffName.peek(),retentionDays:Number(n.retentionDays.peek()),maxNewChatsPerHour:Number(n.maxNewChatsPerHour.peek())})).settings,E.toast("Chat settings saved",{type:"success"}),t.close()}catch(V){E.toast(V?.message||"Could not save",{type:"error"})}}}});Re(t,()=>{O.dispose(),i(),N===t&&(N=null)});const Ne=t.close;t.close=async(...V)=>n.dirty.peek()&&!r.leaving&&!await E.confirm("Discard your changes to the chat settings?")?!1:Ne(...V),t.open()}r.add(()=>N?.close()),Ae(h,{id:"chats-settings",icon:"settings",title:"Chat settings",onClick:re});const ie=e=>{e.ctrlKey||e.metaKey||e.altKey||e.target.closest?.("input, textarea, select, [contenteditable], .dm-slideover")||(e.key==="/"&&(e.preventDefault(),l.querySelector(".chats-search input")?.focus()),e.key==="Escape"&&o.peek()&&C())};document.addEventListener("keydown",ie),r.add(()=>document.removeEventListener("keydown",ie)),Pe(l,"chats");const Q=l.querySelector('a[href="#/launchers/knowledge"]');if(Q&&(z==="#/ai-assist"?Q.remove():Q.setAttribute("href",`${z}/knowledge`)),I.scan(l),await w(),s()&&o.peek()){const e=o.peek();o.value="",j(e)}s()&&/[?&]settings=1\b/.test(location.hash)&&(history.replaceState(null,"",b),re())}};
@@ -1 +1 @@
1
- const i={templateUrl:"",async onMount(){location.hash="#/menus"}};export const viewLoaders={projects:()=>import("./projects.js").then(e=>e.projectsView),projectDetail:()=>import("./project-detail.js").then(e=>e.projectDetailView),projectSettings:()=>import("./project-settings.js").then(e=>e.projectSettingsView),apiTokens:()=>import("./api-tokens.js").then(e=>e.apiTokensView),apiEndpoints:()=>import("./api-endpoints.js").then(e=>e.apiEndpointsView),apiEndpointEditor:()=>import("./api-endpoint-editor.js").then(e=>e.apiEndpointEditorView),dashboard:()=>import("./dashboard.js").then(e=>e.dashboardView),dashboards:()=>import("./dashboards.js").then(e=>e.dashboardsView),pages:()=>import("./pages.js").then(e=>e.pagesView),pageEditor:()=>import("./page-editor.js").then(e=>e.pageEditorView),appearance:()=>import("./appearance.js").then(e=>e.appearanceView),footer:()=>import("./footer.js").then(e=>e.footerView),settings:()=>import("./settings.js").then(e=>e.settingsView),theme:()=>import("./theme.js").then(e=>e.themeView),layouts:()=>import("./layouts.js").then(e=>e.layoutsView),media:()=>import("./media.js").then(e=>e.mediaView),login:()=>import("./login.js").then(e=>e.loginView),users:()=>import("./users.js").then(e=>e.usersView),userEditor:()=>import("./user-editor.js").then(e=>e.userEditorView),plugins:()=>import("./plugins.js").then(e=>e.pluginsView),pluginCode:()=>import("./plugin-code.js").then(e=>e.pluginCodeView),documentation:()=>import("./documentation.js").then(e=>e.documentationView),tutorials:()=>import("./tutorials.js").then(e=>e.tutorialsView),apiReference:()=>import("./api-reference.js").then(e=>e.apiReferenceView),collections:()=>import("./collections.js").then(e=>e.collectionsView),collectionEditor:()=>import("./collection-editor.js").then(e=>e.collectionEditorView),collectionEntries:()=>import("./collection-entries.js").then(e=>e.collectionEntriesView),forms:()=>import("./forms.js").then(e=>e.formsView),formEditor:()=>import("./form-editor.js").then(e=>e.formEditorView),formSubmissions:()=>import("./form-submissions.js").then(e=>e.formSubmissionsView),viewsList:()=>import("./views-list.js").then(e=>e.viewsListView),viewEditor:()=>import("./view-editor.js").then(e=>e.viewEditorView),viewPreview:()=>import("./view-preview.js").then(e=>e.viewPreviewView),actionsList:()=>import("./actions-list.js").then(e=>e.actionsListView),actionEditor:()=>import("./action-editor.js").then(e=>e.actionEditorView),proDocs:()=>import("./pro-docs.js").then(e=>e.proDocsView),blocks:()=>import("./blocks.js").then(e=>e.blocksView),components:()=>import("./components.js").then(e=>e.componentsView),myProfile:()=>import("./my-profile.js").then(e=>e.myProfileView),roles:()=>import("./roles.js").then(e=>e.rolesView),roleEditor:()=>import("./role-editor.js").then(e=>e.roleEditorView),effects:()=>import("./effects.js").then(e=>e.effectsView),search:()=>import("./search.js").then(e=>e.searchView),contentApi:()=>import("./content-api.js").then(e=>e.contentApiView),notes:()=>import("./notes.js").then(e=>e.notesView),chats:()=>import("./chats.js").then(e=>e.chatsView),chatKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),todo:()=>import("./todo.js").then(e=>e.todoView),calculator:()=>import("../lib/calculator.js").then(e=>e.calculatorView),analytics:()=>import("./analytics.js").then(e=>e.analyticsView),seo:()=>import("./seo.js").then(e=>e.seoView),wordpressImport:()=>import("./wordpress-import.js").then(e=>e.wordpressImportView),contacts:()=>import("./contacts.js").then(e=>e.contactsView),callNew:()=>import("./call-new.js").then(e=>e.callNewView),notifications:()=>import("./notifications.js").then(e=>e.notificationsView),menus:()=>import("./menus.js").then(e=>e.menusView),contextMenus:()=>import("./context-menus.js").then(e=>e.contextMenusView),launchers:()=>import("./launchers.js").then(e=>e.launchersView),contextMenuEditor:()=>import("./context-menu-editor.js").then(e=>e.contextMenuEditorView),menuEditor:()=>import("./menu-editor.js").then(e=>e.menuEditorView),menuLocations:()=>import("./menu-locations.js").then(e=>e.menuLocationsView),menusRedirect:async()=>i,pluginGuides:()=>import("./plugin-guides.js").then(e=>e.pluginGuidesView),pluginGuide:()=>import("./plugin-guides.js").then(e=>e.pluginGuideView)};for(const e of["tutorialCrud","tutorialPlugin","tutorialEditor","tutorialForms","componentsReference","componentsHowto","componentsWalkthrough","componentsRules","usagePages","usageMedia","usageNavigation","usageDconfig","usageShortcodes","usageSiteSettings","usagePlugins","usageUsersRoles","usageViews","usageActions","usageCtaShortcode","usageEditions","usageCollections","usageBlocks","usageTools","usageDashboard","usageSearchEngines","usageLaunchers","usageChat","apiRefAuthentication","apiRefPages","apiRefSettings","apiRefLayouts","apiRefNavigation","apiRefMedia","apiRefUsers","apiRefPlugins","apiRefCollections","apiRefViews","apiRefActions","apiRefForms","apiRefScaffold","apiRefExternal","apiRefContent","apiRefBuilder"])viewLoaders[e]=()=>import("./doc-pages.js").then(t=>t.docViews[e]);
1
+ const i={templateUrl:"",async onMount(){location.hash="#/menus"}};export const viewLoaders={projects:()=>import("./projects.js").then(e=>e.projectsView),projectDetail:()=>import("./project-detail.js").then(e=>e.projectDetailView),projectSettings:()=>import("./project-settings.js").then(e=>e.projectSettingsView),apiTokens:()=>import("./api-tokens.js").then(e=>e.apiTokensView),apiEndpoints:()=>import("./api-endpoints.js").then(e=>e.apiEndpointsView),apiEndpointEditor:()=>import("./api-endpoint-editor.js").then(e=>e.apiEndpointEditorView),dashboard:()=>import("./dashboard.js").then(e=>e.dashboardView),dashboards:()=>import("./dashboards.js").then(e=>e.dashboardsView),pages:()=>import("./pages.js").then(e=>e.pagesView),pageEditor:()=>import("./page-editor.js").then(e=>e.pageEditorView),appearance:()=>import("./appearance.js").then(e=>e.appearanceView),footer:()=>import("./footer.js").then(e=>e.footerView),settings:()=>import("./settings.js").then(e=>e.settingsView),theme:()=>import("./theme.js").then(e=>e.themeView),layouts:()=>import("./layouts.js").then(e=>e.layoutsView),media:()=>import("./media.js").then(e=>e.mediaView),login:()=>import("./login.js").then(e=>e.loginView),users:()=>import("./users.js").then(e=>e.usersView),userEditor:()=>import("./user-editor.js").then(e=>e.userEditorView),plugins:()=>import("./plugins.js").then(e=>e.pluginsView),pluginCode:()=>import("./plugin-code.js").then(e=>e.pluginCodeView),documentation:()=>import("./documentation.js").then(e=>e.documentationView),tutorials:()=>import("./tutorials.js").then(e=>e.tutorialsView),apiReference:()=>import("./api-reference.js").then(e=>e.apiReferenceView),collections:()=>import("./collections.js").then(e=>e.collectionsView),collectionEditor:()=>import("./collection-editor.js").then(e=>e.collectionEditorView),collectionEntries:()=>import("./collection-entries.js").then(e=>e.collectionEntriesView),forms:()=>import("./forms.js").then(e=>e.formsView),formEditor:()=>import("./form-editor.js").then(e=>e.formEditorView),formSubmissions:()=>import("./form-submissions.js").then(e=>e.formSubmissionsView),viewsList:()=>import("./views-list.js").then(e=>e.viewsListView),viewEditor:()=>import("./view-editor.js").then(e=>e.viewEditorView),viewPreview:()=>import("./view-preview.js").then(e=>e.viewPreviewView),actionsList:()=>import("./actions-list.js").then(e=>e.actionsListView),actionEditor:()=>import("./action-editor.js").then(e=>e.actionEditorView),proDocs:()=>import("./pro-docs.js").then(e=>e.proDocsView),blocks:()=>import("./blocks.js").then(e=>e.blocksView),components:()=>import("./components.js").then(e=>e.componentsView),myProfile:()=>import("./my-profile.js").then(e=>e.myProfileView),roles:()=>import("./roles.js").then(e=>e.rolesView),roleEditor:()=>import("./role-editor.js").then(e=>e.roleEditorView),effects:()=>import("./effects.js").then(e=>e.effectsView),search:()=>import("./search.js").then(e=>e.searchView),contentApi:()=>import("./content-api.js").then(e=>e.contentApiView),notes:()=>import("./notes.js").then(e=>e.notesView),chats:()=>import("./chats.js").then(e=>e.chatsView),chatKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),aiAssistChats:()=>import("./chats.js").then(e=>e.chatsView),aiAssistKnowledge:()=>import("./chat-knowledge.js").then(e=>e.chatKnowledgeView),aiAssistSettings:()=>import("./ai-assist-settings.js").then(e=>e.aiAssistSettingsView),aiAssistBuilders:()=>import("./ai-assist-builders.js").then(e=>e.aiAssistBuildersView),todo:()=>import("./todo.js").then(e=>e.todoView),calculator:()=>import("../lib/calculator.js").then(e=>e.calculatorView),analytics:()=>import("./analytics.js").then(e=>e.analyticsView),seo:()=>import("./seo.js").then(e=>e.seoView),wordpressImport:()=>import("./wordpress-import.js").then(e=>e.wordpressImportView),contacts:()=>import("./contacts.js").then(e=>e.contactsView),callNew:()=>import("./call-new.js").then(e=>e.callNewView),notifications:()=>import("./notifications.js").then(e=>e.notificationsView),menus:()=>import("./menus.js").then(e=>e.menusView),contextMenus:()=>import("./context-menus.js").then(e=>e.contextMenusView),launchers:()=>import("./launchers.js").then(e=>e.launchersView),contextMenuEditor:()=>import("./context-menu-editor.js").then(e=>e.contextMenuEditorView),menuEditor:()=>import("./menu-editor.js").then(e=>e.menuEditorView),menuLocations:()=>import("./menu-locations.js").then(e=>e.menuLocationsView),menusRedirect:async()=>i,pluginGuides:()=>import("./plugin-guides.js").then(e=>e.pluginGuidesView),pluginGuide:()=>import("./plugin-guides.js").then(e=>e.pluginGuideView)};for(const e of["tutorialCrud","tutorialPlugin","tutorialEditor","tutorialForms","componentsReference","componentsHowto","componentsWalkthrough","componentsRules","usagePages","usageMedia","usageNavigation","usageDconfig","usageShortcodes","usageSiteSettings","usagePlugins","usageUsersRoles","usageViews","usageActions","usageCtaShortcode","usageEditions","usageCollections","usageBlocks","usageTools","usageDashboard","usageSearchEngines","usageLaunchers","usageChat","apiRefAuthentication","apiRefPages","apiRefSettings","apiRefLayouts","apiRefNavigation","apiRefMedia","apiRefUsers","apiRefPlugins","apiRefCollections","apiRefViews","apiRefActions","apiRefForms","apiRefScaffold","apiRefExternal","apiRefContent","apiRefBuilder"])viewLoaders[e]=()=>import("./doc-pages.js").then(t=>t.docViews[e]);
@@ -1 +1 @@
1
- import{api as l,isAuthenticated as A,setAuthData as f,takePendingLogout as D}from"../api.js";import{themesInDisplayOrder as O}from"../lib/themes.js";import{enhancePasswordFields as b}from"../lib/password-field.js";import{challengeText as g,loginBrandFromStatus as S,minutesText as j,passwordVerdict as z,readLoginHash as H,resetTokenFrom as N}from"../lib/login-arrange.js";import{viewLifetime as V}from"../lib/tool-kit.js";import{applyAdminBrand as W}from"../lib/admin-brand.js";import{isDarkAdminTheme as Y}from"../lib/theme-aware-logo.js";const K={name:{type:"string",required:!0,minLength:2,label:"Full Name",formConfig:{placeholder:"Your name",autocomplete:"name"}},email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"admin@example.com",autocomplete:"email"}},password:{type:"password",required:!0,minLength:8,label:"Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password",tooltip:"Minimum 8 characters"}}},U={email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"you@example.com",autocomplete:"email"}},password:{type:"password",required:!0,label:"Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"current-password"}}},G={email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"you@example.com",autocomplete:"email"}}},J={password:{type:"password",required:!0,minLength:8,label:"New Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password"}},confirmPassword:{type:"password",required:!0,label:"Confirm Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password"}}};let T=Promise.resolve();function Q(){let e;T=new Promise(o=>{e=o});const t=M.subscribe("router:afterChange",()=>{a(),e()}),a=()=>{typeof t=="function"&&t()};setTimeout(()=>{a(),e()},1500)}function y(e){T.then(()=>R.navigate(e))}const m=V(/^#\/(login|reset-password)(\?|$)/);function X(){const e=M.observable(null),t=M.observable("code"),a=M.observable(S()),o=M.observable("");return{step:M.observable(""),siteTitle:M.observable("Domma CMS"),brand:a,brandTheme:o,brandLogo:M.computed(()=>{o.value;const r=a.value;return Y()?r.logoDark||r.logo:r.logo||r.logoDark}),notice:M.observable(""),byEmail:M.observable(!0),expiresIn:M.observable(""),obTitle:M.observable(""),obTagline:M.observable(""),obSiteError:M.observable(""),obSiteSaving:M.observable(!1),themes:O(),theme:M.observable("charcoal-dark"),obThemeError:M.observable(""),obThemeSaving:M.observable(!1),chChallenge:e,chMode:t,chTitle:M.computed(()=>e.value?.title||"One more step"),chLabel:M.computed(()=>g(e.value,t.value).label),chHelp:M.computed(()=>g(e.value,t.value).help),chInputMode:M.computed(()=>g(e.value,t.value).inputMode),chImage:M.computed(()=>e.value?.image||""),chSecret:M.computed(()=>e.value?.secret||""),chCanTrust:M.computed(()=>e.value?.trust===!0),chCanRecover:M.computed(()=>e.value?.recovery===!0),chCode:M.observable(""),chTrust:M.observable(!1),chError:M.observable(""),chBusy:M.observable(!1),resetEmail:M.observable(""),resetExpiry:M.observable(""),resetLines:M.observable([])}}function w(e,t={}){e.byEmail.value=t.resetByEmail!==!1,e.expiresIn.value=t.resetExpiresIn||"";const a=S(t);e.brand.value=a,e.siteTitle.value=a.title,W(a)}export const loginView={templateUrl:"/admin/js/templates/login.html",async onMount(e){m.reset(),Q();const t=D(),a=window.location.hash,{next:o,expired:r}=H(a);if(A()){y(a.startsWith("#/reset-password")?"/":o);return}const n=e.get(0).querySelector(".login-wrap")||e.get(0),u=X(),c={state:u,root:n,next:o,token:"",email:"",pw:{problems:[],asked:0,timer:null}},p=M.applyBindings(u,n,{methods:Z(c)});if(m.add(()=>p.dispose()),m.add(()=>clearTimeout(c.pw.timer)),m.add(M.effect(()=>{u.step.value;const s=u.brand.value;requestAnimationFrame(()=>{if(!n.isConnected)return;const d=n.querySelector(".login-brand-icon"),i=I.render(s.icon,{size:32})||I.render("layout",{size:32});d&&i&&d.replaceChildren(i),I.scan(n)})})),m.add(Domma.theme.onChange(()=>{u.brandTheme.value=Domma.theme.get()})),a.startsWith("#/reset-password")){await ae(c,N(a));return}let h=!1;const v=E.loader(e.get(0),{type:"dots"});try{const s=await l.auth.setupStatus();h=s.needsSetup,w(u,s)}catch{E.toast("Could not reach the server.",{type:"error"})}finally{v.destroy()}h?(u.step.value="setup",_(c)):(u.step.value="login",k(c),r&&!t&&(u.notice.value="Your session ended - sign in again to carry on where you were."))}};function Z(e){const{state:t}=e,a=o=>r=>{r?.preventDefault?.(),o()};return{skipSite:a(()=>{t.step.value="onboarding-theme"}),saveSite:()=>$(t),pickTheme:o=>{t.theme.value=o},skipTheme:a(()=>{t.step.value="onboarding-done"}),saveTheme:()=>ee(t),backToLogin:a(()=>{t.step.value="login"}),forgot:a(()=>{const o=String(e.root.querySelector('#login-form-container input[type="email"]')?.value||"").trim();t.step.value="forgot",q(e,o)}),toggleRecovery:a(()=>C(t,t.chMode.value==="code"?"recovery":"code")),copySecret:async()=>{try{await navigator.clipboard.writeText(String(t.chSecret.value).replace(/\s+/g,"")),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - select the key and copy it.",{type:"warning"})}},verify:o=>{o?.preventDefault?.(),te(e)},newLink:a(async()=>{try{w(t,await l.auth.setupStatus())}catch{}t.step.value="forgot",q(e)}),signInAfterReset:a(()=>{t.step.value="login",k(e,{email:e.email})})}}function _(e){F.render("#setup-form-container",K,{},{layout:"stacked",submitText:"Create admin account",onSubmit:async t=>{try{const a=await l.auth.setup(t);f(a),e.state.step.value="onboarding-site"}catch(a){return E.toast(a.message||"Setup failed. Please try again.",{type:"error"}),!1}}}),b(e.root.querySelector("#setup-form-container"))}async function $(e){e.obSiteError.value="";const t=e.obTitle.value.trim(),a=e.obTagline.value.trim();e.obSiteSaving.value=!0;try{const o=await l.settings.get();await l.settings.save({...o,title:t||o.title,tagline:a||o.tagline,brand:{...o.brand||{},text:t||o.brand?.text||o.title},seo:{...o.seo||{},defaultTitle:t||o.seo&&o.seo.defaultTitle}}),e.step.value="onboarding-theme"}catch(o){e.obSiteError.value=o.message||"Could not save site details."}finally{e.obSiteSaving.value=!1}}async function ee(e){e.obThemeError.value="",e.obThemeSaving.value=!0;try{await l.theme.save({theme:e.theme.value||"charcoal-dark"}),e.step.value="onboarding-done"}catch(t){e.obThemeError.value=t.message||"Could not save theme."}finally{e.obThemeSaving.value=!1}}function k(e,{email:t=""}={}){F.render("#login-form-container",U,t?{email:t}:{},{layout:"stacked",submitText:"Sign in",onSubmit:async a=>{try{const o=await l.auth.login(a);if(o?.challenge&&o.ticket)return x(e,o),!1;f(o),y(e.next)}catch(o){return E.toast(o.message||"Invalid credentials. Please try again.",{type:"error"}),!1}}}),b(e.root.querySelector("#login-form-container"))}function x(e,{challenge:t,ticket:a}){const{state:o}=e;e.ticket=a,o.chChallenge.value=t||{},o.chTrust.value=!1,C(o,"code"),o.step.value="challenge"}function C(e,t){e.chMode.value=t,e.chCode.value="",e.chError.value="",setTimeout(()=>document.getElementById("challenge-code")?.focus(),0)}async function te(e){const{state:t}=e;t.chBusy.value=!0;try{const a=await l.auth.verifyLogin({ticket:e.ticket,response:String(t.chCode.value||"").trim(),mode:t.chMode.value,trust:t.chTrust.value===!0});if(a?.challenge&&a.ticket){x(e,a);return}f(a),y(e.next)}catch(a){const o=a.message||"That did not match.";t.chError.value=o,/sign in again/i.test(o)&&setTimeout(()=>{t.step.value="login"},1800)}finally{t.chBusy.value=!1}}function q(e,t=""){const{state:a}=e;a.byEmail.value&&F.render("#forgot-form-container",G,t?{email:t}:{},{layout:"stacked",submitText:"Send reset link",onSubmit:async o=>{try{const r=await l.auth.forgotPassword(o.email);r?.expiresIn&&(a.expiresIn.value=r.expiresIn)}catch{}a.step.value="forgot-success"}})}async function ae(e,t){const{state:a}=e;if(!t){a.step.value="reset-invalid";return}const o=E.loader(e.root,{type:"dots"});let r;l.auth.setupStatus().then(n=>w(a,n)).catch(()=>{});try{r=await l.auth.checkReset(t)}catch{a.step.value="reset-invalid";return}finally{o.destroy()}e.token=t,e.email=r.email||"",a.resetEmail.value=e.email,a.resetExpiry.value=j(r.minutesLeft),a.step.value="reset",oe(e)}function oe(e){const{state:t,token:a,email:o,pw:r}=e,n=e.root.querySelector("#reset-form-container"),u=()=>({password:String(n.querySelector('input[name="password"]')?.value||""),confirm:String(n.querySelector('input[name="confirmPassword"]')?.value||"")}),c=()=>{const{password:s,confirm:d}=u(),i=z({password:s,confirm:d,problems:r.problems}),L=[...i.messages,...i.mismatch?["The two passwords do not match yet."]:[]];return t.resetLines.value=s?L.map((P,B)=>({id:B,text:P})):[],i},p=async()=>{const{password:s}=u(),d=++r.asked;if(s.length<8){r.problems=[],c();return}try{const i=await l.auth.checkReset(a,s);d===r.asked&&(r.problems=i.problems||[])}catch(i){if(i.body?.expired){t.step.value="reset-invalid";return}}d===r.asked&&c()};F.render("#reset-form-container",J,{},{layout:"stacked",submitText:"Set new password",onSubmit:async s=>{await p();const d=c();if(!d.ok)return E.toast(d.mismatch?"The passwords do not match.":"That password does not meet the rules below.",{type:"error"}),!1;try{await l.auth.resetPassword(a,s.password),history.replaceState(null,"","#/reset-password"),t.step.value="reset-done"}catch(i){return i.body?.expired?(t.step.value="reset-invalid",!1):(r.problems=i.body?.problems||[],c(),E.toast(i.message||"The password was not changed.",{type:"error"}),!1)}}});const h=n.querySelector("form")||n;if(o){const s=document.createElement("input");s.type="email",s.name="username",s.autocomplete="username",s.value=o,s.readOnly=!0,s.hidden=!0,h.prepend(s)}b(n);const v=s=>{s.target.matches?.('input[type="password"], input[name="password"], input[name="confirmPassword"]')&&(s.target.name==="password"&&(r.problems=[]),c(),clearTimeout(r.timer),s.target.name==="password"&&(r.timer=setTimeout(p,400)))};n.addEventListener("input",v),m.add(()=>n.removeEventListener("input",v))}
1
+ import{api as u,isAuthenticated as D,setAuthData as f,takePendingLogout as O}from"../api.js";import{themesInDisplayOrder as j}from"../lib/themes.js";import{enhancePasswordFields as b}from"../lib/password-field.js";import{challengeText as g,loginBrandFromStatus as S,minutesText as z,passwordVerdict as H,readLoginHash as N,resetTokenFrom as V}from"../lib/login-arrange.js";import{viewLifetime as W}from"../lib/tool-kit.js";import{applyAdminBrand as Y}from"../lib/admin-brand.js";import{isDarkAdminTheme as K}from"../lib/theme-aware-logo.js";import{applyAdminTheme as T}from"../lib/admin-theme.js";const U={name:{type:"string",required:!0,minLength:2,label:"Full Name",formConfig:{placeholder:"Your name",autocomplete:"name"}},email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"admin@example.com",autocomplete:"email"}},password:{type:"password",required:!0,minLength:8,label:"Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password",tooltip:"Minimum 8 characters"}}},G={email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"you@example.com",autocomplete:"email"}},password:{type:"password",required:!0,label:"Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"current-password"}}},J={email:{type:"email",required:!0,label:"Email Address",formConfig:{placeholder:"you@example.com",autocomplete:"email"}}},Q={password:{type:"password",required:!0,minLength:8,label:"New Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password"}},confirmPassword:{type:"password",required:!0,label:"Confirm Password",formConfig:{placeholder:"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",autocomplete:"new-password"}}};let k=Promise.resolve();function X(){let e;k=new Promise(o=>{e=o});const t=M.subscribe("router:afterChange",()=>{a(),e()}),a=()=>{typeof t=="function"&&t()};setTimeout(()=>{a(),e()},1500)}function y(e){k.then(()=>R.navigate(e))}const d=W(/^#\/(login|reset-password)(\?|$)/);function Z(){const e=M.observable(null),t=M.observable("code"),a=M.observable(S()),o=M.observable("");return{step:M.observable(""),siteTitle:M.observable("Domma CMS"),brand:a,brandTheme:o,brandLogo:M.computed(()=>{o.value;const r=a.value;return K()?r.logoDark||r.logo:r.logo||r.logoDark}),notice:M.observable(""),byEmail:M.observable(!0),expiresIn:M.observable(""),obTitle:M.observable(""),obTagline:M.observable(""),obSiteError:M.observable(""),obSiteSaving:M.observable(!1),themes:j(),theme:M.observable("charcoal-dark"),obThemeError:M.observable(""),obThemeSaving:M.observable(!1),chChallenge:e,chMode:t,chTitle:M.computed(()=>e.value?.title||"One more step"),chLabel:M.computed(()=>g(e.value,t.value).label),chHelp:M.computed(()=>g(e.value,t.value).help),chInputMode:M.computed(()=>g(e.value,t.value).inputMode),chImage:M.computed(()=>e.value?.image||""),chSecret:M.computed(()=>e.value?.secret||""),chCanTrust:M.computed(()=>e.value?.trust===!0),chCanRecover:M.computed(()=>e.value?.recovery===!0),chCode:M.observable(""),chTrust:M.observable(!1),chError:M.observable(""),chBusy:M.observable(!1),resetEmail:M.observable(""),resetExpiry:M.observable(""),resetLines:M.observable([])}}function w(e,t={}){T(t.adminTheme||{dommaTheme:"charcoal-light"}),e.byEmail.value=t.resetByEmail!==!1,e.expiresIn.value=t.resetExpiresIn||"";const a=S(t);e.brand.value=a,e.siteTitle.value=a.title,Y(a)}export const loginView={templateUrl:"/admin/js/templates/login.html",async onMount(e){d.reset(),X();const t=O(),a=window.location.hash,{next:o,expired:r}=N(a);if(D()){y(a.startsWith("#/reset-password")?"/":o);return}const i=e.get(0).querySelector(".login-wrap")||e.get(0),l=Z(),c={state:l,root:i,next:o,token:"",email:"",pw:{problems:[],asked:0,timer:null}},p=M.applyBindings(l,i,{methods:_(c)});if(d.add(()=>p.dispose()),d.add(()=>clearTimeout(c.pw.timer)),d.add(M.effect(()=>{l.step.value;const s=l.brand.value;requestAnimationFrame(()=>{if(!i.isConnected)return;const m=i.querySelector(".login-brand-icon"),n=I.render(s.icon,{size:32})||I.render("layout",{size:32});m&&n&&m.replaceChildren(n),I.scan(i)})})),d.add(Domma.theme.onChange(()=>{l.brandTheme.value=Domma.theme.get()})),a.startsWith("#/reset-password")){try{w(l,await u.auth.setupStatus())}catch{T({dommaTheme:"charcoal-light"})}await oe(c,V(a));return}let h=!1;const v=E.loader(e.get(0),{type:"dots"});try{const s=await u.auth.setupStatus();h=s.needsSetup,w(l,s)}catch{E.toast("Could not reach the server.",{type:"error"})}finally{v.destroy()}h?(l.step.value="setup",$(c)):(l.step.value="login",x(c),r&&!t&&(l.notice.value="Your session ended - sign in again to carry on where you were."))}};function _(e){const{state:t}=e,a=o=>r=>{r?.preventDefault?.(),o()};return{skipSite:a(()=>{t.step.value="onboarding-theme"}),saveSite:()=>ee(t),pickTheme:o=>{t.theme.value=o},skipTheme:a(()=>{t.step.value="onboarding-done"}),saveTheme:()=>te(t),backToLogin:a(()=>{t.step.value="login"}),forgot:a(()=>{const o=String(e.root.querySelector('#login-form-container input[type="email"]')?.value||"").trim();t.step.value="forgot",L(e,o)}),toggleRecovery:a(()=>q(t,t.chMode.value==="code"?"recovery":"code")),copySecret:async()=>{try{await navigator.clipboard.writeText(String(t.chSecret.value).replace(/\s+/g,"")),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - select the key and copy it.",{type:"warning"})}},verify:o=>{o?.preventDefault?.(),ae(e)},newLink:a(async()=>{try{w(t,await u.auth.setupStatus())}catch{}t.step.value="forgot",L(e)}),signInAfterReset:a(()=>{t.step.value="login",x(e,{email:e.email})})}}function $(e){F.render("#setup-form-container",U,{},{layout:"stacked",submitText:"Create admin account",onSubmit:async t=>{try{const a=await u.auth.setup(t);f(a),e.state.step.value="onboarding-site"}catch(a){return E.toast(a.message||"Setup failed. Please try again.",{type:"error"}),!1}}}),b(e.root.querySelector("#setup-form-container"))}async function ee(e){e.obSiteError.value="";const t=e.obTitle.value.trim(),a=e.obTagline.value.trim();e.obSiteSaving.value=!0;try{const o=await u.settings.get();await u.settings.save({...o,title:t||o.title,tagline:a||o.tagline,brand:{...o.brand||{},text:t||o.brand?.text||o.title},seo:{...o.seo||{},defaultTitle:t||o.seo&&o.seo.defaultTitle}}),e.step.value="onboarding-theme"}catch(o){e.obSiteError.value=o.message||"Could not save site details."}finally{e.obSiteSaving.value=!1}}async function te(e){e.obThemeError.value="",e.obThemeSaving.value=!0;try{await u.theme.save({theme:e.theme.value||"charcoal-dark"}),e.step.value="onboarding-done"}catch(t){e.obThemeError.value=t.message||"Could not save theme."}finally{e.obThemeSaving.value=!1}}function x(e,{email:t=""}={}){F.render("#login-form-container",G,t?{email:t}:{},{layout:"stacked",submitText:"Sign in",onSubmit:async a=>{try{const o=await u.auth.login(a);if(o?.challenge&&o.ticket)return C(e,o),!1;f(o),y(e.next)}catch(o){return E.toast(o.message||"Invalid credentials. Please try again.",{type:"error"}),!1}}}),b(e.root.querySelector("#login-form-container"))}function C(e,{challenge:t,ticket:a}){const{state:o}=e;e.ticket=a,o.chChallenge.value=t||{},o.chTrust.value=!1,q(o,"code"),o.step.value="challenge"}function q(e,t){e.chMode.value=t,e.chCode.value="",e.chError.value="",setTimeout(()=>document.getElementById("challenge-code")?.focus(),0)}async function ae(e){const{state:t}=e;t.chBusy.value=!0;try{const a=await u.auth.verifyLogin({ticket:e.ticket,response:String(t.chCode.value||"").trim(),mode:t.chMode.value,trust:t.chTrust.value===!0});if(a?.challenge&&a.ticket){C(e,a);return}f(a),y(e.next)}catch(a){const o=a.message||"That did not match.";t.chError.value=o,/sign in again/i.test(o)&&setTimeout(()=>{t.step.value="login"},1800)}finally{t.chBusy.value=!1}}function L(e,t=""){const{state:a}=e;a.byEmail.value&&F.render("#forgot-form-container",J,t?{email:t}:{},{layout:"stacked",submitText:"Send reset link",onSubmit:async o=>{try{const r=await u.auth.forgotPassword(o.email);r?.expiresIn&&(a.expiresIn.value=r.expiresIn)}catch{}a.step.value="forgot-success"}})}async function oe(e,t){const{state:a}=e;if(!t){a.step.value="reset-invalid";return}const o=E.loader(e.root,{type:"dots"});let r;try{r=await u.auth.checkReset(t)}catch{a.step.value="reset-invalid";return}finally{o.destroy()}e.token=t,e.email=r.email||"",a.resetEmail.value=e.email,a.resetExpiry.value=z(r.minutesLeft),a.step.value="reset",re(e)}function re(e){const{state:t,token:a,email:o,pw:r}=e,i=e.root.querySelector("#reset-form-container"),l=()=>({password:String(i.querySelector('input[name="password"]')?.value||""),confirm:String(i.querySelector('input[name="confirmPassword"]')?.value||"")}),c=()=>{const{password:s,confirm:m}=l(),n=H({password:s,confirm:m,problems:r.problems}),P=[...n.messages,...n.mismatch?["The two passwords do not match yet."]:[]];return t.resetLines.value=s?P.map((B,A)=>({id:A,text:B})):[],n},p=async()=>{const{password:s}=l(),m=++r.asked;if(s.length<8){r.problems=[],c();return}try{const n=await u.auth.checkReset(a,s);m===r.asked&&(r.problems=n.problems||[])}catch(n){if(n.body?.expired){t.step.value="reset-invalid";return}}m===r.asked&&c()};F.render("#reset-form-container",Q,{},{layout:"stacked",submitText:"Set new password",onSubmit:async s=>{await p();const m=c();if(!m.ok)return E.toast(m.mismatch?"The passwords do not match.":"That password does not meet the rules below.",{type:"error"}),!1;try{await u.auth.resetPassword(a,s.password),history.replaceState(null,"","#/reset-password"),t.step.value="reset-done"}catch(n){return n.body?.expired?(t.step.value="reset-invalid",!1):(r.problems=n.body?.problems||[],c(),E.toast(n.message||"The password was not changed.",{type:"error"}),!1)}}});const h=i.querySelector("form")||i;if(o){const s=document.createElement("input");s.type="email",s.name="username",s.autocomplete="username",s.value=o,s.readOnly=!0,s.hidden=!0,h.prepend(s)}b(i);const v=s=>{s.target.matches?.('input[type="password"], input[name="password"], input[name="confirmPassword"]')&&(s.target.name==="password"&&(r.problems=[]),c(),clearTimeout(r.timer),s.target.name==="password"&&(r.timer=setTimeout(p,400)))};i.addEventListener("input",v),d.add(()=>i.removeEventListener("input",v))}
@@ -1,11 +1,11 @@
1
- import{api as $,apiRequest as w}from"../api.js";import{placeTools as Oe,WITHHELD_URL as Re}from"../lib/sidebar-grouping.js";import{addBannerAction as me}from"../lib/plugin-chrome.js";import{helpPopovers as Ie}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as fe}from"../lib/tool-kit.js";import{changedTabs as Ae,describeCacheKey as J,draftOf as De,expiresIn as He,formFromDraft as Pe,siteSettingsForm as $e,homeValue as Be,siteSettingsPayload as je,siteUrlError as he,settingsProblems as Ue,snapshot as ve,TAB_FIELDS as qe}from"../lib/site-settings-arrange.js";import{pickMedia as _e}from"../lib/media-picker.js";import{makeIconInput as Ke}from"../lib/shortcode-modal.js";import{fmtDateTime as Fe}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,be="#/settings",g="settings.draft",We=`
1
+ import{api as $,apiRequest as g}from"../api.js";import{placeTools as Re,WITHHELD_URL as Ie}from"../lib/sidebar-grouping.js";import{addBannerAction as fe}from"../lib/plugin-chrome.js";import{helpPopovers as Ae}from"../lib/help-popover.js";import{openMenuAt as G,sidebarCount as he}from"../lib/tool-kit.js";import{changedTabs as De,describeCacheKey as J,draftOf as He,expiresIn as Pe,formFromDraft as $e,siteSettingsForm as Be,homeValue as je,siteSettingsPayload as Ue,siteUrlError as ve,settingsProblems as qe,snapshot as be,TAB_FIELDS as _e}from"../lib/site-settings-arrange.js";import{pickMedia as Ke}from"../lib/media-picker.js";import{makeIconInput as Fe}from"../lib/shortcode-modal.js";import{fmtDateTime as We}from"../lib/dates.js";const Q=/^\/settings(\?.*)?$/,ge="#/settings",y="settings.draft",ze=`
2
2
  <div class="stx-problem">
3
3
  <span class="stx-chip" data-bind-class="tone === 'danger' ? 'is-bad' : 'is-warn'">{{label}}</span>
4
4
  <span>{{text}}</span>
5
5
  <button type="button" class="btn btn-sm btn-ghost" data-go="{{tab}}">Go there</button>
6
- </div>`,ze=`
6
+ </div>`,Ne=`
7
7
  <div class="stx-row" data-id="{{id}}" tabindex="0">
8
8
  <span class="stx-main"><strong>{{path}}</strong><small>{{meta}}</small></span>
9
9
  <span class="stx-chip">{{expires}}</span>
10
10
  <button type="button" class="stx-kebab" aria-label="Actions for {{path}}" title="Actions">\u22EE</button>
11
- </div>`,B=["general","branding","email","cookies","cache"];async function Ne(c,l){const[r,y]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Re)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(y||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Oe(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ge=!1;function Ve(){ge||!window.R?.use||(ge=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ve(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let y=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!y&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=$e(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>ve(v.value)),x=M.computed(()=>ve(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(Ae(j(),v.value));return Object.fromEntries(Object.keys(qe).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=Ue(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:He(s.expiresAt,t)}})}));const ye={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>he(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=he(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(je(e,u.peek(),{adminHomeReady:q.peek()})),window.dispatchEvent(new Event("admin-assistant:settings"));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Le={...e,smtpPass:""};a.smtpPass.value="",v.value=Le;try{S.remove?S.remove(g):S.set(g,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(pe=>e[pe]!==t[pe]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),fe(be),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function we(){await E.confirm("Throw away your unsaved settings?")&&(ae(v.peek()),T.value="")}function ae(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function ke(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await w("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([w("/cache/status").catch(()=>null),w("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Ee(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await w("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Se(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await w("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),fe(be)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const ne=e=>K.peek().find(t=>t.key===e);function Me(e){const t=ne(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=We;const b=n.querySelector(".stx-list");b.innerHTML=ze;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),oe=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(oe)&&V.activate(B.indexOf(oe));const xe=M.applyBindings(ye,n,{methods:{save:N,discard:we,sendTest:ke,refreshCache:D,clearCache:Ee,toggleCache:Se,pickBrandImage:async e=>{const t=await _e({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>xe.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Ke("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ie(n,{position:"bottom"}));const Ce=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Ce);const Y=n.querySelector("#stx-admin-home");Ne(Y,Be(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Te=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});r(()=>Te?.destroy?.());const re=e=>{const t=ne(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ie=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}re(t)},ce=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&re(t))};b.addEventListener("click",ie),b.addEventListener("keydown",ce),r(()=>{b.removeEventListener("click",ie),b.removeEventListener("keydown",ce)}),me(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),me(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const le=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",le,!0),r(()=>document.removeEventListener("keydown",le,!0));const ue=()=>{if(x.peek())try{S.set(g,{form:De(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},de=e=>{x.peek()&&(ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",de),r(()=>window.removeEventListener("beforeunload",de)),f={dirty:()=>x.peek(),dispose(){y=!0,ue(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(g)}catch{}if(h?.form){try{S.remove?S.remove(g):S.set(g,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${Fe(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ae(Pe(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
11
+ </div>`,B=["general","branding","email","cookies","cache"];async function Ve(c,l){const[r,w]=await Promise.all([H.get("/api/sidebar/menu").catch(()=>({items:[]})),H.get("/api/sidebar/registered-items").catch(()=>[])]),n=new Map([["/","Dashboard (built in)"]]),i=(p,u)=>{for(const o of p||[]){if(!o||o.hidden||o.restricted)continue;const a=typeof o.url=="string"?o.url:"";a.startsWith(Ie)||(a.startsWith("#/")&&a.length>2&&!n.has(a.slice(1))&&n.set(a.slice(1),`${u?`${u} \u203A `:""}${o.text||a}`),i(o.items,o.url?u:o.text||u))}},k=(w||[]).filter(p=>!/^~\d+$/.test(String(p?.item?.text||"")));i(Re(r?.items||[],k),""),n.has(l)||n.set(l,`${l} (not in the sidebar)`),c.replaceChildren();for(const[p,u]of n){const o=document.createElement("option");o.value=p,o.textContent=u,c.appendChild(o)}}let f=null,ye=!1;function Ye(){ye||!window.R?.use||(ye=!0,R.use((c,l,r)=>!(Q.test(l?.path||"")&&!Q.test(c?.path||""))||!f?.dirty()?r():E.confirm("You have unsaved settings. Leave anyway? They are kept as a draft for your next visit (not the SMTP password).").then(n=>{n?r():history.replaceState(null,"","#/settings")})),M.subscribe("router:afterChange",({to:c}={})=>{if(f&&!Q.test(c?.path||"")){const l=f;f=null,l.dispose()}}))}export const settingsView={templateUrl:"/admin/js/templates/settings.html",async onMount(c){if(Ye(),f){const e=f;f=null,e.dispose()}const l=[],r=e=>(l.push(e),e);let w=!1;const n=c.get(0).querySelector(".stx")||c.get(0),i=()=>!w&&n.isConnected,k=E.loader(c.get(0),{type:"dots"});let p;try{p=await $.settings.get()}catch(e){k.destroy(),E.toast(`Could not load the settings: ${e.message||e}`,{type:"error"});return}if(k.destroy(),!n.isConnected)return;const u=M.observable(p||{}),o=Be(p||{}),a={};for(const[e,t]of Object.entries(o))a[e]=M.observable(t);const j=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),X=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),v=M.observable(o),U=M.computed(()=>be(v.value)),x=M.computed(()=>be(j())!==U.value),C=M.observable(!1),T=M.observable(""),Z=M.observable(!1);$.plugins.policy().then(e=>{i()&&(Z.value=e?.signedOnly===!1)}).catch(()=>{});const q=M.observable(!1),ee=M.computed(()=>{const e=new Set(De(j(),v.value));return Object.fromEntries(Object.keys(_e).map(t=>[t,e.has(t)]))}),_=M.observable([]);r(M.effect(()=>{_.value=qe(j(),u.value).map(e=>({...e,label:e.tone==="danger"?"Mail":"Check"}))}));const te=M.observable(""),L=M.observable(!1),O=M.observable(""),A=M.observable(""),m=M.observable(null),K=M.observable([]),F=M.observable(""),W=M.observable(!0),z=M.observable(""),se=M.observable([]);r(M.effect(()=>{const e=F.value.trim().toLowerCase(),t=Date.now();se.value=[...K.value].reverse().filter(s=>!e||String(s.key).toLowerCase().includes(e)||(s.tags||[]).some(d=>String(d).toLowerCase().includes(e))).map(s=>{const d=J(s.key);return{id:s.key,path:d.path,meta:[d.page?`as ${d.role}`:"not a page",(s.tags||[]).join(", ")].filter(Boolean).join(" \xB7 "),expires:Pe(s.expiresAt,t)}})}));const ae=M.observable(!1);g("/ai-assist").catch(()=>null).then(e=>{i()&&(ae.value=e?.on===!0)});const we={...a,saving:C,dirty:x,tabs:ee,problems:_,testTo:te,testing:L,testResult:O,testTone:A,aiAssistOn:ae,cacheQuery:F,cacheLoading:W,cacheError:z,cacheRows:se,errorText:T,problemsText:M.computed(()=>_.value.length?"yes":""),siteUrlError:M.computed(()=>ve(a.siteUrl.value)),noSmtp:M.computed(()=>!String(a.smtpHost.value||"").trim()),mayAllowInsecureTLS:Z,dirtyEmail:M.computed(()=>ee.value.email),cacheOn:M.computed(()=>m.value?.enabled===!0),cacheState:M.computed(()=>{const e=m.value;return e?e.enabled?`On (${e.driver})`:"Off":"Status unknown"}),cacheSize:M.computed(()=>{const e=m.value;return e?.enabled&&e.size!==null&&e.size!==void 0?`${e.size}${e.maxItems?` of ${e.maxItems}`:""} entries`:""}),cacheHits:M.computed(()=>{const e=m.value?.hitRate;return e==null?"":`${Math.round(e*100)}% served from the cache`}),cacheToggleText:M.computed(()=>m.value?.enabled?"Turn off":"Turn on"),cacheEmpty:M.computed(()=>F.value.trim()?"Nothing matches.":m.value?.enabled?"The cache is empty - pages are cached as visitors open them.":"The cache is off.")};async function N(){if(C.peek())return;const e=X(),t=v.peek(),s=ve(e.siteUrl);if(s){E.toast(`Site URL: ${s}`,{type:"error"});return}C.value=!0,T.value="";const d=String(e.title).trim()!==String(t.title).trim();try{await $.settings.save(Ue(e,u.peek(),{adminHomeReady:q.peek()})),window.dispatchEvent(new Event("admin-assistant:settings"));const P=await $.settings.get().catch(()=>null);if(!i())return;P&&(u.value=P);const Oe={...e,smtpPass:""};a.smtpPass.value="",v.value=Oe;try{S.remove?S.remove(y):S.set(y,null)}catch{}document.dispatchEvent(new CustomEvent("dm:admin-home-changed")),(d||["adminBrandEnabled","adminBrandTitle","adminBrandLogo","adminBrandLogoDark","adminBrandIcon"].some(me=>e[me]!==t[me]))&&document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild")),he(ge),E.toast("Settings saved.",{type:"success"})}catch(P){T.value=P.message||"Could not save the settings.",E.toast("Settings not saved - see the message at the top.",{type:"error"})}finally{C.value=!1}}async function ke(){await E.confirm("Throw away your unsaved settings?")&&(ne(v.peek()),T.value="")}function ne(e){for(const[t,s]of Object.entries(e))a[t]&&(a[t].value=s)}async function Ee(){if(!L.peek()){L.value=!0,A.value="",O.value="Sending\u2026";try{const e=await g("/settings/test-email",{method:"POST",body:JSON.stringify({to:te.peek().trim()||void 0})});if(!i())return;O.value=e?.message||"Test email sent.",A.value="is-ok"}catch(e){if(!i())return;O.value=e.message||"Could not send the test email.",A.value="is-bad"}finally{L.value=!1}}}async function D(){W.value=!0;try{const[e,t]=await Promise.all([g("/cache/status").catch(()=>null),g("/cache/keys")]);if(!i())return;m.value=e,K.value=Array.isArray(t?.entries)?t.entries:[],z.value=""}catch(e){if(!i())return;z.value=`Could not read the cache: ${e.message||e}`}finally{W.value=!1}}async function Se(){if(await E.confirm("Clear the whole response cache? The next visitor to each page renders it afresh.")){try{await g("/cache/clear",{method:"POST"}),E.toast("Cache cleared.",{type:"success"})}catch(e){E.toast(e.message||"Could not clear the cache.",{type:"error"})}i()&&await D()}}async function Me(){const e=m.peek()?.enabled===!0;if(!(e&&!await E.confirm("Turn the response cache off? Every visit will render its page afresh until it is turned back on. The choice is saved (config/cache.json)."))){try{m.value=await g("/cache/toggle",{method:"POST",body:JSON.stringify({enabled:!e})}),E.toast(e?"Cache turned off.":"Cache turned on.",{type:"success"}),he(ge)}catch(t){E.toast(t.message||"Could not change the cache.",{type:"error"})}i()&&await D()}}const oe=e=>K.peek().find(t=>t.key===e);function xe(e){const t=oe(e);if(!t)return[];const s=J(t.key);return[{header:s.path},{label:"Open the page",icon:"external-link",disabled:!s.page,action:()=>window.open(s.path,"_blank","noopener")},{label:"Copy key",icon:"copy",action:async()=>{try{await navigator.clipboard.writeText(t.key),E.toast("Key copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}},...s.page?[{label:"Copy address",icon:"link",action:async()=>{try{await navigator.clipboard.writeText(new URL(s.path,location.origin).href),E.toast("Address copied.",{type:"success"})}catch{E.toast("Could not copy - your browser blocked the clipboard.",{type:"warning"})}}}]:[]]}n.querySelector(".stx-problems").innerHTML=ze;const b=n.querySelector(".stx-list");b.innerHTML=Ne;const V=E.tabs(n.querySelector(".stx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),re=new URLSearchParams(location.hash.split("?")[1]||"").get("tab");B.includes(re)&&V.activate(B.indexOf(re));const Ce=M.applyBindings(we,n,{methods:{save:N,discard:ke,sendTest:Ee,refreshCache:D,clearCache:Se,toggleCache:Me,pickBrandImage:async e=>{const t=await Ke({title:"Choose a branding image",current:a[e].peek()});t&&i()&&(a[e].value=t)},clearBrandImage:e=>{a[e].value=""},goTab:e=>{const t=B.indexOf(e);t>=0&&V.activate(t)}}});r(()=>Ce.dispose());for(const e of n.querySelectorAll("[data-brand-icon]")){const t=e.dataset.brandIcon,s=Fe("Choose an icon",a[t].peek());s.input.id=`stx-${t}`,s.input.classList.add("form-input");const d=()=>{a[t].value=s.input.value};s.input.addEventListener("input",d),r(()=>s.input.removeEventListener("input",d)),r(M.effect(()=>{s.input.value=a[t].value})),e.appendChild(s.el)}r(Ae(n,{position:"bottom"}));const Te=e=>{const t=e.target.closest("[data-go]");if(!t)return;const s=B.indexOf(t.dataset.go);s>=0&&V.activate(s)};n.querySelector(".stx-problems").addEventListener("click",Te);const Y=n.querySelector("#stx-admin-home");Ve(Y,je(a.adminHome.peek())).then(()=>{i()&&(Y.value=a.adminHome.peek(),q.value=!0)}).catch(()=>{});const Le=E.contextMenu(b,{cursor:"glyph",match:".stx-row",inherit:!1,density:"compact",items:e=>xe(e.dataset.id)});r(()=>Le?.destroy?.());const ie=e=>{const t=oe(e.dataset.id),s=t&&J(t.key);s?.page?window.open(s.path,"_blank","noopener"):G(e)},ce=e=>{const t=e.target.closest(".stx-row");if(!t)return;const s=e.target.closest(".stx-kebab");if(s){G(s);return}ie(t)},le=e=>{const t=e.target.closest(".stx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),G(t)):e.key==="Enter"&&e.target===t&&ie(t))};b.addEventListener("click",ce),b.addEventListener("keydown",le),r(()=>{b.removeEventListener("click",ce),b.removeEventListener("keydown",le)}),fe(c,{id:"settings-view-site",icon:"external-link",title:"View site",onClick:()=>window.open("/","_blank","noopener")}),fe(c,{id:"settings-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>N()});const ue=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),N())};document.addEventListener("keydown",ue,!0),r(()=>document.removeEventListener("keydown",ue,!0));const de=()=>{if(x.peek())try{S.set(y,{form:He(X()),base:U.peek(),at:new Date().toISOString()})}catch{}},pe=e=>{x.peek()&&(de(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",pe),r(()=>window.removeEventListener("beforeunload",pe)),f={dirty:()=>x.peek(),dispose(){w=!0,de(),l.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(n),D();let h=null;try{h=S.get(y)}catch{}if(h?.form){try{S.remove?S.remove(y):S.set(y,null)}catch{}const e=h.base&&h.base!==U.peek(),t=h.at?` (${We(h.at)})`:"",s=e?`You left unsaved settings${t}, but the saved settings have changed since. Restore your version anyway?`:`You left unsaved settings${t}. Restore them?`;await E.confirm(s)&&i()&&(ne($e(v.peek(),h.form)),q.peek()&&(Y.value=a.adminHome.peek()))}}};
@@ -1241,7 +1241,7 @@ The four Tools below were plugins until 0.67.0 and are now part of the CMS. They
1241
1241
  - Admin: **Content > Chats** (`#/launchers/chats`, `#/launchers/chats/:id`) - the inbox, waiting first, the live thread (3s poll), replies with per-chat drafts, end/delete/email in a context menu, Available switch, settings cog; sidebar badge `/api/chats/_count` (live while someone waits, red after 5 minutes). **Chats > Knowledge** (`#/launchers/knowledge`) - entries with an editor slideover (question, other ways of asking, keywords, Markdown answer, up to five buttons, on/off), Try the bot with scores, and the Unanswered list (Make an entry, add to the closest entry, dismiss). Visitor panel `public/js/launcher-chat.mjs` `mountChat(container, {launcherId, title, chat})` + `public/css/launcher-chat.css`, domma-reactive.
1242
1242
  - Permission `chats` (`read`, `reply`, `manage`) in the Tools group; Admin is granted it once. All of it is behind the Launchers switch.
1243
1243
  - AI Assist (unreleased): the paid `ai-assist` Tool (Pro plan) calls `hooks.enableAiAssist()` (`services/aiAssist.js`, paid + closedSource only, off when the Tool is disabled). Without it `aiAvailable()` is false (chat config says `ai: false`, nothing is asked) and the admin assistant is unavailable (`requestAdminAnswer` 403). `GET /api/launchers/items` says `aiAssist`, and the launcher editor notes under AI answers when it is off. The Manager checks the `ai-assist` licence (no longer the Site Builder's).
1244
- - Della's AI answers (unreleased; Pro plan, hosted sites): when the matcher says `none`, `services/chat/ai.js` `aiAnswer()` asks the Manager (`MANAGER_URL` + `FLEET_TOKEN`, `POST /api/fleet/launcher-chat`; on dcm the in-process registry `Symbol.for('domma.launcher-chat')`) with the site's name, `assistantBrief()` (site.json `assistant.context`/`rules` from Site Settings > General > AI assistant, plus the launcher's `chat.aiContext`/`aiRules`), the enabled non-sample Knowledge (most used first, 16,000 characters), the last 10 visitor/bot messages and the question. A non-empty answer is stored as a bot message with `ai: true` (`misses` reset); empty or refused falls back to the usual "do not know". The question is still logged as unanswered. A 403 (no licence) backs off 10 minutes, a 429 (month used) 30 minutes, anything else 1 minute. Per launcher `chat.ai` (default on), `chat.aiUseSite` (default on; off = the launcher's own context only - the site's rules always apply), `chat.aiMaxPerChat` (20; `aiCount` on the session); the default bot name is now Della. A character's chat is called by the character's name, or by `chat.characterName` when set (admin: **Call her** under Use Della) - `characterChat()` in `public/js/characters.mjs` - so Della can be "Dash" on one launcher with her own artwork. Packs in `CHARACTERS`: dot, daisy, della, dash (Job Board) and remy (health care, Regimen; unreleased), each a 3x2 atlas in `public/images/characters/<id>-poses.png`. `aiContext`/`aiRules` never reach the page (`publicLauncher`). `/api/chat/config` says `ai` so the panel can say Della is an AI assistant. Manager side: `plugins/site-manager/services/launcherChatRoutes.js` (fleet token, the `ai-site-builder` licence, 2,000 answers per site per month counting "do not know", 4 at once) and `tools/launcher-chat` (Claude Haiku 5.5, low effort; fixed cached system prompt, then the owner's context and rules as a second system block; the visitor's words only in the user message; `LAUNCHER_CHAT_ANTHROPIC_KEY` read by the job alone).
1244
+ - Della's AI answers (unreleased; Pro plan, hosted sites): when the matcher says `none`, `services/chat/ai.js` `aiAnswer()` asks the Manager (`MANAGER_URL` + `FLEET_TOKEN`, `POST /api/fleet/launcher-chat`; on dcm the in-process registry `Symbol.for('domma.launcher-chat')`) with the site's name, `assistantBrief()` (site.json `assistant.context`/`rules` from Site Settings > General > AI assistant, plus the launcher's `chat.aiContext`/`aiRules`), the enabled non-sample Knowledge (most used first, 48,000 characters), the last 10 visitor/bot messages and the question. A non-empty answer is stored as a bot message with `ai: true` (`misses` reset); empty or refused falls back to the usual "do not know". The question is still logged as unanswered. A 403 (no licence) backs off 10 minutes, a 429 (month used) 30 minutes, anything else 1 minute. Per launcher `chat.ai` (default on), `chat.aiUseSite` (default on; off = the launcher's own context only - the site's rules always apply), `chat.aiMaxPerChat` (20; `aiCount` on the session); the default bot name is now Della. A character's chat is called by the character's name, or by `chat.characterName` when set (admin: **Call her** under Use Della) - `characterChat()` in `public/js/characters.mjs` - so Della can be "Dash" on one launcher with her own artwork. Packs in `CHARACTERS`: dot, daisy, della, dash (Job Board) and remy (health care, Regimen; unreleased), each a 3x2 atlas in `public/images/characters/<id>-poses.png`. `aiContext`/`aiRules` never reach the page (`publicLauncher`). `/api/chat/config` says `ai` so the panel can say Della is an AI assistant. Manager side: `plugins/site-manager/services/launcherChatRoutes.js` (fleet token, the `ai-site-builder` licence, 2,000 answers per site per month counting "do not know", 4 at once) and `tools/launcher-chat` (Claude Haiku 5.5, low effort; fixed cached system prompt, then the owner's context and rules as a second system block; the visitor's words only in the user message; `LAUNCHER_CHAT_ANTHROPIC_KEY` read by the job alone).
1245
1245
  - Saved chats (unreleased): preset `chat-saved` (in `CHAT_PRESET_SLUGS`, `chats.manage` through the generic API, kept out of site repos) - a copy of a chat with `note`, `outcome` (to look at / looking into it / done), visitor, page, dates, who saved it, `transcript` (plain text) and `messages`. `POST /api/chats/:id/save` (reply), `GET /api/chats/saved` and `/saved/:sid` (read), `PUT /saved/:sid` (reply; note, outcome), `DELETE /saved/:sid` (manage); at most 2,000 per site. Chats inbox: a **Saved** tab, the context-menu item **Save for a closer look…**, and an outcome/note bar on an open saved chat (`services/chat/saved.js`, `arrangeSaved()`).
1246
1246
  - Visitor panel look (unreleased): bot and staff avatars, runs of messages grouped (name on the first, avatar on the last), gradient visitor bubbles, soft chips for links and choices, a rounded composer with the send button inside, messages easing in (still for reduced motion), and in a launcher panel the bot's avatar (with a dot while someone answers) and the status under the title. Panel 400 x 600. Per-chat branding: `chat.accent` / `chat.accentText` (a theme token or hex, `launcherColour`) and `chat.avatar` (a site address only, `launcherAvatar()`), in the page's chat block and `/api/chat/config`; the panel sets `--chat-accent` / `--chat-accent-text` on itself (`launcherChatAccentCss()`: a hex accent with no text colour gets black or white by contrast, a token its `--dm-<token>-text`), and the bot's picture replaces its initial in the heading, the typing row and its messages.
1247
1247
  - Chat window and extras (unreleased): `chat.size` sm/md/lg/custom + `width`/`height` (`launcherChatBox()`; desktop only, clamped 300-720 x 380-900 and to the window), `chat.resizable` (a grip in the corner opposite the disc; size kept per launcher in the browser, `launcher-chat-size:<id>`, double-click resets), `chat.starters` (up to 4 buttons under the greeting; a tap within 1.7s of opening waits out the anti-bot window), `chat.personButton` below/header (an icon with a tooltip before the close button), greeting placeholders `{greeting}` `{timeofday}` `{day}` `{date}` `{time}` `{botname}` `{site}`, `chat.times` time/datetime/none on each message (`fillGreeting()`, the visitor's clock, text only), and `chat.keepDays` (0 = the site's `retentionDays`; the hourly tidy-up reads each launcher's).
@@ -764,6 +764,32 @@ nothing was stored (an end-form set not to record) - treat that as not sent. An
764
764
  `meta.updatedAt` with `meta.createdAt` if the answers must be as sent. When the person's data is erased, use
765
765
  `removeFormEntry`, and `formEntriesBy(form, userId)` for the entries they sent but your plugin never used. Feature-detect an older core: `import('../../server/services/formContext.js').catch(() => null)`.
766
766
 
767
+ ## AI Assist: listing your AI chats
768
+
769
+ A Tool with its own AI chats (the Site Builder's conversations, the Tool Builder's builds) can list them on
770
+ **AI Assist › Builders**, so a site with AI Assist has every AI chat in one place. Declare it in `plugin.json`:
771
+
772
+ ```json
773
+ "admin": {
774
+ "aiAssist": {
775
+ "label": "Site Builder",
776
+ "url": "#/plugins/ai-site-builder",
777
+ "list": "/api/plugins/ai-site-builder/conversations",
778
+ "permission": "ai-builder",
779
+ "character": "dot"
780
+ }
781
+ }
782
+ ```
783
+
784
+ - `url` must be your own screen (`#/plugins/<name>...`) and `list` your own API (`/api/plugins/<name>/...`, no
785
+ query); anything else is skipped at load with a warning.
786
+ - The tab shows your entry only to people holding `permission` (the resource or any of its actions) whose admin
787
+ scope covers `url`, and reads `list` with **their** token - your route decides what each person sees.
788
+ - `list` answers `{items: [{id, title, updatedAt, status, startedBy}]}` (`{conversations}` and `{builds}` with the
789
+ same fields, or `plugin`/`displayName` for id/title, are read too).
790
+ - A chat opens at `<url>?open=<id>`: read `open` from `location.hash` when your view mounts and open that chat.
791
+ - Older engines ignore the block, so it is safe to ship before the engine has it.
792
+
767
793
  ## Dashboard widgets
768
794
 
769
795
  With **Dashboard Pro**, admins build their own Dashboard from widgets the Tools offer. A widget ships
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.59.0",
3
+ "version": "1.61.0",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -3,9 +3,22 @@ import {authenticate as defaultAuthenticate} from '../../middleware/auth.js';
3
3
  import {getConfig} from '../../config.js';
4
4
  import {siteAssistant} from '../../services/assistant.js';
5
5
  import {adminAssistantConfig, adminAssistantContext, requestAdminAnswer} from '../../services/adminAssistant.js';
6
+ import {aiAssistBuildersFor, chatsHome, isAiAssist} from '../../services/aiAssist.js';
7
+ import {adminAccessFor} from '../../services/adminAccess.js';
8
+ import {covers} from '../../services/pluginScope.js';
9
+ import {isToolEnabled} from '../../services/tools.js';
6
10
 
7
- export async function adminAssistantRoutes(fastify, {authenticate = defaultAuthenticate, contextFor = adminAssistantContext, settings = adminAssistantConfig, answer = requestAdminAnswer} = {}) {
11
+ export async function adminAssistantRoutes(fastify, {authenticate = defaultAuthenticate, contextFor = adminAssistantContext, settings = adminAssistantConfig, answer = requestAdminAnswer,
12
+ aiAssist = isAiAssist, chatsOn = () => isToolEnabled('launchers'), accessFor = adminAccessFor} = {}) {
8
13
  const guard = {preHandler: [authenticate]};
14
+ // Whether this site has AI Assist (Pro) - the admin's screen, routes and pop-ups follow it.
15
+ // `builders`: the other Tools' AI chats this viewer may open (their own APIs still decide what is listed).
16
+ fastify.get('/ai-assist', guard, async (request) => {
17
+ const on = aiAssist() === true;
18
+ let builders = [];
19
+ if (on) { try { builders = aiAssistBuildersFor(accessFor(request.user), covers); } catch { builders = []; } }
20
+ return {on, chats: chatsOn() === true, chatsHome: chatsHome(), builders};
21
+ });
9
22
  fastify.get('/admin-assistant/config', guard, async request => {
10
23
  const cfg = settings();
11
24
  if (!cfg.enabled) return {enabled: false};
@@ -27,6 +27,7 @@ import {getMenu} from '../../services/menus.js';
27
27
  import {resolveAdminHome} from '../../services/adminHome.js';
28
28
  import {adminAccessFor} from '../../services/adminAccess.js';
29
29
  import {adminBrandFor} from '../../services/adminBrand.js';
30
+ import {adminThemePresentation, loadThemeConfig} from '../../services/themeSettings.js';
30
31
  import {seesNotificationsScreen} from '../../services/adminPortal.js';
31
32
  import {getAdminPortal} from '../../services/plugins.js';
32
33
  import {authenticate, checkVisibility} from '../../middleware/auth.js';
@@ -80,7 +81,9 @@ export async function authRoutes(fastify) {
80
81
  fastify.get('/auth/setup-status', async () => {
81
82
  const count = await countUsers();
82
83
  const site = getConfig('site') || {};
83
- return {needsSetup: count === 0, siteTitle: String(site.title || ''), adminBrand: adminBrandFor(site), resetByEmail: isSmtpConfigured(site.smtp),
84
+ const theme = await loadThemeConfig();
85
+ return {needsSetup: count === 0, siteTitle: String(site.title || ''), adminBrand: adminBrandFor(site),
86
+ adminTheme: adminThemePresentation(theme.adminTheme, theme), resetByEmail: isSmtpConfigured(site.smtp),
84
87
  resetExpiresIn: resetLifetime().text};
85
88
  });
86
89
 
@@ -20,11 +20,10 @@ import {
20
20
  requirePermission as defaultRequirePermission
21
21
  } from '../../middleware/auth.js';
22
22
  import {
23
- compileCustomThemeCss,
23
+ adminThemePresentation,
24
24
  compileOverrideCss,
25
25
  getThemeTokenMap,
26
26
  listCustomThemes,
27
- resolveThemeClasses,
28
27
  listThemeIds,
29
28
  listThemeTokens,
30
29
  loadThemeConfig,
@@ -121,10 +120,7 @@ export async function themeRoutes(fastify, opts = {}) {
121
120
  if (reply.sent) return reply;
122
121
  }
123
122
  const id = asked || saved;
124
- const {dommaTheme, customClass} = resolveThemeClasses(id, cfg);
125
- return {theme: id, dommaTheme, customClass, css: customClass ? compileCustomThemeCss([id]) : '',
126
- font: {family: cfg.font?.adminFamily || '', stylesheet: cfg.font?.stylesheet || ''},
127
- sidebar: cfg.adminSidebar !== false};
123
+ return adminThemePresentation(id, cfg);
128
124
  });
129
125
 
130
126
  /*
package/server/server.js CHANGED
@@ -778,6 +778,18 @@ try {
778
778
  (await import('./services/passwordReset.js')).registerPasswordChangeNotice({log: app.log});
779
779
 
780
780
  await registerPlugins(app);
781
+ // AI Assist (Pro) owns every chat: its screen takes the Chats entry's place, which keeps
782
+ // its spot in a saved menu. Plugins load once per process (a switch restarts it).
783
+ {
784
+ const {isAiAssist} = await import('./services/aiAssist.js');
785
+ if (isAiAssist()) {
786
+ const url = isToolEnabled('launchers') ? '#/ai-assist/chats' : '#/ai-assist/settings';
787
+ // Under Data by default; an admin's own placement in the menu still wins.
788
+ registerSidebarItem({folder: 'data', item: {source: 'Built in', text: 'AI Assist', url, icon: 'sparkles', permission: isToolEnabled('launchers') ? 'chats' : 'settings',
789
+ ...(isToolEnabled('launchers') && {countUrl: '/api/chats/_count'})}});
790
+ hideSidebarUrl('#/launchers/chats', url);
791
+ }
792
+ }
781
793
  // After the plugins' onRequest hooks - see serve() in services/adminAssets.js.
782
794
  adminAssets.serve();
783
795