domma-cms 1.38.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.39.0] - 2026-11-06
4
+
5
+ - **Self-hosted sites buy Tools inside their admin.** On a site with no manager, Marketplace > Browse reads the Domma store: **Buy…** opens the payment page in a new tab and the Tool installs itself once paid. Bought outright - it keeps working for good - with a term of updates; **Renew…** buys another. One licence per site address. The payment claim and licence keys stay on the server in `config/store.json` (kept out of git); `server.json` `storeUrl` (or `DOMMA_STORE_URL`) points the store elsewhere, and `false` switches it off. See `server/services/storeClient.js`.
6
+ - **Enter licence key…** on a store Tool takes a key bought on the public Marketplace page, and **Connect to Domma** links the site to the email it bought with, so every licence bought for its address arrives by itself.
7
+ - A Tool that comes free with a purchase (the MongoDB Adapter with Email and Data Transfer) installs beside it.
8
+
3
9
  ## [1.38.0] - 2026-11-06
4
10
 
5
11
  - **One leaderboards hub for every Game.** `[games-leaderboards /]` now lives in the shared Games library (`plugins/_lib/games/hub.js` and `public/games/hub.js`), so any Game with a leaderboard can join it without a change here: it shows a group for every Game the site has, in the order `games="..."` names them or else by name. Its styles moved into the shared Games stylesheet. For Hangman, Anagram, Group Four, Jigsaw, Sliding Puzzle, Memory Pairs, Timeline, Higher or Lower, Picture Reveal, Treasure Hunt and Map Guess, which join the four first Games in the hub.
package/CLAUDE.md CHANGED
@@ -193,6 +193,15 @@ copy is touched, carries `data/` and `.entitlement.json` across, and restores th
193
193
  any failure - "neither version installed" is the one state it must never produce. Versions compare
194
194
  numerically (1.10.0 > 1.2.0). Unsigned installs and downgrades each need their own explicit flag.
195
195
 
196
+ **Self-hosted sites buy from the Domma store - `server/services/storeClient.js`.** A site with no manager (no
197
+ `MANAGER_URL`/`FLEET_TOKEN`) and no wildcard owner entitlement reads Browse from the store (`server.json` `storeUrl`,
198
+ `DOMMA_STORE_URL`; default the manager's `site-manager/store`), not the fleet catalogue. `routes/api/plugin-marketplace.js`
199
+ `buy` starts a checkout and keeps the CLAIM secret in `config/store.json` (0600, gitignored, with the licence keys) -
200
+ the browser only ever gets the payment URL; `claim` swaps it for the key once paid and installs through
201
+ `installPlugin` with the envelope's entitlement. Bought outright (perpetual): the entitlement's `supportExpiresAt`
202
+ is the licence's and the store refuses a NEWER version after it (`mayDownload` on the manager); one licence per site
203
+ address (`self:<host>`), so localhost/IP/.local addresses are refused there.
204
+
196
205
  **Signed-only sites (hosted) - `server/services/codePolicy.js`.** `signedOnly()` is true when the environment has
197
206
  `DOMMA_SIGNED_ONLY=1` (the Manager sets it on sites it forks, after the site's .env), when server.json had
198
207
  `requireSignedPlugins: true` at boot, or when it has it now. On such a site the hosted owner is level 0, and
package/admin/js/api.js CHANGED
@@ -1 +1 @@
1
- import{claimDrafts as $}from"./lib/draft-owner.js";import{loginHashFor as O}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function y(e){S.set("auth_token",e)}function f(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw f(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return y(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&y(e),o&&S.set("auth_refresh_token",o),n&&($(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=O(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),f()}export{t as apiRequest,g as refreshAccessToken,a as getToken,f as clearAuth};
1
+ import{claimDrafts as O}from"./lib/draft-owner.js";import{loginHashFor as $}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),folders:()=>t("/media/_folders",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"}),buy:e=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e})}),claim:e=>t("/plugins/marketplace/claim",{method:"POST",body:JSON.stringify({id:e})}),enterKey:(e,o)=>t("/plugins/marketplace/key",{method:"POST",body:JSON.stringify({slug:e,key:o})}),connect:e=>t("/plugins/marketplace/connect",{method:"POST",body:JSON.stringify({email:e})}),connectCheck:()=>t("/plugins/marketplace/connect/check",{method:"POST",body:"{}"}),disconnect:()=>t("/plugins/marketplace/connect",{method:"DELETE"}),dropPurchase:e=>t(`/plugins/marketplace/purchases/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&(O(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=$(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
@@ -1,2 +1,2 @@
1
- export const FILTERS=["all","on","off","attention"],BROWSE_FILTERS=["all","installed","available","updates"],BLOCKING=new Set(["expired","unlicensed"]);const m={grace:{text:"Renew",tone:"warn",title:"The rental term has ended - still running during the grace period"},"support-ended":{text:"Support ended",tone:"muted",title:"Owned outright and still running, but no longer entitled to updates"},expired:{text:"Expired",tone:"danger",title:"The rental term and grace period have ended - this plugin is not running"},unlicensed:{text:"Unlicensed",tone:"danger",title:"No valid entitlement for this site - this plugin is not running"}};export function compareVersions(e,s){const r=o=>String(o??"").split(".").map(a=>parseInt(a,10)||0),t=r(e),n=r(s);for(let o=0;o<Math.max(t.length,n.length);o++){const a=(t[o]??0)-(n[o]??0);if(a)return a>0?1:-1}return 0}export function pluginStatus(e){return e.core?{key:"core",text:"Built in",tone:"info",running:!0}:e.enabled&&BLOCKING.has(e.entitlement)?{key:"blocked",text:"Not running",tone:"danger",running:!1}:e.enabled&&e.supersededBy?{key:"replaced",text:"Replaced",tone:"muted",running:!1}:e.enabled&&e.blockedBy?{key:"blocked",text:`Needs ${e.blockedBy}`,tone:"danger",running:!1}:e.enabled?{key:"on",text:"On",tone:"ok",running:!0}:{key:"off",text:"Off",tone:"muted",running:!1}}export function updateFor(e,s){const r=s?.get?.(e.name);return r&&compareVersions(r,e.version)>0?r:""}export function needsAttention(e,s){return pluginStatus(e).key==="blocked"||e.entitlement==="grace"||!!updateFor(e,s)}export function fmtReleased(e){if(!e||!/^\d{4}-\d{2}-\d{2}/.test(String(e)))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const r=t=>String(t).padStart(2,"0");return`${r(s.getDate())}.${r(s.getMonth()+1)}.${s.getFullYear()}`}export function arrangePlugins(e,{filter:s="all",query:r="",latest:t=new Map}={}){const n=String(r).trim().toLowerCase(),o={all:()=>!0,on:i=>pluginStatus(i).running,off:i=>!pluginStatus(i).running,attention:i=>needsAttention(i,t)}[s]||(()=>!0),a=i=>needsAttention(i,t)?0:pluginStatus(i).running?1:2;return[...e||[]].filter(o).filter(i=>!n||[i.name,i.displayName,i.description,i.author].some(c=>String(c||"").toLowerCase().includes(n))).sort((i,c)=>a(i)-a(c)||String(i.displayName||i.name).localeCompare(String(c.displayName||c.name)))}export function pluginRow(e,s=new Map){const r=pluginStatus(e),t=m[e.entitlement]||null,n=updateFor(e,s),o=fmtReleased(e.date);return{name:e.name,displayName:e.displayName||e.name,icon:e.icon||"package",meta:[`v${e.version}`,e.author?`by ${e.author}`:"",o?`released ${o}`:"",e.supersededBy?`replaced by ${e.supersededBy}`:"",e.locked?"locked by your manager":""].filter(Boolean).join(" \xB7 "),description:e.description||"",statusText:r.text,statusCls:`is-${r.tone}`,licensed:e.closedSource===!0,entText:t?.text||"",entCls:t?`is-${t.tone}`:"",entTitle:t?.title||"",update:n,updateText:n?`Update to ${n}`:"",configurable:settingsFields(e).length>0,locked:e.locked===!0,rowCls:[r.running?"":"is-off",needsAttention(e,s)?"is-attention":""].filter(Boolean).join(" ")}}export function formatPrice(e){if(e?.tier!=="paid")return"Free";const s=e.terms?.managed?.monthly;return s==null||!Number.isFinite(Number(s))?"Paid":`${e.terms?.currency==="GBP"?"\xA3":`${e.terms?.currency||""} `}${(Number(s)/100).toFixed(2)}/mo`}export function catalogueAction(e){return e.installed&&e.updatable&&e.entitled?e.needsCms?"needs-cms":"update":e.installed?"installed":e.entitled?e.needsCms?"needs-cms":"install":e.buyUrl?"buy":"locked"}export function arrangeCatalogue(e,{filter:s="all",query:r=""}={}){const t=String(r).trim().toLowerCase(),n={all:()=>!0,installed:a=>a.installed,available:a=>catalogueAction(a)==="install",updates:a=>catalogueAction(a)==="update"}[s]||(()=>!0),o={update:0,install:1,buy:2,installed:3,"needs-cms":4,locked:5};return[...e||[]].filter(n).filter(a=>!t||[a.slug,a.displayName,a.description].some(i=>String(i||"").toLowerCase().includes(t))).sort((a,i)=>o[catalogueAction(a)]-o[catalogueAction(i)]||String(a.displayName||a.slug).localeCompare(String(i.displayName||i.slug)))}export function catalogueRow(e){const s=catalogueAction(e),r=e.entitled&&e.tier==="paid";return{slug:e.slug,displayName:e.displayName||e.slug,icon:e.icon||"package",meta:[e.installed&&e.installedVersion&&e.installedVersion!==e.version?`v${e.installedVersion} \u2192 v${e.version}`:`v${e.version}`,e.installed?"installed":"",s==="needs-cms"&&e.minCmsVersion?`needs Domma CMS ${String(e.minCmsVersion).replace(/^[^\d]+/,"")} or later`:""].filter(Boolean).join(" \xB7 "),description:e.description||"",price:formatPrice(e),licText:r?e.licenceStatus==="grace"?"Renew":"Licensed":"",licCls:e.licenceStatus==="grace"?"is-warn":"is-ok",action:s,actionText:{update:"Update",install:"Install",installed:"Installed","needs-cms":"Needs newer CMS",buy:e.licenceStatus==="expired"?"Renew\u2026":"Buy\u2026",locked:e.licenceStatus==="expired"?"Licence expired":"Not licensed"}[s],rowCls:s==="locked"||s==="needs-cms"?"is-off":s==="update"?"is-attention":""}}export const isSecretKey=e=>/pass(word)?|secret|token|api[-_]?key|private|credential|uri$|dsn/i.test(String(e));export function labelFor(e){const s=String(e).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return s?s[0].toUpperCase()+s.slice(1):String(e)}export function settingsFields(e){const s=e?.settings||{},r={...e?.effectiveSettings||{},...s};return Array.isArray(e?.settingsSchema)&&e.settingsSchema.length?e.settingsSchema.filter(t=>t&&t.key).map(t=>{const n=t.type==="select"?"select":t.type==="number"?"number":t.type==="boolean"||t.type==="checkbox"?"checkbox":t.type==="textarea"?"textarea":"text",o=r[t.key]??t.default??(n==="checkbox"?!1:"");return{key:t.key,label:t.label||labelFor(t.key),type:n,value:n==="checkbox"?o===!0:String(o??""),options:(t.options||[]).map(a=>typeof a=="object"?{value:String(a.value),label:String(a.label??a.value)}:{value:String(a),label:String(a)}),min:t.min,max:t.max,help:t.help||"",secret:t.secret===!0||isSecretKey(t.key)}}):Object.entries(r).map(([t,n])=>{const o=isSecretKey(t);if(typeof n=="boolean")return{key:t,label:labelFor(t),type:"checkbox",value:n,secret:o};if(typeof n=="number")return{key:t,label:labelFor(t),type:"number",value:String(n),secret:o};if(n!==null&&typeof n=="object")return{key:t,label:labelFor(t),type:"json",value:JSON.stringify(n,null,2),secret:o};const a=String(n??"");return{key:t,label:labelFor(t),type:a.includes(`
2
- `)||a.length>80?"textarea":"text",value:a,secret:o}})}export function readSettings(e,s){const r={},t={};for(const n of e){const o=s[n.key];if(n.type==="checkbox"){!!o!=!!n.value&&(t[n.key]=!!o);continue}const a=String(o??"");if(a!==String(n.value))if(n.type==="number"){const i=Number(a);if(a.trim()===""||!Number.isFinite(i)){r[n.key]="A number, please.";continue}if(n.min!=null&&i<n.min){r[n.key]=`At least ${n.min}.`;continue}if(n.max!=null&&i>n.max){r[n.key]=`At most ${n.max}.`;continue}t[n.key]=i}else if(n.type==="json")try{t[n.key]=JSON.parse(a)}catch{r[n.key]="Not valid JSON."}else t[n.key]=a}return{errors:r,changed:t}}export function slugifyPlugin(e){return String(e??"").toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/g,"").slice(0,40).replace(/-+$/,"")}export function checkScaffold(e,s=[]){const r=a=>String(e?.[a]??"").trim(),t={displayName:r("displayName"),slug:r("slug"),description:r("description"),author:r("author"),icon:r("icon")||"box"},n={},o=/[<>"\\]|\*\//;t.displayName?t.displayName.length>60&&(n.displayName="60 characters at most."):n.displayName="A plugin needs a name.",/^[a-z][a-z0-9-]{1,39}$/.test(t.slug)?s.includes(t.slug)&&(n.slug=`"${t.slug}" is already installed.`):n.slug="2-40 characters: lowercase letters, digits and hyphens, starting with a letter.",t.description.length>300&&(n.description="300 characters at most."),t.author.length>80&&(n.author="80 characters at most."),/^[a-z][a-z0-9-]{0,39}$/.test(t.icon)||(n.icon="A lowercase icon name (letters, digits, hyphens).");for(const a of["displayName","description","author"])!n[a]&&o.test(t[a])&&(n[a]='No <, >, ", backslash or */.');return{errors:n,payload:t}}export function planLines(e){const s=[];for(const r of e?.cascaded||[])s.push(`${r.displayName||r.name} is switched ${r.enabled?"on":"off"} too - ${r.enabled?`${r.becauseName||r.because} needs it`:`it needs ${r.becauseName||r.because}`}.`);for(const r of e?.losses||[])s.push(`${r.displayName||r.name} stays on without ${r.toolName||r.tool}${r.reason?`, but loses: ${r.reason.replace(/\.$/,"")}`:""}.`);return s}export function dependencyRows(e,{plugins:s=[],tools:r=[],catalogue:t=[]}={}){const n={on:["On","is-ok"],off:["Off","is-muted"],missing:["Not installed","is-warn"]},o=l=>{const u=r.find(d=>d.name===l);if(u)return{displayName:u.displayName||l,state:u.enabled===!1?"off":"on"};const p=s.find(d=>d.name===l);return p?{displayName:p.displayName||l,state:pluginStatus(p).running?"on":"off"}:{displayName:t.find(d=>d.slug===l)?.displayName||l,state:"missing"}},a=(l,u="")=>{const{displayName:p,state:g}=o(l),[d,y]=n[g];return{name:l,displayName:p,reason:u,state:g,stateText:d,stateCls:y}},i=Array.isArray(e?.requires)?e.requires.filter(l=>typeof l=="string"&&l):[],c=e?.uses,f=Array.isArray(c)?c.filter(l=>typeof l=="string").map(l=>[l,""]):Object.entries(c&&typeof c=="object"?c:{}).map(([l,u])=>[l,typeof u=="string"?u:""]);return{needs:i.map(l=>a(l)),worksWith:f.map(([l,u])=>a(l,u))}}export function dependencyText(e){return(e||[]).map(s=>`${s.displayName} (${s.stateText.toLowerCase()})`).join(", ")}
1
+ export const FILTERS=["all","on","off","attention"],BROWSE_FILTERS=["all","installed","available","updates"],BLOCKING=new Set(["expired","unlicensed"]);const x={grace:{text:"Renew",tone:"warn",title:"The rental term has ended - still running during the grace period"},"support-ended":{text:"Support ended",tone:"muted",title:"Owned outright and still running, but no longer entitled to updates"},expired:{text:"Expired",tone:"danger",title:"The rental term and grace period have ended - this plugin is not running"},unlicensed:{text:"Unlicensed",tone:"danger",title:"No valid entitlement for this site - this plugin is not running"}};export function compareVersions(e,r){const t=a=>String(a??"").split(".").map(o=>parseInt(o,10)||0),n=t(e),s=t(r);for(let a=0;a<Math.max(n.length,s.length);a++){const o=(n[a]??0)-(s[a]??0);if(o)return o>0?1:-1}return 0}export function pluginStatus(e){return e.core?{key:"core",text:"Built in",tone:"info",running:!0}:e.enabled&&BLOCKING.has(e.entitlement)?{key:"blocked",text:"Not running",tone:"danger",running:!1}:e.enabled&&e.supersededBy?{key:"replaced",text:"Replaced",tone:"muted",running:!1}:e.enabled&&e.blockedBy?{key:"blocked",text:`Needs ${e.blockedBy}`,tone:"danger",running:!1}:e.enabled?{key:"on",text:"On",tone:"ok",running:!0}:{key:"off",text:"Off",tone:"muted",running:!1}}export function updateFor(e,r){const t=r?.get?.(e.name);return t&&compareVersions(t,e.version)>0?t:""}export function needsAttention(e,r){return pluginStatus(e).key==="blocked"||e.entitlement==="grace"||!!updateFor(e,r)}export function fmtReleased(e){if(!e||!/^\d{4}-\d{2}-\d{2}/.test(String(e)))return"";const r=new Date(e);if(Number.isNaN(r.getTime()))return"";const t=n=>String(n).padStart(2,"0");return`${t(r.getDate())}.${t(r.getMonth()+1)}.${r.getFullYear()}`}export function arrangePlugins(e,{filter:r="all",query:t="",latest:n=new Map}={}){const s=String(t).trim().toLowerCase(),a={all:()=>!0,on:i=>pluginStatus(i).running,off:i=>!pluginStatus(i).running,attention:i=>needsAttention(i,n)}[r]||(()=>!0),o=i=>needsAttention(i,n)?0:pluginStatus(i).running?1:2;return[...e||[]].filter(a).filter(i=>!s||[i.name,i.displayName,i.description,i.author].some(c=>String(c||"").toLowerCase().includes(s))).sort((i,c)=>o(i)-o(c)||String(i.displayName||i.name).localeCompare(String(c.displayName||c.name)))}export function pluginRow(e,r=new Map){const t=pluginStatus(e),n=x[e.entitlement]||null,s=updateFor(e,r),a=fmtReleased(e.date);return{name:e.name,displayName:e.displayName||e.name,icon:e.icon||"package",meta:[`v${e.version}`,e.author?`by ${e.author}`:"",a?`released ${a}`:"",e.supersededBy?`replaced by ${e.supersededBy}`:"",e.locked?"locked by your manager":""].filter(Boolean).join(" \xB7 "),description:e.description||"",statusText:t.text,statusCls:`is-${t.tone}`,licensed:e.closedSource===!0,entText:n?.text||"",entCls:n?`is-${n.tone}`:"",entTitle:n?.title||"",update:s,updateText:s?`Update to ${s}`:"",configurable:settingsFields(e).length>0,locked:e.locked===!0,rowCls:[t.running?"":"is-off",needsAttention(e,r)?"is-attention":""].filter(Boolean).join(" ")}}export function formatMoney(e,r="GBP"){const t={GBP:"\xA3",USD:"$",EUR:"\u20AC"}[String(r||"GBP").toUpperCase()],n=(Number(e)/100).toFixed(2);return t?`${t}${n}`:`${n} ${r}`}export function formatPrice(e){if(e?.tier!=="paid")return"Free";if(e.store)return e.owned?e.canRenew&&Number.isFinite(Number(e.renewal))&&e.renewal>0?`Renew ${formatMoney(e.renewal,e.currency)}`:"Owned":e.forSale&&Number(e.price)>0?formatMoney(e.price,e.currency):"Not on sale";const r=e.terms?.managed?.monthly;return r==null||!Number.isFinite(Number(r))?"Paid":`${e.terms?.currency==="GBP"?"\xA3":`${e.terms?.currency||""} `}${(Number(r)/100).toFixed(2)}/mo`}export function catalogueAction(e){return e.store&&e.pending?"waiting":e.installed&&e.updatable&&e.entitled?e.needsCms?"needs-cms":"update":e.store&&e.owned&&e.updatable&&e.canRenew||e.store&&e.installed&&e.tier==="paid"&&!e.owned&&!e.licensedHere&&e.forSale?"buy":e.installed?"installed":e.entitled?e.needsCms?"needs-cms":"install":e.store?(e.owned?e.canRenew:e.forSale)?"buy":"locked":e.buyUrl?"buy":"locked"}export function arrangeCatalogue(e,{filter:r="all",query:t=""}={}){const n=String(t).trim().toLowerCase(),s={all:()=>!0,installed:o=>o.installed,available:o=>catalogueAction(o)==="install",updates:o=>catalogueAction(o)==="update"}[r]||(()=>!0),a={waiting:0,update:1,install:2,buy:3,installed:4,"needs-cms":5,locked:6};return[...e||[]].filter(s).filter(o=>!n||[o.slug,o.displayName,o.description].some(i=>String(i||"").toLowerCase().includes(n))).sort((o,i)=>a[catalogueAction(o)]-a[catalogueAction(i)]||String(o.displayName||o.slug).localeCompare(String(i.displayName||i.slug)))}function h(e,r){return{update:"Update",install:"Install",installed:"Installed","needs-cms":"Needs newer CMS",waiting:"Paid? Check\u2026",buy:(e.store?e.owned:e.licenceStatus==="expired")?"Renew\u2026":"Buy\u2026",locked:e.store?e.owned?"Updates ended":"Not on sale":e.licenceStatus==="expired"?"Licence expired":"Not licensed"}[r]}function b(e){return e.tier!=="paid"?{licText:"",licCls:"is-ok"}:e.store?e.owned?e.updates?{licText:"Licensed",licCls:"is-ok"}:{licText:"Updates ended",licCls:"is-warn"}:{licText:"",licCls:"is-ok"}:e.entitled?e.licenceStatus==="grace"?{licText:"Renew",licCls:"is-warn"}:{licText:"Licensed",licCls:"is-ok"}:{licText:"",licCls:"is-ok"}}export function supportText(e,r=Date.now()){if(!e?.store||!e.owned||!e.supportEnds)return"";const t=Date.parse(e.supportEnds);if(!Number.isFinite(t))return"";const n=new Date(t).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"});return t>=r?`updates until ${n}`:`updates ended ${n}`}export function catalogueRow(e){const r=catalogueAction(e);return{slug:e.slug,displayName:e.displayName||e.slug,icon:e.icon||"package",meta:[e.installed&&e.installedVersion&&e.installedVersion!==e.version?`v${e.installedVersion} \u2192 v${e.version}`:`v${e.version}`,e.installed?"installed":"",supportText(e),e.store&&e.note?e.note:"",r==="waiting"?"waiting for payment":"",r==="needs-cms"&&e.minCmsVersion?`needs Domma CMS ${String(e.minCmsVersion).replace(/^[^\d]+/,"")} or later`:""].filter(Boolean).join(" \xB7 "),description:e.description||"",price:formatPrice(e),...b(e),action:r,actionText:h(e,r),rowCls:r==="locked"||r==="needs-cms"?"is-off":r==="update"||r==="waiting"?"is-attention":""}}export function storeBuyLines(e,{site:r="",email:t=""}={}){const n=e.displayName||e.slug;return e.owned?{title:`Renew ${n}`,lines:[`${e.renewalPeriodMonths||12} more months of updates for ${n} on ${r||"this site"}: ${formatMoney(e.renewal,e.currency)}, paid once.`,"The version you have keeps working either way.",`Payment opens in a new tab. The receipt goes to ${t||"your email address"}.`]}:{title:`Buy ${n}`,lines:[`${n} for ${r||"this site"}: ${formatMoney(e.price,e.currency)}, paid once. It is yours to keep, with ${e.supportMonths||12} months of updates - renew them later if you like.`,"One licence covers one site address.",`Payment opens in a new tab. The receipt and licence key go to ${t||"your email address"}, and ${n} installs here as soon as the payment is through.`]}}export const isSecretKey=e=>/pass(word)?|secret|token|api[-_]?key|private|credential|uri$|dsn/i.test(String(e));export function labelFor(e){const r=String(e).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return r?r[0].toUpperCase()+r.slice(1):String(e)}export function settingsFields(e){const r=e?.settings||{},t={...e?.effectiveSettings||{},...r};return Array.isArray(e?.settingsSchema)&&e.settingsSchema.length?e.settingsSchema.filter(n=>n&&n.key).map(n=>{const s=n.type==="select"?"select":n.type==="number"?"number":n.type==="boolean"||n.type==="checkbox"?"checkbox":n.type==="textarea"?"textarea":"text",a=t[n.key]??n.default??(s==="checkbox"?!1:"");return{key:n.key,label:n.label||labelFor(n.key),type:s,value:s==="checkbox"?a===!0:String(a??""),options:(n.options||[]).map(o=>typeof o=="object"?{value:String(o.value),label:String(o.label??o.value)}:{value:String(o),label:String(o)}),min:n.min,max:n.max,help:n.help||"",secret:n.secret===!0||isSecretKey(n.key)}}):Object.entries(t).map(([n,s])=>{const a=isSecretKey(n);if(typeof s=="boolean")return{key:n,label:labelFor(n),type:"checkbox",value:s,secret:a};if(typeof s=="number")return{key:n,label:labelFor(n),type:"number",value:String(s),secret:a};if(s!==null&&typeof s=="object")return{key:n,label:labelFor(n),type:"json",value:JSON.stringify(s,null,2),secret:a};const o=String(s??"");return{key:n,label:labelFor(n),type:o.includes(`
2
+ `)||o.length>80?"textarea":"text",value:o,secret:a}})}export function readSettings(e,r){const t={},n={};for(const s of e){const a=r[s.key];if(s.type==="checkbox"){!!a!=!!s.value&&(n[s.key]=!!a);continue}const o=String(a??"");if(o!==String(s.value))if(s.type==="number"){const i=Number(o);if(o.trim()===""||!Number.isFinite(i)){t[s.key]="A number, please.";continue}if(s.min!=null&&i<s.min){t[s.key]=`At least ${s.min}.`;continue}if(s.max!=null&&i>s.max){t[s.key]=`At most ${s.max}.`;continue}n[s.key]=i}else if(s.type==="json")try{n[s.key]=JSON.parse(o)}catch{t[s.key]="Not valid JSON."}else n[s.key]=o}return{errors:t,changed:n}}export function slugifyPlugin(e){return String(e??"").toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/g,"").slice(0,40).replace(/-+$/,"")}export function checkScaffold(e,r=[]){const t=o=>String(e?.[o]??"").trim(),n={displayName:t("displayName"),slug:t("slug"),description:t("description"),author:t("author"),icon:t("icon")||"box"},s={},a=/[<>"\\]|\*\//;n.displayName?n.displayName.length>60&&(s.displayName="60 characters at most."):s.displayName="A plugin needs a name.",/^[a-z][a-z0-9-]{1,39}$/.test(n.slug)?r.includes(n.slug)&&(s.slug=`"${n.slug}" is already installed.`):s.slug="2-40 characters: lowercase letters, digits and hyphens, starting with a letter.",n.description.length>300&&(s.description="300 characters at most."),n.author.length>80&&(s.author="80 characters at most."),/^[a-z][a-z0-9-]{0,39}$/.test(n.icon)||(s.icon="A lowercase icon name (letters, digits, hyphens).");for(const o of["displayName","description","author"])!s[o]&&a.test(n[o])&&(s[o]='No <, >, ", backslash or */.');return{errors:s,payload:n}}export function planLines(e){const r=[];for(const t of e?.cascaded||[])r.push(`${t.displayName||t.name} is switched ${t.enabled?"on":"off"} too - ${t.enabled?`${t.becauseName||t.because} needs it`:`it needs ${t.becauseName||t.because}`}.`);for(const t of e?.losses||[])r.push(`${t.displayName||t.name} stays on without ${t.toolName||t.tool}${t.reason?`, but loses: ${t.reason.replace(/\.$/,"")}`:""}.`);return r}export function dependencyRows(e,{plugins:r=[],tools:t=[],catalogue:n=[]}={}){const s={on:["On","is-ok"],off:["Off","is-muted"],missing:["Not installed","is-warn"]},a=l=>{const u=t.find(d=>d.name===l);if(u)return{displayName:u.displayName||l,state:u.enabled===!1?"off":"on"};const p=r.find(d=>d.name===l);return p?{displayName:p.displayName||l,state:pluginStatus(p).running?"on":"off"}:{displayName:n.find(d=>d.slug===l)?.displayName||l,state:"missing"}},o=(l,u="")=>{const{displayName:p,state:f}=a(l),[d,y]=s[f];return{name:l,displayName:p,reason:u,state:f,stateText:d,stateCls:y}},i=Array.isArray(e?.requires)?e.requires.filter(l=>typeof l=="string"&&l):[],c=e?.uses,g=Array.isArray(c)?c.filter(l=>typeof l=="string").map(l=>[l,""]):Object.entries(c&&typeof c=="object"?c:{}).map(([l,u])=>[l,typeof u=="string"?u:""]);return{needs:i.map(l=>o(l)),worksWith:g.map(([l,u])=>o(l,u))}}export function dependencyText(e){return(e||[]).map(r=>`${r.displayName} (${r.stateText.toLowerCase()})`).join(", ")}
@@ -113,5 +113,7 @@
113
113
  .plx-actions { display: flex; align-items: center; gap: .4rem; padding-top: .6rem; border-top: 1px solid var(--dm-border); flex-wrap: wrap; }
114
114
  .plx-actions .btn { display: inline-flex; align-items: center; gap: .3rem; }
115
115
  .plx-spacer { flex: 1; }
116
+ .plx-connect { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem .6rem; padding: .5rem .7rem; border: 1px dashed var(--dm-border); border-radius: var(--dm-radius-md); }
117
+ .plx-connect .plx-note { flex: 1; min-width: 14rem; }
116
118
  @media (max-width: 640px) { .plx-main small { white-space: normal; } .plx-chips { display: none; } }
117
119
  </style>
@@ -1,4 +1,4 @@
1
- import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"../lib/plugin-chrome.js";import{SHAPES as at,whileLoading as nt}from"../lib/loading.js";import{helpPopovers as Ue}from"../lib/help-popover.js";import{onceClosed as st,openMenuAt as Re,sidebarCount as lt,viewLifetime as it}from"../lib/tool-kit.js";import{pluginAccent as je}from"../lib/plugin-accent.js";import{reportRestart as ot}from"../lib/server-restart.js";import{FILTERS as rt,arrangeCatalogue as dt,arrangePlugins as ct,catalogueAction as te,catalogueRow as ut,checkScaffold as pt,dependencyRows as bt,formatPrice as Be,fmtReleased as mt,needsAttention as ht,planLines as ft,pluginRow as vt,pluginStatus as De,readSettings as gt,settingsFields as Fe,slugifyPlugin as yt,updateFor as qe}from"../lib/plugins-arrange.js";const We=/^#\/plugins\/?(\?.*)?$/,wt="#/plugins",be="plugins.filter",ae="plugins.draft",xt=`
1
+ import{api as h,getUser as Y}from"../api.js";import{addBannerAction as ke}from"../lib/plugin-chrome.js";import{SHAPES as vt,whileLoading as wt}from"../lib/loading.js";import{helpPopovers as He}from"../lib/help-popover.js";import{onceClosed as xt,openMenuAt as Ve,sidebarCount as kt,viewLifetime as $t}from"../lib/tool-kit.js";import{pluginAccent as Ye}from"../lib/plugin-accent.js";import{reportRestart as Et}from"../lib/server-restart.js";import{FILTERS as St,arrangeCatalogue as Tt,arrangePlugins as Ct,catalogueAction as re,catalogueRow as Mt,checkScaffold as Nt,dependencyRows as It,formatPrice as ce,fmtReleased as Ot,needsAttention as At,planLines as Lt,pluginRow as Dt,pluginStatus as Je,readSettings as Ut,settingsFields as Qe,slugifyPlugin as Rt,storeBuyLines as Bt,updateFor as Ge}from"../lib/plugins-arrange.js";const Ze=/^#\/plugins\/?(\?.*)?$/,et=5e3,Ft=3e4,jt=20*6e4,Wt="#/plugins",$e="plugins.filter",de="plugins.draft",Pt=`
2
2
  <div class="plx-row" data-name="{{name}}" tabindex="0" data-bind-class="rowCls" style="--plugin-accent: {{accent}}">
3
3
  <span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
4
4
  <span class="plx-main"><strong>{{displayName}}</strong><small data-bind-text="meta"></small></span>
@@ -10,7 +10,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
10
10
  <span class="plx-chip" data-bind-class="statusCls" data-bind-text="statusText"></span>
11
11
  </span>
12
12
  <button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
13
- </div>`,kt=`
13
+ </div>`,qt=`
14
14
  <div class="plx-row" data-tool="{{name}}" tabindex="0" data-bind-class="rowCls">
15
15
  <span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
16
16
  <span class="plx-main"><strong>{{displayName}}</strong><small data-bind-text="meta"></small></span>
@@ -19,7 +19,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
19
19
  <span class="plx-chip" data-bind-class="statusCls" data-bind-text="statusText"></span>
20
20
  </span>
21
21
  <button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
22
- </div>`,$t=`
22
+ </div>`,_t=`
23
23
  <div class="plx-row" data-slug="{{slug}}" tabindex="0" data-bind-class="rowCls" style="--plugin-accent: {{accent}}">
24
24
  <span class="plx-icon" aria-hidden="true"><span data-icon="{{icon}}" data-icon-size="17"></span></span>
25
25
  <span class="plx-main"><strong>{{displayName}}</strong><small>{{meta}}</small></span>
@@ -29,12 +29,12 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
29
29
  </span>
30
30
  <button type="button" class="btn btn-sm plx-act" data-bind-class="actCls" data-bind-disabled="actDisabled" data-bind-text="actionText"></button>
31
31
  <button type="button" class="plx-kebab" aria-label="Actions for {{displayName}}" title="Actions">\u22EE</button>
32
- </div>`,Et=`
32
+ </div>`,Kt=`
33
33
  <li class="plx-dep">
34
34
  <strong data-bind-text="displayName"></strong>
35
35
  <span class="plx-chip" data-bind-class="stateCls" data-bind-text="stateText"></span>
36
36
  <small class="plx-hint" data-bind-hidden="!reason" data-bind-text="reason"></small>
37
- </li>`,d=T=>String(T??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function me(T){const m=document.createElement("template");return m.innerHTML=T.trim(),m.content.firstElementChild}const g=it(We);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(T){g.reset();const m=T.get(0).querySelector(".plx")||T.get(0),k=()=>We.test(location.hash)&&m.isConnected,L=M.observable([]),R=M.observable([]),he=M.computed(()=>R.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),h=M.observable({available:null,site:null,items:[]}),fe=M.observable(!0),ne=M.observable(""),b=M.observable("");let ve="all";try{ve=rt.includes(S.get(be))?S.get(be):"all"}catch{}const N=M.observable(ve),V=M.observable(""),j=M.observable("all"),ge=M.observable("");g.add(M.effect(()=>{const e=N.value;try{S.set(be,e)}catch{}}));const Y=M.computed(()=>new Map((h.value.items||[]).map(e=>[e.slug,e.version]))),W=e=>(h.peek().items||[]).find(t=>t.slug===e),se=M.observable([]);g.add(M.effect(()=>{const e=Y.value;se.value=ct(L.value,{filter:N.value,query:V.value,latest:e}).map(t=>({...vt(t,e),accent:je(t.name)}))}));const Pe=M.computed(()=>{const e=L.value,t=Y.value,a=e.filter(n=>De(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>ht(n,t)).length}}),J=M.computed(()=>(h.value.items||[]).filter(e=>te(e)==="update").length),ze=M.computed(()=>L.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),le=M.observable([]);g.add(M.effect(()=>{le.value=dt(h.value.items,{filter:j.value,query:ge.value}).map(e=>{const t=ut(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:je(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const _e=M.computed(()=>{const e=h.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>te(t)==="install").length,updates:J.value}}),Q=e=>L.peek().find(t=>t.name===e);async function ie(){try{const[e,t]=await nt(m.querySelector(".dm-loading-slot"),Promise.all([v.plugins.list(),v.tools.list().catch(()=>[])]),at.iconRows);if(!k())return;L.value=Array.isArray(e)?e:[],R.value=Array.isArray(t)?t:[],ne.value=""}catch(e){ne.value=`Could not load the plugins: ${e.message||e}`}finally{fe.value=!1}}async function ye(){try{const e=await v.marketplace.catalogue();if(!k())return;h.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[]}}catch{h.value={available:!1,site:null,items:[],failed:!0}}}const P=async()=>{await Promise.all([ie(),ye()]),lt(wt)};async function B(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${d(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||b.peek())return;const l=i=>a==="tool"?v.tools.update(e.name,{enabled:t,cascade:i}):v.plugins.update(e.name,{enabled:t,cascade:i});b.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let i;try{i=await l(!1)}catch(c){if(c.status!==409||!c.body?.needsConfirm)throw c;const u=ft(c.body.plan);if(b.value="",!await E.confirm(`<p>Switching ${d(e.displayName||e.name)} ${n} also means:</p><ul>${u.map(o=>`<li>${d(o)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;b.value=`Switching ${e.displayName||e.name} ${n}\u2026`,i=await l(!0)}await ot(i,{onStatus:c=>{b.value=c}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(i){E.toast(`Not switched ${n}: ${i.message||i}`,{type:"error"})}finally{b.value="",k()&&await P()}}async function D(e,{update:t=!1}={}){const a=d(e.displayName||e.slug),n=t?`<p>Update ${a} from ${d(e.installedVersion)} to ${d(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${d(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const l=await v.marketplace.install(e.slug,e.version,{update:t}),i=l?.action==="upgrade"?`${e.slug} updated${l.from?` from ${l.from}`:""} to ${l.version}.`:`${e.slug} ${l?.version??e.version} installed.`;E.toast(`${i} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(l){E.toast(l.message||"Install failed.",{type:"error"})}k()&&await P()}}function we(e){e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function xe(e,t){const n=W(e)?.tier==="paid"?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${d(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const i=(await v.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${i} Restart the server to apply.`,{type:"success",duration:6e3})}catch(l){E.toast(`Uninstall failed: ${l.message||l}`,{type:"error"})}k()&&await P()}}async function ke(e){try{await v.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const $e=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},z=m.querySelector(".plx-file");async function He(e){if(b.peek())return;b.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await v.plugins.installFile(e,t),l=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${l} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(b.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${d(n.name)} ${d(n.installedVersion||"the installed version")} is already installed. Update it to ${d(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${d(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${d(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}b.value=`Installing ${e.name}\u2026`}}finally{b.value="",k()&&await P()}}const Ee=async()=>{const e=z.files?.[0];z.value="",e&&await He(e)};z.addEventListener("change",Ee),g.add(()=>z.removeEventListener("change",Ee));const G=new Set;let U=null,Se=!1;function Me({title:e,size:t="md",panel:a,model:n,methods:l,dirty:i=()=>!1,form:c=null,cleanup:u=()=>{}}){const o=E.slideover({title:d(e),size:t,position:"right"});o.element.appendChild(a);const $=Ue(a),w=M.applyBindings(n,a,{methods:l});c&&(U=c),G.add(o),st(o,()=>{u(),w.dispose(),$(),G.delete(o),U===c&&(U=null)});const x=o.close.bind(o);let f=!1,O=!1;return o.close=async F=>{if(!f&&F!==!0&&i()){if(O)return;O=!0;const q=await E.confirm("Discard the changes you have not saved?");if(O=!1,!q)return}return f=!0,x()},I.scan(a),o.open(),o}function oe(e,t=null){const a=Q(e);if(!a)return;const n=De(a),l=Fe(a),i=W(a.name),c=qe(a,Y.peek()),u=!!(c&&i?.entitled&&!i?.needsCms),$={...Object.fromEntries(l.map(s=>[s.key,s.value])),...Object.fromEntries(Object.entries(t||{}).filter(([s])=>!l.find(p=>p.key===s)?.secret))},w=Object.fromEntries(l.map(s=>[s.key,M.observable($[s.key])])),x=M.computed(()=>gt(l,Object.fromEntries(l.map(s=>[s.key,w[s.key].value])))),f=M.observable(!1),O=()=>Object.keys(x.peek().changed).length>0||Object.keys(x.peek().errors).length>0,F=[["Version",`v${a.version}${c?` (v${c} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",mt(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,s])=>s),q=(s,p)=>{const A=`plx-set-${p}`,Z=s.help?` <span data-help="${d(s.help)}"></span>`:"",H=`<label class="form-label" for="${A}">${d(s.label)}${Z}</label>`,K=`data-model="v${p}.value"`,ee=`<small class="plx-err" data-bind-hidden="!err${p}.value" data-bind-text="err${p}.value"></small>`;if(s.type==="checkbox")return`<div class="plx-setting">${H}<input id="${A}" type="checkbox" class="form-switch" ${K}></div>`;if(s.type==="select")return`<div>${H}<select id="${A}" class="form-input" ${K}>${s.options.map(Le=>`<option value="${d(Le.value)}">${d(Le.label)}</option>`).join("")}</select>${ee}</div>`;if(s.type==="json")return`<div>${H}<textarea id="${A}" class="form-input plx-json" rows="5" spellcheck="false" ${K}></textarea>${ee}</div>`;if(s.type==="textarea")return`<div>${H}<textarea id="${A}" class="form-input" rows="3" ${K}></textarea>${ee}</div>`;const Ze=s.type==="number"?"number":s.secret?"password":"text",et=`${s.min!=null?` min="${d(s.min)}"`:""}${s.max!=null?` max="${d(s.max)}"`:""}`;return`<div>${H}<input id="${A}" type="${Ze}" class="form-input" autocomplete="${s.secret?"new-password":"off"}"${et} ${K}>${ee}</div>`},r=bt(a,{plugins:L.peek(),tools:R.peek(),catalogue:h.peek().items||[]}),C={saving:f,needs:M.observable(r.needs),worksWith:M.observable(r.worksWith),hasNeeds:r.needs.length>0,hasWorksWith:r.worksWith.length>0,hasFields:l.length>0,cannot:M.computed(()=>f.value||!Object.keys(x.value.changed).length||Object.keys(x.value.errors).length>0),...Object.fromEntries(l.flatMap((s,p)=>[[`v${p}`,w[s.key]],[`err${p}`,M.computed(()=>x.value.errors[s.key]||"")]]))},_=me(`
37
+ </li>`,i=O=>String(O??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function Ee(O){const g=document.createElement("template");return g.innerHTML=O.trim(),g.content.firstElementChild}const y=$t(Ze);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(O){y.reset();const g=O.get(0).querySelector(".plx")||O.get(0),p=()=>Ze.test(location.hash)&&g.isConnected,R=M.observable([]),j=M.observable([]),Se=M.computed(()=>j.value.map(e=>{const t=[...(e.requiredBy||[]).map(a=>a.displayName),...(e.usedBy||[]).map(a=>a.displayName)];return{name:e.name,displayName:e.displayName,icon:e.icon,meta:[e.description,t.length?`used by ${t.join(", ")}`:"",e.locked?"locked by your manager":"",e.staff?"your host's staff can still use it":""].filter(Boolean).join(" \xB7 "),locked:e.locked===!0,statusText:e.enabled?"On":"Off",statusCls:e.enabled?"is-ok":"is-muted",rowCls:e.enabled?"":"is-off"}})),u=M.observable({available:null,site:null,items:[]}),Te=M.observable(!0),ue=M.observable(""),f=M.observable("");let Ce="all";try{Ce=St.includes(S.get($e))?S.get($e):"all"}catch{}const A=M.observable(Ce),J=M.observable(""),W=M.observable("all"),Me=M.observable("");y.add(M.effect(()=>{const e=A.value;try{S.set($e,e)}catch{}}));const Q=M.computed(()=>new Map((u.value.items||[]).map(e=>[e.slug,e.version]))),L=e=>(u.peek().items||[]).find(t=>t.slug===e),pe=M.observable([]);y.add(M.effect(()=>{const e=Q.value;pe.value=Ct(R.value,{filter:A.value,query:J.value,latest:e}).map(t=>({...Dt(t,e),accent:Ye(t.name)}))}));const tt=M.computed(()=>{const e=R.value,t=Q.value,a=e.filter(n=>Je(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>At(n,t)).length}}),G=M.computed(()=>(u.value.items||[]).filter(e=>re(e)==="update").length),at=M.computed(()=>R.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),me=M.observable([]);y.add(M.effect(()=>{me.value=Tt(u.value.items,{filter:W.value,query:Me.value}).map(e=>{const t=Mt(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:Ye(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const nt=M.computed(()=>{const e=u.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>re(t)==="install").length,updates:G.value}}),Z=e=>R.peek().find(t=>t.name===e);async function he(){try{const[e,t]=await wt(g.querySelector(".dm-loading-slot"),Promise.all([h.plugins.list(),h.tools.list().catch(()=>[])]),vt.iconRows);if(!p())return;R.value=Array.isArray(e)?e:[],j.value=Array.isArray(t)?t:[],ue.value=""}catch(e){ue.value=`Could not load the plugins: ${e.message||e}`}finally{Te.value=!1}}async function Ne(){try{const e=await h.marketplace.catalogue();if(!p())return;u.value={available:!!e?.available,site:e?.site||null,items:e?.catalogue||[],mode:e?.mode||(e?.available?"managed":"none"),siteError:e?.siteError||"",storeFailed:e?.failed||"",connection:e?.connection||null},e?.connection?.status==="pending"&&be();for(const t of e?.pending||[])Ie(t.id,{fast:!1})}catch{u.value={available:!1,site:null,items:[],failed:!0}}}const v=async()=>{await Promise.all([he(),Ne()]),kt(Wt)};async function P(e,t,a="plugin"){if(e.core)return;const n=t?"on":"off";if(e.locked){E.toast(`${e.displayName||e.name} is locked by your site's manager - ask them to switch it ${n}.`,{type:"info",duration:6e3});return}if(!await E.confirm(`Switch ${i(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||f.peek())return;const s=o=>a==="tool"?h.tools.update(e.name,{enabled:t,cascade:o}):h.plugins.update(e.name,{enabled:t,cascade:o});f.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let o;try{o=await s(!1)}catch(d){if(d.status!==409||!d.body?.needsConfirm)throw d;const m=Lt(d.body.plan);if(f.value="",!await E.confirm(`<p>Switching ${i(e.displayName||e.name)} ${n} also means:</p><ul>${m.map(r=>`<li>${i(r)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;f.value=`Switching ${e.displayName||e.name} ${n}\u2026`,o=await s(!0)}await Et(o,{onStatus:d=>{f.value=d}}),E.toast(`${e.displayName||e.name} is ${n}.${t?" Reload the admin to open its screens.":""}`,{type:"success",duration:6e3});try{document.dispatchEvent(new CustomEvent("dm:sidebar-rebuild"))}catch{}}catch(o){E.toast(`Not switched ${n}: ${o.message||o}`,{type:"error"})}finally{f.value="",p()&&await v()}}async function F(e,{update:t=!1}={}){const a=i(e.displayName||e.slug),n=t?`<p>Update ${a} from ${i(e.installedVersion)} to ${i(e.version)}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`:`<p>Install ${a} v${i(e.version)}?</p> <p class="text-muted">It arrives licensed to this site and takes effect after a restart.</p>`;if(await E.confirm(n,{title:t?"Update plugin":"Install plugin",confirmText:t?"Update":"Install",cancelText:"Cancel",html:!0})){try{const s=await h.marketplace.install(e.slug,e.version,{update:t}),o=s?.action==="upgrade"?`${e.slug} updated${s.from?` from ${s.from}`:""} to ${s.version}.`:`${e.slug} ${s?.version??e.version} installed.`;E.toast(`${o} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(s){E.toast(s.message||"Install failed.",{type:"error"})}p()&&await v()}}const x=new Map;y.add(()=>{for(const e of x.values())clearTimeout(e.timer);x.clear()});function Ie(e,{fast:t=!0}={}){if(!e||x.has(e))return;const a={timer:null,until:Date.now()+(t?jt:0)};x.set(e,a);const n=()=>{clearTimeout(a.timer),!(!p()||!x.has(e))&&(a.timer=setTimeout(()=>te(e),Date.now()<a.until?et:Ft))};a.next=n,n()}const Oe=e=>{const t=x.get(e);t&&clearTimeout(t.timer),x.delete(e)},ee=new Set;async function te(e,{byHand:t=!1}={}){if(!p()||ee.has(e))return;ee.add(e),clearTimeout(x.get(e)?.timer);let a;try{a=await h.marketplace.claim(e)}catch(s){t&&E.toast(s.message||"The store could not be asked just now.",{type:"error"}),ee.delete(e),x.get(e)?.next?.();return}ee.delete(e);const n=L(a.slug)?.displayName||a.slug;if(a.status==="pending"){t&&E.toast(`Not paid yet - ${n} installs here as soon as the payment is through.`,{type:"info",duration:6e3}),x.get(e)?.next?.();return}if(Oe(e),a.status==="paid")if(a.kind==="renew")E.toast(`${n}: updates renewed.${a.installed&&!a.refreshed?" Update it on the Browse tab.":""}`,{type:"success",duration:8e3});else if(a.installed&&a.refreshed===!1&&a.installError)E.toast(`${n} is paid for, but the copy here could not be brought up to date: ${a.installError}. Use Update on the Browse tab.`,{type:"warning",duration:12e3});else if(a.installed){const s=(a.included||[]).filter(o=>o.installed).map(o=>L(o.slug)?.displayName||o.slug);E.toast(`${n} is paid for and installed${s.length?`, with ${s.join(" and ")} free`:""}. Restart the server to activate ${s.length?"them":"it"}.`+(s.some(o=>/mongo/i.test(o))?" Then open MongoDB in the sidebar to connect your database.":""),{type:"success",duration:12e3})}else E.toast(`${n} is paid for, but did not install: ${a.installError||"try Install on the Browse tab"}. The licence key is in your email.`,{type:"warning",duration:12e3});else a.status!=="unknown"&&E.toast(`${n}: the purchase ${a.status==="expired"?"was not paid for in time":`is ${a.status}`}.`,{type:"warning",duration:8e3});p()&&await v()}async function st(e){if(e?.pending&&await E.confirm(`<p>Stop waiting for the payment for ${i(e.displayName||e.slug)}?</p> <p class="text-muted">Nothing is cancelled at the store - if you did pay, the licence key is in your email and Install from file takes the file it links to.</p>`,{title:"Stop waiting",confirmText:"Stop waiting",cancelText:"Keep waiting",html:!0})){Oe(e.pending);try{await h.marketplace.dropPurchase(e.pending)}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}p()&&await v()}}async function lt(e){const t=await E.prompt(`Licence key for ${i(e.displayName||e.slug)} - it is in the email you had when you bought it.`,{title:"Enter licence key",inputPlaceholder:"DOMMA-XXXX-XXXX-XXXX",confirmText:"Use this key"});if(!(!t||!p()))try{const a=await h.marketplace.enterKey(e.slug,String(t).trim());await v();const n=L(e.slug);a.updates&&n&&!n.installed?(E.toast(`Licence accepted for ${e.displayName||e.slug}.`,{type:"success"}),await F(n)):E.toast(`Licence accepted for ${e.displayName||e.slug}.${n?.installed?" Restart the server for it to take effect.":""}`,{type:"success",duration:7e3})}catch(a){E.toast(a.message||"That key could not be used.",{type:"error",duration:8e3})}}async function ot(e){if(f.peek())return;const t=Bt(e,{site:u.peek().site,email:Y()?.email}),a=t.lines.map((s,o)=>`<p${o?' class="text-muted"':""}>${i(s)}</p>`).join(" ");if(!await E.confirm(a,{title:t.title,confirmText:e.owned?"Renew":"Buy",cancelText:"Cancel",html:!0}))return;const n=window.open("","_blank");try{const s=await h.marketplace.buy(e.slug);n&&!n.closed?(n.opener=null,n.location.href=s.checkoutUrl):window.open(s.checkoutUrl,"_blank","noopener")||E.toast("Your browser blocked the payment tab - allow pop-ups for this site and choose Buy again.",{type:"warning",duration:9e3}),Ie(s.id),E.toast(`Payment opened in a new tab. ${e.displayName||e.slug} ${e.owned?"renews":"installs here"} as soon as it is through - keep this page open, or come back to it.`,{type:"info",duration:9e3})}catch(s){try{n?.close()}catch{}E.toast(s.message||"The purchase could not be started.",{type:"error",duration:8e3})}p()&&await v()}let ae=null,q=0;y.add(()=>clearTimeout(ae));function be(){q||(q=Date.now()+60*6e4),clearTimeout(ae),!(!p()||Date.now()>q)&&(ae=setTimeout(()=>fe(!1),et))}let ne=!1;async function fe(e){if(ne||!p())return;ne=!0;let t;try{t=await h.marketplace.connectCheck()}catch(n){e&&E.toast(n.message||"Could not ask just now.",{type:"error"}),ne=!1,be();return}ne=!1;const a=t?.connection||null;if(a?.status==="pending"){e&&E.toast(`Not yet - open the link we emailed to ${a.email} and choose Connect.`,{type:"info",duration:6e3}),be();return}q=0,a?.status==="connected"?E.toast(`Connected to Domma as ${a.email}.`,{type:"success",duration:7e3}):E.toast("The link was not opened in time - choose Connect to Domma again.",{type:"warning",duration:7e3}),p()&&await v()}async function it(){const e=await E.prompt("The email address you bought your Tools with. We email it a link; open it and choose Connect.",{title:"Connect to Domma",inputPlaceholder:Y()?.email||"you@example.com",defaultValue:Y()?.email||"",confirmText:"Email me the link"});if(!(e==null||!p()))try{const t=await h.marketplace.connect(String(e).trim()||Y()?.email||"");E.toast(`Link emailed to ${t.connection?.email}. Open it and choose Connect - this page picks it up.`,{type:"info",duration:9e3}),q=0,await v()}catch(t){E.toast(t.message||"Could not connect.",{type:"error",duration:8e3})}}async function rt(){const e=u.peek().connection;if(e&&!(e.status!=="pending"&&!await E.confirm(`<p>Disconnect this site from Domma (${i(e.email)})?</p> <p class="text-muted">The licences it already has stay. New ones stop arriving by themselves - connect again, or enter a key.</p>`,{title:"Disconnect",confirmText:"Disconnect",cancelText:"Keep it",html:!0}))){clearTimeout(ae),q=0;try{await h.marketplace.disconnect()}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}p()&&await v()}}const Ae=()=>{for(const e of[...x.keys()])te(e);u.peek().connection?.status==="pending"&&fe(!1)};window.addEventListener("focus",Ae),y.add(()=>window.removeEventListener("focus",Ae));function Le(e){if(e?.store){ot(e);return}e?.buyUrl&&(window.open(e.buyUrl,"_blank","noopener"),E.toast(`Manage my site opened in a new tab. We email you a sign-in link; ${e.displayName||e.slug} is ticked ready once you are in. Install it here when it is paid for.`,{type:"info",duration:9e3}))}async function De(e,t){const n=L(e)?.tier==="paid"&&!L(e)?.store?` <p class="text-muted">It is a paid Tool: your site's manager is told, and if you pay for it on its own it comes off your monthly bill (the rest of this month is credited).</p>`:"";if(await E.confirm(`<p>Uninstall ${i(t||e)}?</p> <p class="text-muted">Its files are removed, and its <code>data/</code> folder with them. Roles it added are removed and their users moved to <code>user</code>. Restart the server to finish.</p>${n}`,{title:"Uninstall plugin",confirmText:"Uninstall",cancelText:"Cancel",html:!0})){try{const o=(await h.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${o} Restart the server to apply.`,{type:"success",duration:6e3})}catch(s){E.toast(`Uninstall failed: ${s.message||s}`,{type:"error"})}p()&&await v()}}async function Ue(e){try{await h.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const Re=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},X=g.querySelector(".plx-file");async function ct(e){if(f.peek())return;f.value=`Installing ${e.name}\u2026`;const t={};try{for(let a=0;a<4;a++)try{const n=await h.plugins.installFile(e,t),s=n.action==="upgrade"?`${n.name} updated${n.from?` from ${n.from}`:""} to ${n.version}.`:`${n.name} ${n.version} installed.`;E.toast(`${s} Restart the server to activate it.`,{type:"success",duration:6e3});return}catch(n){if(f.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${i(n.name)} ${i(n.installedVersion||"the installed version")} is already installed. Update it to ${i(n.incomingVersion||"this file")}?</p> <p class="text-muted">The plugin keeps its data, and the current version is put back if the update fails.</p>`,{title:"Update plugin",confirmText:"Update",cancelText:"Cancel",html:!0}))return;t.confirmUpgrade=!0}else if(/refusing to downgrade/i.test(n.message)&&!t.confirmDowngrade){if(!await E.confirm(`<p>${i(n.message)} Install it anyway?</p> <p class="text-muted">An older version may not understand data written by the newer one.</p>`,{title:"Downgrade plugin",confirmText:"Downgrade",cancelText:"Cancel",html:!0}))return;t.confirmDowngrade=!0}else if(/unsigned|signature/i.test(n.message)&&!t.confirmUnsigned){if(!await E.confirm(`<p>${i(n.message)}</p> <p class="text-muted">An unsigned plugin has not been verified as coming from the marketplace. Its code runs on this server with full access. Install it anyway?</p>`,{title:"Unsigned plugin",confirmText:"Install anyway",cancelText:"Cancel",html:!0}))return;t.confirmUnsigned=!0}else{E.toast(n.message||"Install failed.",{type:"error"});return}f.value=`Installing ${e.name}\u2026`}}finally{f.value="",p()&&await v()}}const Be=async()=>{const e=X.files?.[0];X.value="",e&&await ct(e)};X.addEventListener("change",Be),y.add(()=>X.removeEventListener("change",Be));const se=new Set;let B=null,Fe=!1;function je({title:e,size:t="md",panel:a,model:n,methods:s,dirty:o=()=>!1,form:d=null,cleanup:m=()=>{}}){const r=E.slideover({title:i(e),size:t,position:"right"});r.element.appendChild(a);const C=He(a),$=M.applyBindings(n,a,{methods:s});d&&(B=d),se.add(r),xt(r,()=>{m(),$.dispose(),C(),se.delete(r),B===d&&(B=null)});const T=r.close.bind(r);let w=!1,D=!1;return r.close=async _=>{if(!w&&_!==!0&&o()){if(D)return;D=!0;const K=await E.confirm("Discard the changes you have not saved?");if(D=!1,!K)return}return w=!0,T()},I.scan(a),r.open(),r}function ge(e,t=null){const a=Z(e);if(!a)return;const n=Je(a),s=Qe(a),o=L(a.name),d=Ge(a,Q.peek()),m=!!(d&&o?.entitled&&!o?.needsCms),C={...Object.fromEntries(s.map(l=>[l.key,l.value])),...Object.fromEntries(Object.entries(t||{}).filter(([l])=>!s.find(b=>b.key===l)?.secret))},$=Object.fromEntries(s.map(l=>[l.key,M.observable(C[l.key])])),T=M.computed(()=>Ut(s,Object.fromEntries(s.map(l=>[l.key,$[l.key].value])))),w=M.observable(!1),D=()=>Object.keys(T.peek().changed).length>0||Object.keys(T.peek().errors).length>0,_=[["Version",`v${a.version}${d?` (v${d} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",Ot(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,l])=>l),K=(l,b)=>{const U=`plx-set-${b}`,oe=l.help?` <span data-help="${i(l.help)}"></span>`:"",H=`<label class="form-label" for="${U}">${i(l.label)}${oe}</label>`,V=`data-model="v${b}.value"`,ie=`<small class="plx-err" data-bind-hidden="!err${b}.value" data-bind-text="err${b}.value"></small>`;if(l.type==="checkbox")return`<div class="plx-setting">${H}<input id="${U}" type="checkbox" class="form-switch" ${V}></div>`;if(l.type==="select")return`<div>${H}<select id="${U}" class="form-input" ${V}>${l.options.map(ze=>`<option value="${i(ze.value)}">${i(ze.label)}</option>`).join("")}</select>${ie}</div>`;if(l.type==="json")return`<div>${H}<textarea id="${U}" class="form-input plx-json" rows="5" spellcheck="false" ${V}></textarea>${ie}</div>`;if(l.type==="textarea")return`<div>${H}<textarea id="${U}" class="form-input" rows="3" ${V}></textarea>${ie}</div>`;const gt=l.type==="number"?"number":l.secret?"password":"text",yt=`${l.min!=null?` min="${i(l.min)}"`:""}${l.max!=null?` max="${i(l.max)}"`:""}`;return`<div>${H}<input id="${U}" type="${gt}" class="form-input" autocomplete="${l.secret?"new-password":"off"}"${yt} ${V}>${ie}</div>`},c=It(a,{plugins:R.peek(),tools:j.peek(),catalogue:u.peek().items||[]}),N={saving:w,needs:M.observable(c.needs),worksWith:M.observable(c.worksWith),hasNeeds:c.needs.length>0,hasWorksWith:c.worksWith.length>0,hasFields:s.length>0,cannot:M.computed(()=>w.value||!Object.keys(T.value.changed).length||Object.keys(T.value.errors).length>0),...Object.fromEntries(s.flatMap((l,b)=>[[`v${b}`,$[l.key]],[`err${b}`,M.computed(()=>T.value.errors[l.key]||"")]]))},z=Ee(`
38
38
  <div class="plx-form">
39
39
  <p class="plx-desc"></p>
40
40
  <dl class="plx-facts"></dl>
@@ -51,13 +51,13 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
51
51
  <div data-if="hasFields">
52
52
  <p class="plx-sub">Settings
53
53
  <span data-help-title="Settings" data-help="Saved to config/plugins.json for this site. Only what you change is stored - anything you leave keeps the plugin's own default, so a later version can improve it. Most plugins read their settings as they run; a few only at start-up."></span></p>
54
- <div class="plx-form">${l.map(q).join("")}</div>
54
+ <div class="plx-form">${s.map(K).join("")}</div>
55
55
  </div>
56
56
  <p class="plx-hint" data-if="!hasFields">This plugin has no settings to change here.</p>
57
57
  <div class="plx-actions">
58
58
  ${a.core?"":`<button type="button" class="btn btn-sm btn-ghost" data-on-click="toggle"><span data-icon="${a.enabled?"pause":"play"}" data-icon-size="13"></span> ${a.enabled?"Switch off":"Switch on"}</button>`}
59
- ${u?`<button type="button" class="btn btn-sm btn-ghost" data-on-click="update"><span data-icon="download" data-icon-size="13"></span> Update to v${d(c)}</button>`:""}
60
- ${c&&i?.needsCms?`<span class="plx-hint">v${d(c)}: ${d(i.needsCms)}</span>`:""}
59
+ ${m?`<button type="button" class="btn btn-sm btn-ghost" data-on-click="update"><span data-icon="download" data-icon-size="13"></span> Update to v${i(d)}</button>`:""}
60
+ ${d&&o?.needsCms?`<span class="plx-hint">v${i(d)}: ${i(o.needsCms)}</span>`:""}
61
61
  ${a.sourceEditable!==!1?'<button type="button" class="btn btn-sm btn-ghost" data-on-click="source"><span data-icon="code" data-icon-size="13"></span> Source</button>':""}
62
62
  ${a.closedSource?"":'<button type="button" class="btn btn-sm btn-ghost" data-on-click="exportIt" title="Download as a .dcmsplugin file"><span data-icon="download" data-icon-size="13"></span> Export</button>'}
63
63
  <span class="plx-spacer"></span>
@@ -65,7 +65,7 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
65
65
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-if="hasFields" data-bind-disabled="cannot.value">
66
66
  <span data-icon="check" data-icon-size="13"></span> Save settings</button>
67
67
  </div>
68
- </div>`);_.querySelector(".plx-desc").textContent=a.description||"",_.querySelectorAll(".plx-deps").forEach(s=>{s.innerHTML=Et});const Xe=_.querySelector(".plx-facts");for(const[s,p]of F){const A=document.createElement("dt");A.textContent=s;const Z=document.createElement("dd");Z.textContent=p,Xe.append(A,Z)}async function Ae(){if(C.cannot.peek())return;const{changed:s}=x.peek();f.value=!0;try{await v.plugins.update(a.name,{settings:{...a.settings||{},...s}}),E.toast(`${a.displayName||a.name}: settings saved.`,{type:"success"}),X.close(!0),k()&&await ie()}catch(p){E.toast(`Not saved: ${p.message||p}`,{type:"error"})}finally{f.value=!1}}const ue=s=>async()=>{await X.close(),G.has(X)||s()},X=Me({title:a.displayName||a.name,size:"md",panel:_,model:C,dirty:O,form:l.length?{kind:"settings",name:a.name,dirty:O,values:()=>{const s={};for(const p of l)p.secret||(s[p.key]=w[p.key].peek());return s}}:null,methods:{save:Ae,cancel:()=>X.close(),toggle:ue(()=>B(a,!a.enabled)),update:ue(()=>D(i,{update:!0})),source:ue(()=>$e(a)),exportIt:()=>ke(a)}});_.addEventListener("keydown",s=>{(s.ctrlKey||s.metaKey)&&s.key==="Enter"&&(s.preventDefault(),Ae())})}function Ce(e=null){const t=tt(),a={displayName:M.observable(e?.displayName??""),slug:M.observable(e?.slug??""),description:M.observable(e?.description??""),author:M.observable(e?.author??(t?.name||t?.username||"")),icon:M.observable(e?.icon??"box")},n=JSON.stringify(Object.fromEntries(Object.entries(a).map(([r,C])=>[r,C.peek()]))),l=()=>Object.fromEntries(Object.entries(a).map(([r,C])=>[r,C.peek()])),i=()=>JSON.stringify(l())!==n||!!e;let c=!!e?.slug;const u=M.effect(()=>{const r=a.displayName.value;c||(a.slug.value=yt(r))}),o=M.observable(!1),$=M.computed(()=>pt(Object.fromEntries(Object.entries(a).map(([r,C])=>[r,C.value])),L.value.map(r=>r.name))),w=r=>M.computed(()=>$.value.errors[r]||""),x={...a,saving:o,nameErr:w("displayName"),slugErr:w("slug"),descErr:w("description"),authorErr:w("author"),iconErr:w("icon"),cannot:M.computed(()=>o.value||Object.keys($.value.errors).length>0)},f=me(`
68
+ </div>`);z.querySelector(".plx-desc").textContent=a.description||"",z.querySelectorAll(".plx-deps").forEach(l=>{l.innerHTML=Kt});const ft=z.querySelector(".plx-facts");for(const[l,b]of _){const U=document.createElement("dt");U.textContent=l;const oe=document.createElement("dd");oe.textContent=b,ft.append(U,oe)}async function Xe(){if(N.cannot.peek())return;const{changed:l}=T.peek();w.value=!0;try{await h.plugins.update(a.name,{settings:{...a.settings||{},...l}}),E.toast(`${a.displayName||a.name}: settings saved.`,{type:"success"}),le.close(!0),p()&&await he()}catch(b){E.toast(`Not saved: ${b.message||b}`,{type:"error"})}finally{w.value=!1}}const xe=l=>async()=>{await le.close(),se.has(le)||l()},le=je({title:a.displayName||a.name,size:"md",panel:z,model:N,dirty:D,form:s.length?{kind:"settings",name:a.name,dirty:D,values:()=>{const l={};for(const b of s)b.secret||(l[b.key]=$[b.key].peek());return l}}:null,methods:{save:Xe,cancel:()=>le.close(),toggle:xe(()=>P(a,!a.enabled)),update:xe(()=>F(o,{update:!0})),source:xe(()=>Re(a)),exportIt:()=>Ue(a)}});z.addEventListener("keydown",l=>{(l.ctrlKey||l.metaKey)&&l.key==="Enter"&&(l.preventDefault(),Xe())})}function We(e=null){const t=Y(),a={displayName:M.observable(e?.displayName??""),slug:M.observable(e?.slug??""),description:M.observable(e?.description??""),author:M.observable(e?.author??(t?.name||t?.username||"")),icon:M.observable(e?.icon??"box")},n=JSON.stringify(Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.peek()]))),s=()=>Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.peek()])),o=()=>JSON.stringify(s())!==n||!!e;let d=!!e?.slug;const m=M.effect(()=>{const c=a.displayName.value;d||(a.slug.value=Rt(c))}),r=M.observable(!1),C=M.computed(()=>Nt(Object.fromEntries(Object.entries(a).map(([c,N])=>[c,N.value])),R.value.map(c=>c.name))),$=c=>M.computed(()=>C.value.errors[c]||""),T={...a,saving:r,nameErr:$("displayName"),slugErr:$("slug"),descErr:$("description"),authorErr:$("author"),iconErr:$("icon"),cannot:M.computed(()=>r.value||Object.keys(C.value.errors).length>0)},w=Ee(`
69
69
  <div class="plx-form">
70
70
  <div>
71
71
  <label class="form-label" for="plx-np-name">Display name <span class="text-danger">*</span></label>
@@ -101,10 +101,16 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
101
101
  <button type="button" class="btn btn-sm btn-primary" data-on-click="create" data-bind-disabled="cannot.value">
102
102
  <span data-icon="plus" data-icon-size="13"></span> Create plugin</button>
103
103
  </div>
104
- </div>`);async function O(){if(x.cannot.peek())return;o.value=!0;const{payload:r}=$.peek();try{await v.plugins.scaffold(r),E.toast(`"${r.displayName}" created. Restart the server to activate it.`,{type:"success",duration:6e3}),F.close(!0),k()&&await P()}catch(C){E.toast(C.message||"Could not create the plugin.",{type:"error"})}finally{o.value=!1}}const F=Me({title:"New plugin",size:"sm",panel:f,model:x,dirty:i,form:{kind:"new",name:null,dirty:i,values:l},cleanup:()=>u(),methods:{create:O,cancel:()=>F.close()}}),q=f.querySelector("#plx-np-slug");q.addEventListener("input",()=>{c=!!q.value}),f.addEventListener("keydown",r=>{(r.ctrlKey||r.metaKey)&&r.key==="Enter"&&(r.preventDefault(),O())}),f.querySelector("#plx-np-name")?.focus()}function Ke(e){const t=Q(e);if(!t)return[];const a=W(t.name),n=qe(t,Y.peek()),l=!!b.peek();return[{header:t.displayName||t.name},{label:Fe(t).length?"Details and settings\u2026":"Details\u2026",icon:"settings",action:()=>oe(t.name)},...t.core?[]:[t.enabled?{label:"Switch off\u2026",icon:"pause",disabled:l,action:()=>B(t,!1)}:{label:"Switch on\u2026",icon:"play",disabled:l,action:()=>B(t,!0)}],...n?[{label:a?.needsCms?`Update to v${n} - needs a newer Domma CMS`:`Update to v${n}\u2026`,icon:"download",disabled:l||!a?.entitled||!!a?.needsCms,action:()=>D(a,{update:!0})}]:[],{type:"divider"},{label:"View source",icon:"code",disabled:t.sourceEditable===!1,action:()=>$e(t)},{label:"Export .dcmsplugin",icon:"download",disabled:t.closedSource===!0,action:()=>ke(t)},...t.core?[]:[{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:l,action:()=>xe(t.name,t.displayName)}]]}function Ve(e){const t=R.peek().find(n=>n.name===e);if(!t)return[];const a=!!b.peek();return[{header:t.displayName},t.enabled?{label:t.locked?"Switch off (locked)":"Switch off\u2026",icon:"pause",disabled:a||t.locked,action:()=>B(t,!1,"tool")}:{label:t.locked?"Switch on (locked)":"Switch on\u2026",icon:"play",disabled:a||t.locked,action:()=>B(t,!0,"tool")}]}const Ye=e=>{const t=R.peek().find(a=>a.name===e);t&&B(t,!t.enabled,"tool")};function Je(e){const t=W(e);if(!t)return[];const a=te(t),n=!!b.peek();return[{header:t.displayName||t.slug},...a==="install"?[{label:`Install v${t.version}\u2026`,icon:"download",disabled:n,action:()=>D(t)}]:[],...a==="update"?[{label:`Update to v${t.version}\u2026`,icon:"download",disabled:n,action:()=>D(t,{update:!0})}]:[],...t.installed?[{label:"Open in Installed",icon:"package",action:()=>{V.value=t.slug,N.value="all",Ie.activate?.(0)}},{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:n,action:()=>xe(t.slug,t.displayName)}]:[],...a==="buy"?[{label:`${t.licenceStatus==="expired"?"Renew":"Buy"}${Be(t)!=="Paid"?` - ${Be(t)}`:""}\u2026`,icon:"shopping-cart",action:()=>we(t)}]:[],...a==="locked"?[{label:"Not licensed for this site",icon:"lock",disabled:!0,action:()=>{}}]:[],...a==="needs-cms"?[{label:t.needsCms,icon:"alert-triangle",disabled:!0,action:()=>{}}]:[]]}function Qe(e){const t=W(e);if(!t)return;const a=te(t);a==="install"?D(t):a==="update"?D(t,{update:!0}):a==="buy"?we(t):a==="needs-cms"?E.toast(t.needsCms,{type:"warning",duration:6e3}):t.installed&&(V.value=t.slug,N.value="all",Ie.activate?.(0))}function re(e,t,a,n){const l=E.contextMenu(e,{cursor:"glyph",match:".plx-row",inherit:!1,density:"compact",items:u=>a(u.dataset[t])});g.add(()=>l?.destroy?.());const i=u=>{const o=u.target.closest(".plx-row");if(!o)return;const $=u.target.closest(".plx-kebab");if($){Re($);return}if(u.target.closest(".plx-act")){u.target.closest("button").disabled||n(o.dataset[t]);return}n(o.dataset[t])},c=u=>{const o=u.target.closest(".plx-row");o&&(u.key==="F10"&&u.shiftKey?(u.preventDefault(),Re(o)):u.key==="Enter"&&u.target===o&&n(o.dataset[t]))};e.addEventListener("click",i),e.addEventListener("keydown",c),g.add(()=>{e.removeEventListener("click",i),e.removeEventListener("keydown",c)})}const de=m.querySelector(".plx-browse");de.appendChild(me(`
104
+ </div>`);async function D(){if(T.cannot.peek())return;r.value=!0;const{payload:c}=C.peek();try{await h.plugins.scaffold(c),E.toast(`"${c.displayName}" created. Restart the server to activate it.`,{type:"success",duration:6e3}),_.close(!0),p()&&await v()}catch(N){E.toast(N.message||"Could not create the plugin.",{type:"error"})}finally{r.value=!1}}const _=je({title:"New plugin",size:"sm",panel:w,model:T,dirty:o,form:{kind:"new",name:null,dirty:o,values:s},cleanup:()=>m(),methods:{create:D,cancel:()=>_.close()}}),K=w.querySelector("#plx-np-slug");K.addEventListener("input",()=>{d=!!K.value}),w.addEventListener("keydown",c=>{(c.ctrlKey||c.metaKey)&&c.key==="Enter"&&(c.preventDefault(),D())}),w.querySelector("#plx-np-name")?.focus()}function dt(e){const t=Z(e);if(!t)return[];const a=L(t.name),n=Ge(t,Q.peek()),s=!!f.peek();return[{header:t.displayName||t.name},{label:Qe(t).length?"Details and settings\u2026":"Details\u2026",icon:"settings",action:()=>ge(t.name)},...t.core?[]:[t.enabled?{label:"Switch off\u2026",icon:"pause",disabled:s,action:()=>P(t,!1)}:{label:"Switch on\u2026",icon:"play",disabled:s,action:()=>P(t,!0)}],...n?[{label:a?.needsCms?`Update to v${n} - needs a newer Domma CMS`:`Update to v${n}\u2026`,icon:"download",disabled:s||!a?.entitled||!!a?.needsCms,action:()=>F(a,{update:!0})}]:[],{type:"divider"},{label:"View source",icon:"code",disabled:t.sourceEditable===!1,action:()=>Re(t)},{label:"Export .dcmsplugin",icon:"download",disabled:t.closedSource===!0,action:()=>Ue(t)},...t.core?[]:[{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:s,action:()=>De(t.name,t.displayName)}]]}function ut(e){const t=j.peek().find(n=>n.name===e);if(!t)return[];const a=!!f.peek();return[{header:t.displayName},t.enabled?{label:t.locked?"Switch off (locked)":"Switch off\u2026",icon:"pause",disabled:a||t.locked,action:()=>P(t,!1,"tool")}:{label:t.locked?"Switch on (locked)":"Switch on\u2026",icon:"play",disabled:a||t.locked,action:()=>P(t,!0,"tool")}]}const pt=e=>{const t=j.peek().find(a=>a.name===e);t&&P(t,!t.enabled,"tool")};function mt(e){const t=L(e);if(!t)return[];const a=re(t),n=!!f.peek();return[{header:t.displayName||t.slug},...a==="install"?[{label:`Install v${t.version}\u2026`,icon:"download",disabled:n,action:()=>F(t)}]:[],...a==="update"?[{label:`Update to v${t.version}\u2026`,icon:"download",disabled:n,action:()=>F(t,{update:!0})}]:[],...t.installed?[{label:"Open in Installed",icon:"package",action:()=>{J.value=t.slug,A.value="all",_e.activate?.(0)}},{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:n,action:()=>De(t.slug,t.displayName)}]:[],...a==="buy"?[{label:t.store?`${t.owned?"Renew updates":"Buy"} - ${t.owned?ce(t).replace(/^Renew /,""):ce(t)}\u2026`:`${t.licenceStatus==="expired"?"Renew":"Buy"}${ce(t)!=="Paid"?` - ${ce(t)}`:""}\u2026`,icon:"shopping-cart",action:()=>Le(t)}]:[],...t.store&&t.tier==="paid"&&!t.owned?[{label:"Enter licence key\u2026",icon:"key",action:()=>lt(t)}]:[],...a==="waiting"?[{label:"Paid? Check now",icon:"refresh-cw",action:()=>te(t.pending,{byHand:!0})},{label:"Stop waiting\u2026",icon:"x",action:()=>st(t)}]:[],...a==="locked"?[{label:"Not licensed for this site",icon:"lock",disabled:!0,action:()=>{}}]:[],...a==="needs-cms"?[{label:t.needsCms,icon:"alert-triangle",disabled:!0,action:()=>{}}]:[]]}function ht(e){const t=L(e);if(!t)return;const a=re(t);a==="install"?F(t):a==="update"?F(t,{update:!0}):a==="buy"?Le(t):a==="waiting"?te(t.pending,{byHand:!0}):a==="needs-cms"?E.toast(t.needsCms,{type:"warning",duration:6e3}):t.installed&&(J.value=t.slug,A.value="all",_e.activate?.(0))}function ye(e,t,a,n){const s=E.contextMenu(e,{cursor:"glyph",match:".plx-row",inherit:!1,density:"compact",items:m=>a(m.dataset[t])});y.add(()=>s?.destroy?.());const o=m=>{const r=m.target.closest(".plx-row");if(!r)return;const C=m.target.closest(".plx-kebab");if(C){Ve(C);return}if(m.target.closest(".plx-act")){m.target.closest("button").disabled||n(r.dataset[t]);return}n(r.dataset[t])},d=m=>{const r=m.target.closest(".plx-row");r&&(m.key==="F10"&&m.shiftKey?(m.preventDefault(),Ve(r)):m.key==="Enter"&&m.target===r&&n(r.dataset[t]))};e.addEventListener("click",o),e.addEventListener("keydown",d),y.add(()=>{e.removeEventListener("click",o),e.removeEventListener("keydown",d)})}const ve=g.querySelector(".plx-browse");ve.appendChild(Ee(`
105
105
  <div class="plx-card">
106
106
  <p class="plx-note" data-bind-hidden="browseState.value !== 'loading'">Loading the catalogue\u2026</p>
107
107
  <p class="plx-note" data-bind-hidden="browseState.value !== 'error'">The catalogue could not be loaded - it needs an administrator, and a manager that is reachable.</p>
108
+ <div data-bind-hidden="browseState.value !== 'owner'">
109
+ <p style="margin:0 0 .4rem"><strong>Every plugin is already here.</strong></p>
110
+ <p class="plx-note">This is an owner instance - the manager that the plugins are written on - so there is nothing to buy. Install from file in the banner still takes a <code>.dcmsplugin</code>.</p>
111
+ </div>
112
+ <p class="plx-note is-bad" data-bind-hidden="browseState.value !== 'list' || !catalogue.value.storeFailed" data-bind-text="catalogue.value.storeFailed"></p>
113
+ <p class="plx-note is-bad" data-bind-hidden="browseState.value !== 'list' || !catalogue.value.siteError" data-bind-text="catalogue.value.siteError"></p>
108
114
  <div data-bind-hidden="browseState.value !== 'file'">
109
115
  <p style="margin:0 0 .4rem"><strong>This site installs plugins from a file.</strong></p>
110
116
  <p class="plx-note">Buy a plugin and you are sent a single <code>.dcmsplugin</code> file - Install from file in the banner installs it, and the same button takes an update later. Sites managed for you browse and install here instead, over their manager connection.</p>
@@ -118,10 +124,16 @@ import{api as v,getUser as tt}from"../api.js";import{addBannerAction as pe}from"
118
124
  <button type="button" data-on-click="bUpdates" data-bind-class="browseFilter.value === 'updates' && 'is-on'" data-bind-hidden="!browseCounts.value.updates">Updates <b data-bind-text="browseCounts.value.updates"></b></button>
119
125
  </div>
120
126
  <input type="search" class="form-input plx-search" placeholder="Search the catalogue\u2026" aria-label="Search the catalogue" data-model="browseQuery.value">
121
- <span data-help-title="Browse" data-help="What this site's manager offers it. Install brings a plugin in licensed to this site; Update replaces the installed version and keeps its data. A paid Tool you can buy shows Buy\u2026 (Renew\u2026 once expired): it opens Manage my site in a new tab with that Tool ticked. One shown as Not licensed has no online billing - ask for it to be added. Install and Update take effect after a server restart."></span>
127
+ <span data-help-title="Browse" data-help="What this site can get. Install brings a plugin in licensed to this site; Update replaces the installed version and keeps its data. On a site managed for you, Buy\u2026 (Renew\u2026 once expired) opens Manage my site in a new tab with that Tool ticked, and Not licensed means it has no online billing - ask for it to be added. On a self-hosted site, Buy\u2026 opens the Domma store's payment page in a new tab: the Tool is yours to keep, it installs here once the payment is through, and the licence key is emailed to you. Its updates last a term (shown on the row); Renew\u2026 buys more. Install and Update take effect after a server restart."></span>
122
128
  </div>
123
129
  <p class="plx-note" data-bind-text="siteText.value" data-bind-hidden="!siteText.value"></p>
130
+ <div class="plx-connect" data-bind-hidden="catalogue.value.mode !== 'store'">
131
+ <span class="plx-note" data-bind-text="connectText.value"></span>
132
+ <button type="button" class="btn btn-sm btn-outline" data-on-click="connectStart" data-bind-hidden="connStatus.value !== ''">Connect to Domma\u2026</button>
133
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="connectCheck" data-bind-hidden="connStatus.value !== 'pending'">Check now</button>
134
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="connectForget" data-bind-hidden="connStatus.value === ''" data-bind-text="connStatus.value === 'pending' ? 'Cancel' : 'Disconnect\u2026'"></button>
135
+ </div>
124
136
  <p class="plx-note" data-bind-hidden="browseRows.value.length">Nothing in the catalogue matches.</p>
125
137
  <div class="plx-list plx-catalogue" data-each="browseRows.value key=slug"></div>
126
138
  </div>
127
- </div>`)),de.querySelector(".plx-catalogue").innerHTML=$t;const Te=m.querySelector(".plx-installed");Te.innerHTML=xt;const Ne=m.querySelector(".plx-tools");Ne.innerHTML=kt;const Ie=E.tabs(m.querySelector(".plx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),Ge=M.applyBindings({plugins:L,tools:R,toolRows:he,catalogue:h,loading:fe,loadError:ne,restarting:b,filter:N,query:V,rows:se,counts:Pe,emptyText:ze,updateCount:J,updateCountText:M.computed(()=>`${J.value} update${J.value===1?"":"s"}`),browseFilter:j,browseQuery:ge,browseRows:le,browseCounts:_e,siteText:M.computed(()=>h.value.site?`Licensed to ${h.value.site}.`:""),browseState:M.computed(()=>h.value.available===null?"loading":h.value.failed?"error":h.value.available?"list":"file")},m,{methods:{showAll:()=>{N.value="all"},showOn:()=>{N.value="on"},showOff:()=>{N.value="off"},showAttention:()=>{N.value="attention"},bAll:()=>{j.value="all"},bAvailable:()=>{j.value="available"},bInstalled:()=>{j.value="installed"},bUpdates:()=>{j.value="updates"}}});g.add(()=>Ge.dispose()),g.add(Ue(m,{position:"bottom"})),g.add(M.effect(()=>{se.value,he.value,le.value,requestAnimationFrame(()=>{m.isConnected&&I.scan(m)})})),re(Te,"name",Ke,e=>oe(e)),re(Ne,"tool",Ve,Ye),re(de.querySelector(".plx-catalogue"),"slug",Je,Qe),pe(T,{id:"plugins-guide",icon:"book",title:"Writing a Tool (guide)",onClick:()=>{location.hash="#/tutorials/plugin"}}),pe(T,{id:"plugins-install-file",icon:"upload",title:"Install from file (.dcmsplugin)",onClick:()=>z.click()});let ce=!1;try{ce=(await v.plugins.policy())?.signedOnly===!0}catch{}ce||pe(T,{id:"plugins-new",icon:"plus",title:"New plugin",onClick:()=>Ce()});const Oe=e=>{(b.peek()||U?.dirty())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Oe),g.add(()=>window.removeEventListener("beforeunload",Oe)),g.add(()=>{if(U?.dirty())try{S.set(ae,{kind:U.kind,name:U.name,values:U.values(),at:new Date().toISOString()})}catch{}Se=!0,[...G].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(m),await Promise.all([ie(),ye()]),!k())return;let y=null;try{y=S.get(ae)}catch{}if(y?.values&&!Se){try{S.remove?S.remove(ae):S.set(ae,null)}catch{}const e=y.kind==="new"?"the new plugin you started":`your settings for ${d(Q(y.name)?.displayName||y.name)}`;(y.kind==="new"&&!ce||Q(y.name))&&await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&k()&&(y.kind==="new"?Ce(y.values):oe(y.name,y.values))}}};
139
+ </div>`)),ve.querySelector(".plx-catalogue").innerHTML=_t;const Pe=g.querySelector(".plx-installed");Pe.innerHTML=Pt;const qe=g.querySelector(".plx-tools");qe.innerHTML=qt;const _e=E.tabs(g.querySelector(".plx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),bt=M.applyBindings({plugins:R,tools:j,toolRows:Se,catalogue:u,loading:Te,loadError:ue,restarting:f,filter:A,query:J,rows:pe,counts:tt,emptyText:at,updateCount:G,updateCountText:M.computed(()=>`${G.value} update${G.value===1?"":"s"}`),browseFilter:W,browseQuery:Me,browseRows:me,browseCounts:nt,siteText:M.computed(()=>u.value.site?u.value.mode==="store"?`From the Domma store, for ${u.value.site}. A Tool you buy is yours to keep, with a term of updates you can renew.`:`Licensed to ${u.value.site}.`:""),connStatus:M.computed(()=>u.value.connection?.status||""),connectText:M.computed(()=>{const e=u.value.connection;return e?e.status==="pending"?`Waiting for you to open the link we emailed to ${e.email} - choose Connect there.`:`Connected to Domma as ${e.email}: Tools bought for this site appear here by themselves.`:"Bought Tools on the Domma Marketplace? Connect this site and it picks up every licence bought for it."}),browseState:M.computed(()=>u.value.available===null?"loading":u.value.failed?"error":u.value.available?"list":u.value.mode==="owner"?"owner":"file")},g,{methods:{showAll:()=>{A.value="all"},showOn:()=>{A.value="on"},showOff:()=>{A.value="off"},showAttention:()=>{A.value="attention"},bAll:()=>{W.value="all"},bAvailable:()=>{W.value="available"},bInstalled:()=>{W.value="installed"},bUpdates:()=>{W.value="updates"},connectStart:()=>it(),connectCheck:()=>fe(!0),connectForget:()=>rt()}});y.add(()=>bt.dispose()),y.add(He(g,{position:"bottom"})),y.add(M.effect(()=>{pe.value,Se.value,me.value,requestAnimationFrame(()=>{g.isConnected&&I.scan(g)})})),ye(Pe,"name",dt,e=>ge(e)),ye(qe,"tool",ut,pt),ye(ve.querySelector(".plx-catalogue"),"slug",mt,ht),ke(O,{id:"plugins-guide",icon:"book",title:"Writing a Tool (guide)",onClick:()=>{location.hash="#/tutorials/plugin"}}),ke(O,{id:"plugins-install-file",icon:"upload",title:"Install from file (.dcmsplugin)",onClick:()=>X.click()});let we=!1;try{we=(await h.plugins.policy())?.signedOnly===!0}catch{}we||ke(O,{id:"plugins-new",icon:"plus",title:"New plugin",onClick:()=>We()});const Ke=e=>{(f.peek()||B?.dirty())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Ke),y.add(()=>window.removeEventListener("beforeunload",Ke)),y.add(()=>{if(B?.dirty())try{S.set(de,{kind:B.kind,name:B.name,values:B.values(),at:new Date().toISOString()})}catch{}Fe=!0,[...se].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(g),await Promise.all([he(),Ne()]),!p())return;let k=null;try{k=S.get(de)}catch{}if(k?.values&&!Fe){try{S.remove?S.remove(de):S.set(de,null)}catch{}const e=k.kind==="new"?"the new plugin you started":`your settings for ${i(Z(k.name)?.displayName||k.name)}`;(k.kind==="new"&&!we||Z(k.name))&&await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&p()&&(k.kind==="new"?We(k.values):ge(k.name,k.values))}}};
package/bin/update.js CHANGED
@@ -560,6 +560,8 @@ export default async function update(_positional, flags) {
560
560
  const requiredIgnores = [
561
561
  '.domma-backups/',
562
562
  'plugins/analytics/data/',
563
+ // The Domma store's licence keys and payment claims (services/storeClient.js).
564
+ 'config/store.json*',
563
565
  ];
564
566
  const current = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf8') : '';
565
567
  const missing = requiredIgnores.filter(entry => !current.split(/\r?\n/).includes(entry));
@@ -33,6 +33,7 @@ Controls the HTTP server.
33
33
  | `logging.level` | string | Log verbosity: `fatal`, `error`, `warn`, `info`, `debug`, `trace`, `silent`. Defaults to `info` in development, `warn` otherwise. `warn` hides 4xx responses and plugin `log.info` output, so a failed admin action leaves no trace - raise it to `info` if you need to diagnose one. Overridden by the `LOG_LEVEL` env var. |
34
34
  | `restartOnPluginToggle` | boolean | `true` | Restart the server automatically when an admin enables or disables a plugin. See **Plugin toggles restart the server** below |
35
35
  | `requireSignedPlugins` | boolean | `false` | When `true`, the site runs only plugin code the Marketplace signed: an unsigned `.dcmsplugin` (e.g. one exported from another site) is refused even if the installer confirms it, New plugin is refused, a plugin's files cannot be changed in the code editor (it opens read only), licensed source cannot be read even by a Super Admin, and MongoDB connection options that start a program or read a file (`autoEncryption`, `tls…File`, …) cannot be saved. A bundle with a signature that does not verify is always refused, whatever this is set to. Read fresh on every check, and also as it was at boot, so changing the file on a running site can switch it on but not off. `DOMMA_SIGNED_ONLY=1` in the environment turns it on whatever the file says - Domma CMS Manager sets it on the sites it hosts. Nothing in the admin writes `server.json`. See `server/services/codePolicy.js` |
36
+ | `storeUrl` | string \| `false` | Domma's store | Where a **self-hosted** site's Marketplace buys and downloads Tools (Browse). A Tool bought there is the site's to keep, with a term of updates that is renewed with a one-off payment; the licence keys and the payment claims are kept in `config/store.json` (out of git). `false` switches the store off, leaving Install from file. Not used on a site a Domma CMS Manager runs (it buys through its manager), nor on the manager itself unless `storeUrl` is set there. `DOMMA_STORE_URL` in the environment wins. See `server/services/storeClient.js` |
36
37
  | `outboundAllowPrivate` | boolean \| string[] | `false` | Webhooks (an Action's webhook step, a form's webhook) reach public addresses only: the name is looked up and every address must be public and not the server's own, the request is pinned to that address, redirects into private addresses are refused, and only ports 80 and 443 are used. A self-hosted site that sends webhooks inside its own network sets `true` to lift those rules for every request, or a list of host names, addresses and CIDR ranges (`["n8n.lan", "192.168.10.0/24", "fd00::/8"]`) to lift them for those only - a name passes if it is listed, or if every address it resolves to is. Ignored on a signed-only site (`requireSignedPlugins` / `DOMMA_SIGNED_ONLY=1`), so a hosted site's admin cannot open the host's network. Read fresh on every request. See `server/services/outbound.js` |
37
38
 
38
39
  ### Plugin toggles restart the server
@@ -825,6 +825,17 @@ These free plugins ship in the core package's `plugins/` directory and are good
825
825
  Analytics, effects, the theme switcher, Notes, Todo, Contacts and the demo viewer used to be plugins and are now part
826
826
  of the core CMS. Theme Roller and the other paid plugins are installed from the Marketplace.
827
827
 
828
+ ### Buying a Tool on a self-hosted site
829
+
830
+ A site you host yourself buys paid Tools from the Domma store, inside the admin: **Marketplace > Browse > Buy…**
831
+ opens the payment page in a new tab, and the Tool installs on the site as soon as the payment is through (restart to
832
+ switch it on). It is yours to keep - it carries on running offline whatever happens - and comes with a term of updates;
833
+ when that ends, **Renew…** buys another term with a one-off payment, and the version you have keeps working without
834
+ one. One licence covers one site address, so buy from the site's public address (set the **Site URL** in Site Settings),
835
+ not `localhost`. The licence key is emailed with the receipt, together with a link to the `.dcmsplugin` file for
836
+ Install from file. A Tool bought on the store's own Marketplace web page instead arrives as a key by email: on the Tool's row in Browse choose **Enter licence key…** and it installs. Free Tools in the store install with no key. `config/server.json` `storeUrl` (above) points the
837
+ store elsewhere or switches it off.
838
+
828
839
  ## Signed plugins and `requireSignedPlugins`
829
840
 
830
841
  Plugins from the marketplace are distributed as signed `.dcmsplugin` bundles, and the signature is verified at install.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.38.0",
3
+ "version": "1.39.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",
@@ -1,17 +1,22 @@
1
1
  /**
2
- * Plugin Marketplace API - the managed (fleet) path.
2
+ * Plugin Marketplace API.
3
3
  *
4
- * GET /api/plugins/marketplace - the catalogue as this site sees it
5
- * POST /api/plugins/marketplace/install - fetch a bundle and install it
6
- * DELETE /api/plugins/marketplace/:slug - uninstall (a paid plugin also tells the manager, for billing)
4
+ * GET /api/plugins/marketplace - the catalogue as this site sees it
5
+ * POST /api/plugins/marketplace/install - fetch a bundle and install it
6
+ * POST /api/plugins/marketplace/buy - self-hosted: start buying (or renewing) a Tool
7
+ * POST /api/plugins/marketplace/claim - self-hosted: has it been paid? (installs it when it has)
8
+ * DELETE /api/plugins/marketplace/purchases/:id - self-hosted: stop waiting for a purchase
9
+ * DELETE /api/plugins/marketplace/:slug - uninstall (a paid plugin also tells the manager, for billing)
7
10
  *
8
- * This is delivery path A: a site the manager forked, buying from the fleet's
9
- * own catalogue over loopback. The standalone path - buy, download one file,
10
- * Install from File - goes through `POST /plugins/install-upload` instead and
11
- * shares nothing with this but the installer.
12
- *
13
- * An unmanaged site has no MANAGER_URL, every route here answers "not
14
- * available", and the screen says so in terms that fit that customer.
11
+ * Two delivery paths behind the same screen:
12
+ * managed a site the manager forked buys from the fleet's own catalogue
13
+ * over loopback (managerClient.js) - rented, billed monthly.
14
+ * self-hosted any other site buys from the public Domma store (storeClient.js)
15
+ * - bought outright, with a term of updates. The claim secret and
16
+ * the licence keys stay on this server; the browser only ever sees
17
+ * the payment page's address.
18
+ * An owner instance (the manager itself) has neither, and the screen says so.
19
+ * Install from file (`POST /plugins/install-upload`) works everywhere.
15
20
  *
16
21
  * All routes require authentication + admin role.
17
22
  */
@@ -19,13 +24,74 @@ import {authenticate, requireAdmin} from '../../middleware/auth.js';
19
24
  import {fetchCatalogue, fetchPluginBundle, isManaged, releasePlugin, siteSlug} from '../../services/managerClient.js';
20
25
  import {cmsVersionShortfall, compareVersions, installedCmsVersion, installPlugin, uninstallPlugin} from '../../services/pluginInstaller.js';
21
26
  import {discoverPlugins} from '../../services/plugins.js';
27
+ import {readEnvelope, readManifestFromTarball} from '../../services/pluginEnvelope.js';
28
+ import {originOf, trustedOrigin} from '../../services/passwordReset.js';
29
+ import {getUserById} from '../../services/users.js';
30
+ import * as storeClient from '../../services/storeClient.js';
31
+ import {classifyEntitlement} from '../../services/pluginEntitlement.js';
32
+ import fs from 'node:fs/promises';
33
+ import path from 'node:path';
34
+
35
+ const SLUG = /^[a-z0-9][a-z0-9-_]{0,63}$/;
36
+ /** Entitlement states a plugin runs under (pluginEntitlement.mayLoad). */
37
+ const LOADS = new Set(['valid', 'grace', 'support-ended']);
38
+
39
+ /** Messages the installer raises deliberately - things an admin can act on. Anything else stays vague (it can carry a path). */
40
+ function installError(err) {
41
+ const safe = err.expose === true || [
42
+ 'Plugin already installed', 'Plugin signature invalid', 'Unknown public key',
43
+ 'Invalid plugin slug', 'Refusing to downgrade', 'Refusing to upgrade'
44
+ ].some(m => err.message.startsWith(m));
45
+ return safe ? err.message : 'Installation failed.';
46
+ }
47
+
48
+ /**
49
+ * Download a plugin from the store and install it. The file is the store's
50
+ * signed bundle; an unsigned one is refused here whatever it says, since nothing
51
+ * the store serves is unsigned.
52
+ */
53
+ async function installFromStore(slug, {version = null, update = false} = {}) {
54
+ const parts = readEnvelope(await storeClient.downloadPlugin(slug));
55
+ if (!parts.signature) throw Object.assign(new Error('The store sent an unsigned file - nothing was installed.'), {expose: true});
56
+ const manifest = readManifestFromTarball(parts.tarball);
57
+ if (manifest?.name !== slug) throw Object.assign(new Error('The store sent a different plugin - nothing was installed.'), {expose: true});
58
+ if (version && manifest.version !== version) {
59
+ throw Object.assign(new Error(`The store now has ${slug} ${manifest.version} - reload the Marketplace and try again.`), {expose: true});
60
+ }
61
+ const result = await installPlugin(slug, {
62
+ tarball: parts.tarball, signature: parts.signature, publicKeyId: 'marketplace-1',
63
+ entitlement: parts.entitlement, allowUpgrade: update === true
64
+ });
65
+ return {action: result?.action ?? 'install', from: result?.from ?? null, version: result?.version ?? manifest.version};
66
+ }
67
+
68
+ /**
69
+ * After a renewal: the store's fresh entitlement for the version installed, written beside it - only when it is
70
+ * that same version and the entitlement verifies. True when written.
71
+ */
72
+ async function refreshEntitlement(slug, installedVersion) {
73
+ const parts = readEnvelope(await storeClient.downloadPlugin(slug));
74
+ const manifest = readManifestFromTarball(parts.tarball);
75
+ if (!parts.entitlement || manifest?.name !== slug || manifest.version !== installedVersion) return false;
76
+ if (classifyEntitlement(slug, parts.entitlement).state !== 'valid') return false;
77
+ await fs.writeFile(path.resolve('plugins', slug, '.entitlement.json'), JSON.stringify(parts.entitlement, null, 2) + '\n', 'utf8');
78
+ return true;
79
+ }
80
+
81
+ /** This site's public address, as the store will know it. */
82
+ async function siteAddress(request) {
83
+ return (await trustedOrigin(originOf(request)).catch(() => '')) || originOf(request);
84
+ }
22
85
 
23
86
  export async function pluginMarketplaceRoutes(fastify) {
24
87
  const adminOnly = { preHandler: [authenticate, requireAdmin] };
25
88
 
26
89
  // GET /plugins/marketplace
27
- fastify.get('/plugins/marketplace', adminOnly, async (_request, reply) => {
28
- if (!isManaged()) return reply.send({ available: false, catalogue: [] });
90
+ fastify.get('/plugins/marketplace', adminOnly, async (request, reply) => {
91
+ if (!isManaged()) {
92
+ if (!storeClient.storeOpen()) return reply.send({ available: false, mode: storeClient.isOwnerInstance() ? 'owner' : 'none', catalogue: [] });
93
+ return reply.send(await storeCatalogue(request));
94
+ }
29
95
 
30
96
  const catalogue = await fetchCatalogue();
31
97
 
@@ -66,7 +132,14 @@ export async function pluginMarketplaceRoutes(fastify) {
66
132
  return reply.code(400).send({ error: 'Invalid version format. Expected semver (e.g. 1.0.0).' });
67
133
  }
68
134
  if (!isManaged()) {
69
- return reply.code(503).send({ error: 'This site is not managed - install from a file instead.' });
135
+ if (!storeClient.storeOpen()) return reply.code(503).send({ error: 'This site has no store - install from a file instead.' });
136
+ try {
137
+ const r = await installFromStore(slug, { version, update: update === true });
138
+ return reply.send({ success: true, name: slug, ...r, restartRequired: true });
139
+ } catch (err) {
140
+ fastify.log.warn({ err }, '[marketplace] store install failed');
141
+ return reply.code(err instanceof storeClient.StoreError ? err.status : 400).send({ error: installError(err), code: err.code || null });
142
+ }
70
143
  }
71
144
 
72
145
  let bundle;
@@ -110,14 +183,171 @@ export async function pluginMarketplaceRoutes(fastify) {
110
183
  // `expose` marks a refusal written for the admin (a plugin that needs
111
184
  // a newer CMS, naming both versions) - it used to arrive here as a
112
185
  // bare "Installation failed." while Install from file showed it.
113
- const safe = err.expose === true || [
114
- 'Plugin already installed', 'Plugin signature invalid', 'Unknown public key',
115
- 'Invalid plugin slug', 'Refusing to downgrade', 'Refusing to upgrade'
116
- ].some(m => err.message.startsWith(m));
117
- return reply.code(400).send({ error: safe ? err.message : 'Installation failed.' });
186
+ return reply.code(400).send({ error: installError(err) });
187
+ }
188
+ });
189
+
190
+ // ── The self-hosted store ─────────────────────────────────────────────
191
+
192
+ /** The store's catalogue in the shape the screen already reads, plus where purchases stand. */
193
+ async function storeCatalogue(request) {
194
+ const plugins = await discoverPlugins();
195
+ const installed = new Map(plugins.map(m => [m.name, m.version]));
196
+ const cmsVersion = installedCmsVersion();
197
+ const site = await siteAddress(request);
198
+ // Connected to Domma: pick up what was bought for this site since last time (a failure just waits for next time).
199
+ await storeClient.syncConnection().catch(() => {});
200
+ let answer;
201
+ try {
202
+ answer = await storeClient.fetchStoreCatalogue(site, storeClient.heldKeys([...installed.keys()]));
203
+ } catch (err) {
204
+ return { available: true, mode: 'store', failed: err.message, site: null, catalogue: [], pending: [], connection: storeClient.connectionView() };
205
+ }
206
+ const pending = storeClient.pendingPurchases().map(p => ({ id: p.id, slug: p.slug, kind: p.kind, startedAt: p.startedAt }));
207
+ const catalogue = (Array.isArray(answer.plugins) ? answer.plugins : []).filter(e => SLUG.test(e?.slug || '')).map(e => {
208
+ const have = installed.get(e.slug);
209
+ const owned = e.tier !== 'paid' || e.owned === true;
210
+ return {
211
+ ...e,
212
+ store: true,
213
+ entitled: owned && e.updates !== false,
214
+ // The words the screen already has: licensed, support ended, or not bought.
215
+ licenceStatus: e.tier !== 'paid' ? null : e.owned ? (e.updates ? 'active' : 'support-ended') : 'none',
216
+ installed: have !== undefined,
217
+ installedVersion: have ?? null,
218
+ // Already licensed here by other means (an owner licence, a file bought by email): nothing to buy.
219
+ licensedHere: have !== undefined && e.tier === 'paid' && LOADS.has(classifyEntitlement(e.slug).state),
220
+ updatable: have !== undefined && compareVersions(e.version, have) > 0,
221
+ needsCms: cmsVersionShortfall({ name: e.slug, displayName: e.displayName, minCmsVersion: e.minCmsVersion }, cmsVersion),
222
+ pending: pending.find(p => p.slug === e.slug)?.id ?? null
223
+ };
224
+ });
225
+ return { available: true, mode: 'store', site: answer.site || null, siteError: answer.siteError || null, cmsVersion, catalogue, pending, connection: storeClient.connectionView() };
226
+ }
227
+
228
+ // POST /plugins/marketplace/buy {slug} -> {id, checkoutUrl}
229
+ fastify.post('/plugins/marketplace/buy', adminOnly, async (request, reply) => {
230
+ const slug = request.body?.slug;
231
+ if (!SLUG.test(String(slug || ''))) return reply.code(400).send({ error: 'Invalid plugin slug.' });
232
+ if (isManaged() || !storeClient.storeOpen()) return reply.code(409).send({ error: 'This site does not buy from the Domma store.' });
233
+ const user = await getUserById(request.user?.id);
234
+ if (!user?.email) return reply.code(400).send({ error: 'Your account has no email address for the receipt and licence key - add one under My profile.' });
235
+ try {
236
+ const out = await storeClient.startPurchase({ site: await siteAddress(request), slug, email: user.email, name: user.name || user.displayName || '' });
237
+ return reply.send(out);
238
+ } catch (err) {
239
+ return reply.code(err instanceof storeClient.StoreError ? err.status : 500).send({ error: err instanceof storeClient.StoreError ? err.message : 'The purchase could not be started.' });
118
240
  }
119
241
  });
120
242
 
243
+ // POST /plugins/marketplace/claim {id} -> {status, slug, installed?}
244
+ // Paid for a first purchase: installed here and then (the admin restarts to switch it on).
245
+ fastify.post('/plugins/marketplace/claim', adminOnly, async (request, reply) => {
246
+ const id = String(request.body?.id || '');
247
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return reply.code(400).send({ error: 'Which purchase?' });
248
+ // One claim at a time: two tabs asking at once must not both install it.
249
+ const run = claimChain.then(() => claimAndInstall(id), () => claimAndInstall(id));
250
+ claimChain = run.catch(() => {});
251
+ const r = await run;
252
+ return reply.code(r.code || 200).send(r.body);
253
+ });
254
+
255
+ let claimChain = Promise.resolve();
256
+ async function claimAndInstall(id) {
257
+ let out;
258
+ try {
259
+ out = await storeClient.claimPurchase(id);
260
+ } catch (err) {
261
+ return { code: err instanceof storeClient.StoreError ? err.status : 500, body: { error: err instanceof storeClient.StoreError ? err.message : 'The purchase could not be checked.' } };
262
+ }
263
+ if (out.status !== 'paid') return { body: out };
264
+ const main = await installClaimed(out);
265
+ // What came free with it (the MongoDB Adapter with Email): installed beside it, the same way.
266
+ const included = [];
267
+ for (const slug of out.included || []) {
268
+ const r = await installClaimed({ ...out, slug, kind: out.kind, included: [] });
269
+ included.push({ slug, installed: r.body.installed === true, installError: r.body.installError || null });
270
+ }
271
+ return { code: main.code, body: { ...main.body, included } };
272
+ }
273
+
274
+ /** One claimed Tool onto this site: installed, or its licence written beside a copy already here. */
275
+ async function installClaimed(out) {
276
+ const here = (await discoverPlugins()).find(m => m.name === out.slug);
277
+ if (here) {
278
+ // Already on disk (a renewal, or a copy that was here before it was bought): the licence file the purchase
279
+ // brings is written beside it - at once when the store has that same version; a newer one waits for Update.
280
+ const refreshed = await refreshEntitlement(out.slug, here.version).catch(() => false);
281
+ if (refreshed || out.kind === 'renew') return { body: { ...out, installed: true, refreshed } };
282
+ // A first purchase over an older copy: bring it up to the store's version, which carries the licence.
283
+ try {
284
+ const r = await installFromStore(out.slug, { update: true });
285
+ return { body: { ...out, installed: true, refreshed: true, ...r, restartRequired: true } };
286
+ } catch (err) {
287
+ fastify.log.warn({ err }, '[marketplace] update after purchase failed');
288
+ return { body: { ...out, installed: true, refreshed: false, installError: installError(err) } };
289
+ }
290
+ }
291
+ if (out.kind === 'renew') return { body: { ...out, installed: false } };
292
+ try {
293
+ const r = await installFromStore(out.slug);
294
+ return { body: { ...out, installed: true, ...r, restartRequired: true } };
295
+ } catch (err) {
296
+ fastify.log.warn({ err }, '[marketplace] install after purchase failed');
297
+ // Paid and the key kept: Install on the Browse tab tries again, and the email has the file.
298
+ return { body: { ...out, installed: false, installError: installError(err) } };
299
+ }
300
+ }
301
+
302
+ // POST /plugins/marketplace/key {slug, key} -> {owned}
303
+ // A key bought on the public /marketplace page (or found in the email): kept, then checked with the store.
304
+ fastify.post('/plugins/marketplace/key', adminOnly, async (request, reply) => {
305
+ if (isManaged() || !storeClient.storeOpen()) return reply.code(409).send({ error: 'This site does not buy from the Domma store.' });
306
+ const slug = String(request.body?.slug || '');
307
+ try {
308
+ const before = storeClient.readState().keys[slug];
309
+ await storeClient.saveKey(slug, request.body?.key);
310
+ const answer = await storeClient.fetchStoreCatalogue(await siteAddress(request), storeClient.heldKeys([slug]));
311
+ const row = (answer.plugins || []).find(e => e.slug === slug);
312
+ if (!row?.owned) {
313
+ // Not this site's key for this Tool: put back what was there.
314
+ await storeClient.changeState(s => { if (before) s.keys[slug] = before; else delete s.keys[slug]; });
315
+ return reply.code(400).send({ error: answer.siteError || `That key is not a licence for this Tool on ${answer.site || 'this site'}. A licence is for the address it was bought for.` });
316
+ }
317
+ return reply.send({ owned: true, updates: row.updates === true });
318
+ } catch (err) {
319
+ return reply.code(err instanceof storeClient.StoreError ? err.status : 500).send({ error: err instanceof storeClient.StoreError ? err.message : 'The key could not be checked.' });
320
+ }
321
+ });
322
+
323
+ // Connect to Domma: POST {email?} starts it (a link goes to that email), POST /check asks, DELETE disconnects.
324
+ fastify.post('/plugins/marketplace/connect', adminOnly, async (request, reply) => {
325
+ if (isManaged() || !storeClient.storeOpen()) return reply.code(409).send({ error: 'This site does not buy from the Domma store.' });
326
+ const email = String(request.body?.email || '').trim() || (await getUserById(request.user?.id))?.email || '';
327
+ try {
328
+ return reply.send({ connection: await storeClient.startConnection(await siteAddress(request), email) });
329
+ } catch (err) {
330
+ return reply.code(err instanceof storeClient.StoreError ? err.status : 500).send({ error: err instanceof storeClient.StoreError ? err.message : 'Could not connect.' });
331
+ }
332
+ });
333
+ fastify.post('/plugins/marketplace/connect/check', adminOnly, async (_request, reply) => {
334
+ try {
335
+ return reply.send({ connection: await storeClient.syncConnection() });
336
+ } catch (err) {
337
+ return reply.code(err instanceof storeClient.StoreError ? err.status : 500).send({ error: err instanceof storeClient.StoreError ? err.message : 'Could not check.' });
338
+ }
339
+ });
340
+ fastify.delete('/plugins/marketplace/connect', adminOnly, async (_request, reply) => {
341
+ await storeClient.forgetConnection();
342
+ return reply.send({ success: true });
343
+ });
344
+
345
+ // DELETE /plugins/marketplace/purchases/:id - stop waiting (nothing is cancelled at the store).
346
+ fastify.delete('/plugins/marketplace/purchases/:id', adminOnly, async (request, reply) => {
347
+ await storeClient.dropPurchase(String(request.params.id || ''));
348
+ return reply.send({ success: true });
349
+ });
350
+
121
351
  // DELETE /plugins/marketplace/:slug
122
352
  fastify.delete('/plugins/marketplace/:slug', adminOnly, async (request, reply) => {
123
353
  const { slug } = request.params;
@@ -332,6 +332,8 @@ export function buildGitignore({sitePlugins = [], pluginContent = {}, sitePublic
332
332
  // Each admin's own sidebar Frequent list (keyed by user id).
333
333
  '/content/sidebar/frequent/',
334
334
  '/config/connections.json*',
335
+ // The Domma store's licence keys and payment claims (services/storeClient.js).
336
+ '/config/store.json*',
335
337
  '/config/keys/',
336
338
  '/plugins/*/data/*.jsonl',
337
339
  '/plugins/*/backups/',
@@ -0,0 +1,333 @@
1
+ /**
2
+ * The Domma store - how a SELF-HOSTED site buys and installs Tools.
3
+ *
4
+ * A site a manager runs (managerClient.js) gets its catalogue over the fleet
5
+ * token. A self-hosted one has no token and no manager; its Marketplace asks the
6
+ * public store instead (Domma CMS Manager's site-manager `store/*` routes):
7
+ *
8
+ * catalogue what is on sale, priced for self-hosting, and - for the licence
9
+ * keys this site holds - whether it owns each and has updates
10
+ * checkout a Tool for this site's address -> a payment page and a CLAIM
11
+ * secret, which is kept here and never shown to the browser
12
+ * claim once paid, the claim returns the licence key
13
+ * download the signed .dcmsplugin for a key (free plugins need none), which
14
+ * the ordinary installer then checks and installs
15
+ *
16
+ * Bought outright: the plugin keeps running offline for good; support (newer
17
+ * versions) lasts a term and is renewed with a one-off payment. One licence per
18
+ * site address.
19
+ *
20
+ * Where: `DOMMA_STORE_URL` in the environment, else server.json `storeUrl`, else
21
+ * Domma's own. `storeUrl: false` switches the store off. It is not offered on a
22
+ * managed site (it buys through its manager), nor on an owner instance (a
23
+ * wildcard entitlement - the manager itself, where every plugin is written)
24
+ * unless a store is named there on purpose.
25
+ *
26
+ * Kept in `config/store.json`: the keys this site was given and the purchases
27
+ * still waiting for payment. A key also lives in each installed plugin's
28
+ * `.entitlement.json` (`licenceKey`), which is read too.
29
+ *
30
+ * @module server/services/storeClient
31
+ */
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+ import {getConfig} from '../config.js';
35
+ import {isManaged} from './managerClient.js';
36
+ import {classifyEntitlement, readEntitlement} from './pluginEntitlement.js';
37
+
38
+ export const DEFAULT_STORE_URL = 'https://dcm.dommajs.org/api/plugins/site-manager/store';
39
+ /** A purchase not paid for after this long is let go (the store's own claim lasts 14 days). */
40
+ export const PENDING_DAYS = 14;
41
+ const SLUG = /^[a-z0-9][a-z0-9-_]{0,63}$/;
42
+ const TIMEOUT = 15_000;
43
+
44
+ /** The store's address, or '' when it is switched off. */
45
+ export function storeUrl() {
46
+ const env = process.env.DOMMA_STORE_URL;
47
+ if (env !== undefined) return env === '' || env === 'false' ? '' : (safeStoreUrl(env) || '');
48
+ let configured;
49
+ try { configured = getConfig('server')?.storeUrl; } catch { configured = undefined; }
50
+ if (configured === false) return '';
51
+ if (typeof configured === 'string') return safeStoreUrl(configured) || '';
52
+ return DEFAULT_STORE_URL;
53
+ }
54
+
55
+ /**
56
+ * HTTPS only - the claim secret and licence keys travel in these requests. Plain HTTP is allowed to this machine
57
+ * alone (a store on loopback, as the tests run one). Anything else switches the store off rather than leak.
58
+ */
59
+ export function safeStoreUrl(raw) {
60
+ let u;
61
+ try { u = new URL(String(raw).trim()); } catch { return null; }
62
+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
63
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) return null;
64
+ return `${u.origin}${u.pathname.replace(/\/+$/, '')}`;
65
+ }
66
+
67
+ /** An owner instance: a verified wildcard entitlement. Every plugin is already its own. */
68
+ export function isOwnerInstance() {
69
+ try {
70
+ const e = readEntitlement('__store-owner-probe__');
71
+ return e?.slug === '*' && ['valid', 'grace', 'support-ended'].includes(classifyEntitlement('__store-owner-probe__', e).state);
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /** Was a store named on purpose (server.json `storeUrl` or `DOMMA_STORE_URL`), rather than the default? */
78
+ export function storeNamed() {
79
+ if (process.env.DOMMA_STORE_URL) return true;
80
+ try { return typeof getConfig('server')?.storeUrl === 'string'; } catch { return false; }
81
+ }
82
+
83
+ /**
84
+ * Does this site buy from the store? Never a managed site. An owner instance only when a store is named on
85
+ * purpose - that is how the manager's own admin shows the store screen for a look at it.
86
+ */
87
+ export function storeOpen() {
88
+ return !isManaged() && Boolean(storeUrl()) && (!isOwnerInstance() || storeNamed());
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // What this site holds - config/store.json
93
+ // ---------------------------------------------------------------------------
94
+
95
+ const STATE_FILE = () => path.resolve('config', 'store.json');
96
+
97
+ export function readState() {
98
+ try {
99
+ const raw = JSON.parse(fs.readFileSync(STATE_FILE(), 'utf8'));
100
+ return {
101
+ keys: raw?.keys && typeof raw.keys === 'object' ? raw.keys : {},
102
+ pending: Array.isArray(raw?.pending) ? raw.pending : [],
103
+ connection: raw?.connection && typeof raw.connection === 'object' ? raw.connection : null
104
+ };
105
+ } catch {
106
+ return {keys: {}, pending: [], connection: null};
107
+ }
108
+ }
109
+
110
+ function writeState(state) {
111
+ const file = STATE_FILE();
112
+ const tmp = `${file}.tmp-${process.pid}`;
113
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n', {mode: 0o600});
114
+ fs.renameSync(tmp, file);
115
+ }
116
+
117
+ let chain = Promise.resolve();
118
+ /** Every change to config/store.json, one at a time. */
119
+ export function changeState(fn) {
120
+ const run = chain.then(() => {
121
+ const state = readState();
122
+ const out = fn(state);
123
+ writeState(state);
124
+ return out;
125
+ });
126
+ chain = run.catch(() => {});
127
+ return run;
128
+ }
129
+
130
+ /**
131
+ * The licence keys this site holds, by plugin: config/store.json first, then
132
+ * what each installed plugin's entitlement carries (a plugin installed from a
133
+ * file bought by email).
134
+ */
135
+ export function heldKeys(installedSlugs = []) {
136
+ const keys = {...readState().keys};
137
+ for (const slug of installedSlugs) {
138
+ if (keys[slug] || !SLUG.test(slug)) continue;
139
+ try {
140
+ const own = JSON.parse(fs.readFileSync(path.resolve('plugins', slug, '.entitlement.json'), 'utf8'));
141
+ if (own?.slug === slug && typeof own.licenceKey === 'string') keys[slug] = own.licenceKey;
142
+ } catch { /* none */ }
143
+ }
144
+ return keys;
145
+ }
146
+
147
+ /** Purchases still waiting, minus any past PENDING_DAYS. */
148
+ export function pendingPurchases(now = Date.now()) {
149
+ return readState().pending.filter((p) => now - Date.parse(p.startedAt) < PENDING_DAYS * 86_400_000);
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // Talking to the store
154
+ // ---------------------------------------------------------------------------
155
+
156
+ /** A refusal from the store, carried to the admin as its own words. */
157
+ export class StoreError extends Error {
158
+ constructor(message, status = 502, code = null) {
159
+ super(message);
160
+ this.status = status;
161
+ this.code = code;
162
+ this.expose = true;
163
+ }
164
+ }
165
+
166
+ async function call(pathname, body) {
167
+ const base = storeUrl();
168
+ if (!base) throw new StoreError('The store is switched off on this site.', 503);
169
+ let res;
170
+ try {
171
+ res = await fetch(`${base}${pathname}`, {
172
+ method: 'POST',
173
+ headers: {'Content-Type': 'application/json', Accept: 'application/json'},
174
+ body: JSON.stringify(body),
175
+ signal: AbortSignal.timeout(TIMEOUT)
176
+ });
177
+ } catch (err) {
178
+ console.warn(`[storeClient] ${pathname}: ${err.message}`);
179
+ throw new StoreError('The Domma store could not be reached. Check this server can make outgoing HTTPS requests, then try again.', 503);
180
+ }
181
+ let data = null;
182
+ try { data = await res.json(); } catch { /* not JSON */ }
183
+ if (!res.ok) {
184
+ throw new StoreError(typeof data?.error === 'string' ? data.error.slice(0, 400) : `The store answered ${res.status}.`, res.status >= 500 ? 502 : res.status, data?.code || null);
185
+ }
186
+ return data || {};
187
+ }
188
+
189
+ /** The store's catalogue for this site (`site` = its public origin). */
190
+ export function fetchStoreCatalogue(site, keys) {
191
+ return call('/catalogue', {site, keys});
192
+ }
193
+
194
+ /**
195
+ * Start buying (or renewing) a Tool. The claim secret is kept here; the browser
196
+ * is given only the payment page.
197
+ *
198
+ * @returns {Promise<{id: string, checkoutUrl: string, kind: string, price: number, currency: string}>}
199
+ */
200
+ export async function startPurchase({site, slug, email, name}) {
201
+ const key = readState().keys[slug] || heldKeys([slug])[slug] || '';
202
+ const out = await call('/checkout', {site, slug, email, name, ...(key && {key})});
203
+ if (typeof out.id !== 'string' || typeof out.claim !== 'string' || typeof out.checkoutUrl !== 'string' || !/^https:\/\//i.test(out.checkoutUrl)) {
204
+ throw new StoreError('The store gave an answer this site does not understand.', 502);
205
+ }
206
+ await changeState((s) => {
207
+ // An earlier checkout for the same Tool stays: if its tab is paid after all, it can still be claimed
208
+ // (the store refunds a second payment for a site that already has it, and hands either claim the key).
209
+ s.pending.push({id: out.id, claim: out.claim, slug, kind: out.kind, startedAt: new Date().toISOString()});
210
+ });
211
+ return {id: out.id, checkoutUrl: out.checkoutUrl, kind: out.kind, price: out.price, currency: out.currency};
212
+ }
213
+
214
+ /**
215
+ * Has a purchase been paid? Paid: the key is kept and the purchase leaves the
216
+ * waiting list. `{status, slug, kind}`; status is the store's (pending, paid,
217
+ * failed, refunded, revoked, expired) or 'unknown' for a purchase this site
218
+ * does not hold.
219
+ */
220
+ export async function claimPurchase(id) {
221
+ const p = readState().pending.find((x) => x.id === id);
222
+ if (!p) return {status: 'unknown'};
223
+ const out = await call('/claim', {id: p.id, claim: p.claim});
224
+ if (out.status === 'paid' && typeof out.licenceKey === 'string') {
225
+ await changeState((s) => {
226
+ s.keys[p.slug] = out.licenceKey;
227
+ // Given free with it (the MongoDB Adapter with Email): kept the same way.
228
+ for (const inc of Array.isArray(out.included) ? out.included : []) {
229
+ if (SLUG.test(String(inc?.slug || '')) && KEY_FORMAT.test(String(inc?.licenceKey || ''))) s.keys[inc.slug] = inc.licenceKey;
230
+ }
231
+ s.pending = s.pending.filter((x) => x.id !== id);
232
+ });
233
+ } else if (['failed', 'refunded', 'revoked', 'expired'].includes(out.status)) {
234
+ await changeState((s) => { s.pending = s.pending.filter((x) => x.id !== id); });
235
+ }
236
+ return {status: out.status, slug: p.slug, kind: p.kind,
237
+ included: (Array.isArray(out.included) ? out.included : []).map((i) => i?.slug).filter((x) => SLUG.test(String(x || '')))};
238
+ }
239
+
240
+ /** A licence key typed in (bought on the public /marketplace page, or from the email): kept for that plugin. */
241
+ export const KEY_FORMAT = /^DOMMA-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}$/;
242
+ export function saveKey(slug, key) {
243
+ const k = String(key || '').trim().toUpperCase();
244
+ if (!SLUG.test(String(slug || '')) || !KEY_FORMAT.test(k)) throw new StoreError('That does not look like a licence key - it is like DOMMA-1A2B-3C4D-5E6F.', 400);
245
+ return changeState((s) => { s.keys[slug] = k; });
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Connect to Domma - the licences bought for this site's address with one email, picked up by themselves
250
+ // ---------------------------------------------------------------------------
251
+
252
+ /** What the screen may know about the connection: never its secret. */
253
+ export function connectionView(state = readState()) {
254
+ const c = state.connection;
255
+ return c ? {status: c.status, email: c.email, site: c.site || null, startedAt: c.startedAt || null} : null;
256
+ }
257
+
258
+ /** Ask to connect: the store emails `email` a link to say yes. The secret stays here. */
259
+ export async function startConnection(site, email) {
260
+ const out = await call('/connect/start', {site, email});
261
+ if (typeof out.id !== 'string' || typeof out.secret !== 'string') throw new StoreError('The store gave an answer this site does not understand.', 502);
262
+ await changeState((s) => { s.connection = {id: out.id, secret: out.secret, email: out.email || email, site: out.site || null, status: 'pending', startedAt: new Date().toISOString()}; });
263
+ return connectionView();
264
+ }
265
+
266
+ /**
267
+ * Bring the connection up to date: once approved, every key the store hands over is kept (a key typed in for
268
+ * another Tool is left alone). A connection the store no longer knows, or one never approved in time, is dropped.
269
+ */
270
+ export async function syncConnection() {
271
+ const c = readState().connection;
272
+ if (!c) return null;
273
+ let out;
274
+ try {
275
+ out = await call('/connect/keys', {id: c.id, secret: c.secret});
276
+ } catch (err) {
277
+ if (err.status === 404) { await changeState((s) => { s.connection = null; }); return null; }
278
+ throw err;
279
+ }
280
+ await changeState((s) => {
281
+ if (!s.connection || s.connection.id !== c.id) return;
282
+ if (out.status === 'connected') {
283
+ s.connection.status = 'connected';
284
+ for (const [slug, key] of Object.entries(out.keys || {})) {
285
+ if (SLUG.test(slug) && KEY_FORMAT.test(String(key))) s.keys[slug] = String(key);
286
+ }
287
+ } else if (out.status === 'expired') {
288
+ s.connection = null;
289
+ }
290
+ });
291
+ return connectionView();
292
+ }
293
+
294
+ /** Disconnect: the store forgets it too (the keys already here stay - they are this site's). */
295
+ export async function forgetConnection() {
296
+ const c = readState().connection;
297
+ if (!c) return;
298
+ try { await call('/connect/forget', {id: c.id, secret: c.secret}); } catch { /* gone there already */ }
299
+ await changeState((s) => { s.connection = null; });
300
+ }
301
+
302
+ /** Forget a purchase this site is waiting for (the person gave up on it). */
303
+ export function dropPurchase(id) {
304
+ return changeState((s) => { s.pending = s.pending.filter((x) => x.id !== id); });
305
+ }
306
+
307
+ /**
308
+ * The signed .dcmsplugin for a plugin - free, or for the key this site holds.
309
+ *
310
+ * @returns {Promise<Buffer>}
311
+ */
312
+ export async function downloadPlugin(slug) {
313
+ if (!SLUG.test(slug)) throw new StoreError('Invalid plugin slug.', 400);
314
+ const base = storeUrl();
315
+ if (!base) throw new StoreError('The store is switched off on this site.', 503);
316
+ const key = heldKeys([slug])[slug] || '';
317
+ const url = `${base.replace(/\/store$/, '')}/plugins/${encodeURIComponent(slug)}/download${key ? `?licence=${encodeURIComponent(key)}` : ''}`;
318
+ let res;
319
+ try {
320
+ res = await fetch(url, {signal: AbortSignal.timeout(60_000)});
321
+ } catch (err) {
322
+ console.warn(`[storeClient] download ${slug}: ${err.message}`);
323
+ throw new StoreError('The Domma store could not be reached. Check this server can make outgoing HTTPS requests, then try again.', 503);
324
+ }
325
+ if (!res.ok) {
326
+ let data = null;
327
+ try { data = await res.json(); } catch { /* not JSON */ }
328
+ throw new StoreError(typeof data?.error === 'string' ? data.error.slice(0, 400) : `The store answered ${res.status}.`, res.status >= 500 ? 502 : 403, data?.code || null);
329
+ }
330
+ const buf = Buffer.from(await res.arrayBuffer());
331
+ if (buf.length > 64 * 1024 * 1024) throw new StoreError('That download is larger than any plugin should be.', 502);
332
+ return buf;
333
+ }