domma-cms 1.44.1 → 1.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/CLAUDE.md +5 -2
- package/admin/js/api.js +1 -1
- package/admin/js/lib/plugins-arrange.js +2 -2
- package/admin/js/templates/plugins.html +6 -0
- package/admin/js/views/plugins.js +20 -10
- package/docs/plugin-development.md +1 -0
- package/package.json +1 -1
- package/public/css/site.css +1 -1
- package/server/routes/api/plugin-marketplace.js +43 -4
- package/server/server.js +4 -0
- package/server/services/notification-sources.js +5 -2
- package/server/services/pluginEntitlement.js +46 -2
- package/server/services/pluginInstaller.js +50 -0
- package/server/services/plugins.js +9 -0
- package/server/services/request-log.js +3 -1
- package/server/services/storeClient.js +65 -5
- package/server/templates/page.html +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.46.0] - 2026-11-08
|
|
4
|
+
|
|
5
|
+
- A plugin whose manifest says `hostedOnly: true` (Site Builder and Tool Builder) runs only where Domma hosts the site. On a self-hosted site it is refused at install, with a plain message, and does not load (Marketplace chip "Hosted sites only"). Managed sites and the manager are unchanged.
|
|
6
|
+
- **EU VAT at checkout, when the Domma store asks for it.** When the store's catalogue carries `vat` (Domma charges EU VAT by country, a switch on its side that stays off until it is registered), Marketplace > Buy asks for the buyer's country and an optional EU VAT number. They go to the store with the address the admin bought from, which the store keeps as the tax evidence. A VAT note from the store (a VAT number VIES did not confirm) is shown. While the store asks nothing, nothing changes and nothing new is sent.
|
|
7
|
+
- **The Pro bundle in a self-hosted site's Marketplace.** When the Domma store sells it, Browse shows one card above the Tools: every Pro Tool for this site at one price, which of them the site already owns (not charged again), which are installed, and Buy the bundle… or Renew…. Paid for, it installs every Tool it brings that is not here yet (switched off) and keeps each one's key. A bundle the site holds also hands over the keys of Tools added to it later.
|
|
8
|
+
|
|
9
|
+
## [1.45.0] - 2026-11-08
|
|
10
|
+
|
|
11
|
+
- Request logs hide `hub.verify_token`, the verify token Meta (WhatsApp, Facebook) sends when it checks a webhook (`server/services/request-log.js`).
|
|
12
|
+
- An outline button on a dark hero uses the hero's light text colour, so it can be read (it took the theme's primary, which can be nearly as dark as the hero). The new starter home page's "Browse Tools" button was the case in point.
|
|
13
|
+
- **A bought Tool's updates end when its support does, on the site too.** The store already refused newer downloads after support ended, but a newer copy dropped in by hand still ran. Once a perpetual licence's support has ended, a version above what the licence covers (its `versions`, `<=X.Y.Z`, written with each download) is now refused at install and upgrade, with the old version left in place, and does not load if it is already there (Marketplace chip "Renew to run", plus a critical licence notification). The version the licence covers keeps running for good, and during support any version runs as before.
|
|
14
|
+
- **A self-hosted site proves it is the address its licence is for.** Checkout, claim and every paid download from the Domma store now carry a short-lived proof token, and the site answers it at `/.well-known/domma-store/<token>` (ten minutes, no sign-in, only while the store is on). The store fetches that back from the licensed address, so a key bought for a site the buyer does not run, or copied to another site, cannot be used. Needs the matching Domma CMS Manager release, which this must ship before.
|
|
15
|
+
|
|
3
16
|
## [1.44.1] - 2026-11-08
|
|
4
17
|
|
|
5
18
|
- **A shortcode inside an effect, tabs or an accordion keeps its settings.** `[reveal]`, `[ambient]` and the other effects, `[tabs]`, `[accordion]`, `[carousel]` and the cards render their body before the shortcodes inside it run, and that turned the inner tag's quotes into `"` and its web addresses into links. So `[hero size="md"]` inside `[reveal]` got the class `hero-"md"`, `[embed url="https://…"]` said "Invalid embed URL", and `[spacer size="24" /]` was drawn at the default 40px. Tags with settings are now held back from that pass and put back as written (`markedBody()` in markdown.js). Effects also escape their own `data-fx-*` values.
|
package/CLAUDE.md
CHANGED
|
@@ -199,8 +199,11 @@ numerically (1.10.0 > 1.2.0). Unsigned installs and downgrades each need their o
|
|
|
199
199
|
`buy` starts a checkout and keeps the CLAIM secret in `config/store.json` (0600, gitignored, with the licence keys) -
|
|
200
200
|
the browser only ever gets the payment URL; `claim` swaps it for the key once paid and installs through
|
|
201
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.
|
|
202
|
+
is the licence's and the store refuses a NEWER version after it (`mayDownload` on the manager), and so does this engine: once support has ended, a version above the entitlement's `versions` ceiling (`<=X.Y.Z`, minted per download) neither installs nor loads (`coveredVerdict()` in pluginEntitlement.js, state `not-covered`); one licence per site
|
|
203
|
+
address (`self:<host>`), so localhost/IP/.local addresses are refused there. The site proves it IS that address:
|
|
204
|
+
checkout, claim and every paid download carry a fresh `proof` token (`newProof()`, ten minutes), and the store fetches
|
|
205
|
+
`/.well-known/domma-store/<token>` back from the licence's host (`storeProofRoutes`, no auth, only while `storeOpen()`),
|
|
206
|
+
so a key bought for an address the buyer does not run, or copied to another site, downloads nothing.
|
|
204
207
|
|
|
205
208
|
**Signed-only sites (hosted) - `server/services/codePolicy.js`.** `signedOnly()` is true when the environment has
|
|
206
209
|
`DOMMA_SIGNED_ONLY=1` (the Manager sets it on sites it forks, after the site's .env), when server.json had
|
package/admin/js/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
+
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,o={})=>t("/plugins/marketplace/buy",{method:"POST",body:JSON.stringify({slug:e,...o})}),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 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
|
-
`)||
|
|
1
|
+
export const FILTERS=["all","on","off","attention"],BROWSE_FILTERS=["all","installed","available","updates"],BLOCKING=new Set(["expired","unlicensed","not-covered","hosted-only"]);const h={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"},"not-covered":{text:"Renew to run",tone:"danger",title:"This version came out after the licence's updates ended - renew it, or go back to the version it covers"},"hosted-only":{text:"Hosted sites only",tone:"danger",title:"This Tool runs only on sites Domma hosts - it does not run on a self-hosted site"}};export function compareVersions(e,t){const r=a=>String(a??"").split(".").map(s=>parseInt(s,10)||0),n=r(e),o=r(t);for(let a=0;a<Math.max(n.length,o.length);a++){const s=(n[a]??0)-(o[a]??0);if(s)return s>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,t){const r=t?.get?.(e.name);return r&&compareVersions(r,e.version)>0?r:""}export function needsAttention(e,t){return pluginStatus(e).key==="blocked"||e.entitlement==="grace"||!!updateFor(e,t)}export function fmtReleased(e){if(!e||!/^\d{4}-\d{2}-\d{2}/.test(String(e)))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const r=n=>String(n).padStart(2,"0");return`${r(t.getDate())}.${r(t.getMonth()+1)}.${t.getFullYear()}`}export function arrangePlugins(e,{filter:t="all",query:r="",latest:n=new Map}={}){const o=String(r).trim().toLowerCase(),a={all:()=>!0,on:i=>pluginStatus(i).running,off:i=>!pluginStatus(i).running,attention:i=>needsAttention(i,n)}[t]||(()=>!0),s=i=>needsAttention(i,n)?0:pluginStatus(i).running?1:2;return[...e||[]].filter(a).filter(i=>!o||[i.name,i.displayName,i.description,i.author].some(c=>String(c||"").toLowerCase().includes(o))).sort((i,c)=>s(i)-s(c)||String(i.displayName||i.name).localeCompare(String(c.displayName||c.name)))}export function pluginRow(e,t=new Map){const r=pluginStatus(e),n=h[e.entitlement]||null,o=updateFor(e,t),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:r.text,statusCls:`is-${r.tone}`,licensed:e.closedSource===!0,entText:n?.text||"",entCls:n?`is-${n.tone}`:"",entTitle:n?.title||"",update:o,updateText:o?`Update to ${o}`:"",configurable:settingsFields(e).length>0,locked:e.locked===!0,rowCls:[r.running?"":"is-off",needsAttention(e,t)?"is-attention":""].filter(Boolean).join(" ")}}export function formatMoney(e,t="GBP"){const r={GBP:"\xA3",USD:"$",EUR:"\u20AC"}[String(t||"GBP").toUpperCase()],n=(Number(e)/100).toFixed(2);return r?`${r}${n}`:`${n} ${t}`}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 t=e.terms?.managed?.monthly;return t==null||!Number.isFinite(Number(t))?"Paid":`${e.terms?.currency==="GBP"?"\xA3":`${e.terms?.currency||""} `}${(Number(t)/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:t="all",query:r=""}={}){const n=String(r).trim().toLowerCase(),o={all:()=>!0,installed:s=>s.installed,available:s=>catalogueAction(s)==="install",updates:s=>catalogueAction(s)==="update"}[t]||(()=>!0),a={waiting:0,update:1,install:2,buy:3,installed:4,"needs-cms":5,locked:6};return[...e||[]].filter(o).filter(s=>!n||[s.slug,s.displayName,s.description].some(i=>String(i||"").toLowerCase().includes(n))).sort((s,i)=>a[catalogueAction(s)]-a[catalogueAction(i)]||String(s.displayName||s.slug).localeCompare(String(i.displayName||i.slug)))}function w(e,t){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"}[t]}function $(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,t=Date.now()){if(!e?.store||!e.owned||!e.supportEnds)return"";const r=Date.parse(e.supportEnds);if(!Number.isFinite(r))return"";const n=new Date(r).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"});return r>=t?`updates until ${n}`:`updates ended ${n}`}export function catalogueRow(e){const t=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:"",t==="waiting"?"waiting for payment":"",t==="needs-cms"&&e.minCmsVersion?`needs Domma CMS ${String(e.minCmsVersion).replace(/^[^\d]+/,"")} or later`:""].filter(Boolean).join(" \xB7 "),description:e.description||"",price:formatPrice(e),...$(e),action:t,actionText:w(e,t),rowCls:t==="locked"||t==="needs-cms"?"is-off":t==="update"||t==="waiting"?"is-attention":""}}export function storeBuyLines(e,{site:t="",email:r=""}={}){const n=e.displayName||e.slug;return e.bundle?bundleBuyLines(e,{site:t,email:r}):e.owned?{title:`Renew ${n}`,lines:[`${e.renewalPeriodMonths||12} more months of updates for ${n} on ${t||"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 ${r||"your email address"}.`]}:{title:`Buy ${n}`,lines:[`${n} for ${t||"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 ${r||"your email address"}, and ${n} installs here as soon as the payment is through.`]}}export function bundleBuyLines(e,{site:t="",email:r=""}={}){const n=e.displayName||"Pro bundle",o=(e.contents||[]).length;if(e.owned)return{title:`Renew ${n}`,lines:[`${e.renewalPeriodMonths||12} more months of updates for all ${o} Tools in ${n} on ${t||"this site"}: ${formatMoney(e.renewal,e.currency)}, paid once.`,"Every Tool keeps working either way.",`Payment opens in a new tab. The receipt goes to ${r||"your email address"}.`]};const a=(e.contents||[]).filter(s=>s.owned).length;return{title:`Buy ${n}`,lines:[`All ${o} Tools in ${n} for ${t||"this site"}: ${formatMoney(e.price,e.currency)}, paid once. They are yours to keep, with ${e.supportMonths||12} months of updates for every one - renew them all later for ${formatMoney(e.renewal,e.currency)} a year.`,a?`${a} of them ${a===1?"is":"are"} yours already: not charged again, and ${a===1?"it joins":"they join"} the bundle's updates.`:"One licence covers one site address.",`Payment opens in a new tab. The receipt and licence keys go to ${r||"your email address"}, and the Tools install here (switched off) as soon as the payment is through.`]}}export function bundleCard(e){if(!e)return null;const t=e.contents||[],r=t.filter(a=>a.owned).length,n=t.filter(a=>a.installed).length,o=e.pending?"waiting":e.owned?e.canRenew?"renew":"owned":e.forSale?"buy":"none";return{title:e.displayName||"Pro bundle",lead:e.owned?`Yours: all ${t.length} Tools, with updates until ${String(e.supportEnds||"").slice(0,10)||"the end of its term"}.${e.canRenew?"":e.renewFrom?` Renew from ${String(e.renewFrom).slice(0,10)}.`:""}`:`All ${t.length} Pro Tools for this site in one go: ${formatMoney(e.price,e.currency)} once, with ${e.supportMonths||12} months of updates. Renew them all for ${formatMoney(e.renewal,e.currency)} a year.`,note:!e.owned&&r?`${r} already yours here - not charged again.`:`${n} of ${t.length} installed here.`,chips:t.map(a=>({slug:a.slug,text:a.displayName,cls:a.installed?"is-ok":a.owned?"is-info":""})),action:o,actionText:{buy:"Buy the bundle\u2026",renew:"Renew\u2026",owned:"Yours",waiting:"Waiting for payment\u2026",none:""}[o],actDisabled:o==="owned"||o==="none"||o==="waiting"}}export const isSecretKey=e=>/pass(word)?|secret|token|api[-_]?key|private|credential|uri$|dsn/i.test(String(e));export function labelFor(e){const t=String(e).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return t?t[0].toUpperCase()+t.slice(1):String(e)}export function settingsFields(e){const t=e?.settings||{},r={...e?.effectiveSettings||{},...t};return Array.isArray(e?.settingsSchema)&&e.settingsSchema.length?e.settingsSchema.filter(n=>n&&n.key).map(n=>{const o=n.type==="select"?"select":n.type==="number"?"number":n.type==="boolean"||n.type==="checkbox"?"checkbox":n.type==="textarea"?"textarea":"text",a=r[n.key]??n.default??(o==="checkbox"?!1:"");return{key:n.key,label:n.label||labelFor(n.key),type:o,value:o==="checkbox"?a===!0:String(a??""),options:(n.options||[]).map(s=>typeof s=="object"?{value:String(s.value),label:String(s.label??s.value)}:{value:String(s),label:String(s)}),min:n.min,max:n.max,help:n.help||"",secret:n.secret===!0||isSecretKey(n.key)}}):Object.entries(r).map(([n,o])=>{const a=isSecretKey(n);if(typeof o=="boolean")return{key:n,label:labelFor(n),type:"checkbox",value:o,secret:a};if(typeof o=="number")return{key:n,label:labelFor(n),type:"number",value:String(o),secret:a};if(o!==null&&typeof o=="object")return{key:n,label:labelFor(n),type:"json",value:JSON.stringify(o,null,2),secret:a};const s=String(o??"");return{key:n,label:labelFor(n),type:s.includes(`
|
|
2
|
+
`)||s.length>80?"textarea":"text",value:s,secret:a}})}export function readSettings(e,t){const r={},n={};for(const o of e){const a=t[o.key];if(o.type==="checkbox"){!!a!=!!o.value&&(n[o.key]=!!a);continue}const s=String(a??"");if(s!==String(o.value))if(o.type==="number"){const i=Number(s);if(s.trim()===""||!Number.isFinite(i)){r[o.key]="A number, please.";continue}if(o.min!=null&&i<o.min){r[o.key]=`At least ${o.min}.`;continue}if(o.max!=null&&i>o.max){r[o.key]=`At most ${o.max}.`;continue}n[o.key]=i}else if(o.type==="json")try{n[o.key]=JSON.parse(s)}catch{r[o.key]="Not valid JSON."}else n[o.key]=s}return{errors:r,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,t=[]){const r=s=>String(e?.[s]??"").trim(),n={displayName:r("displayName"),slug:r("slug"),description:r("description"),author:r("author"),icon:r("icon")||"box"},o={},a=/[<>"\\]|\*\//;n.displayName?n.displayName.length>60&&(o.displayName="60 characters at most."):o.displayName="A plugin needs a name.",/^[a-z][a-z0-9-]{1,39}$/.test(n.slug)?t.includes(n.slug)&&(o.slug=`"${n.slug}" is already installed.`):o.slug="2-40 characters: lowercase letters, digits and hyphens, starting with a letter.",n.description.length>300&&(o.description="300 characters at most."),n.author.length>80&&(o.author="80 characters at most."),/^[a-z][a-z0-9-]{0,39}$/.test(n.icon)||(o.icon="A lowercase icon name (letters, digits, hyphens).");for(const s of["displayName","description","author"])!o[s]&&a.test(n[s])&&(o[s]='No <, >, ", backslash or */.');return{errors:o,payload:n}}export function planLines(e){const t=[];for(const r of e?.cascaded||[])t.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||[])t.push(`${r.displayName||r.name} stays on without ${r.toolName||r.tool}${r.reason?`, but loses: ${r.reason.replace(/\.$/,"")}`:""}.`);return t}export function dependencyRows(e,{plugins:t=[],tools:r=[],catalogue:n=[]}={}){const o={on:["On","is-ok"],off:["Off","is-muted"],missing:["Not installed","is-warn"]},a=l=>{const u=r.find(d=>d.name===l);if(u)return{displayName:u.displayName||l,state:u.enabled===!1?"off":"on"};const p=t.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"}},s=(l,u="")=>{const{displayName:p,state:f}=a(l),[d,y]=o[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=>s(l)),worksWith:g.map(([l,u])=>s(l,u))}}export function dependencyText(e){return(e||[]).map(t=>`${t.displayName} (${t.stateText.toLowerCase()})`).join(", ")}
|
|
@@ -115,5 +115,11 @@
|
|
|
115
115
|
.plx-spacer { flex: 1; }
|
|
116
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
117
|
.plx-connect .plx-note { flex: 1; min-width: 14rem; }
|
|
118
|
+
/* The Pro bundle (self-hosted store): one card above the catalogue */
|
|
119
|
+
.plx-bundle { display: flex; flex-direction: column; gap: .5rem; padding: .8rem .9rem; margin-bottom: .75rem; border: 1px solid var(--dm-border);
|
|
120
|
+
border-radius: var(--dm-radius-md); background: color-mix(in srgb, var(--dm-primary) 7%, transparent); }
|
|
121
|
+
.plx-bundle-head { display: flex; align-items: center; gap: .7rem; }
|
|
122
|
+
.plx-bundle-head .plx-main { flex: 1; min-width: 0; }
|
|
123
|
+
.plx-bundle .plx-bundle-tools { display: flex; flex-wrap: wrap; gap: .3rem; justify-content: flex-start; }
|
|
118
124
|
@media (max-width: 640px) { .plx-main small { white-space: normal; } .plx-chips { display: none; } }
|
|
119
125
|
</style>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as h,getUser as
|
|
1
|
+
import{api as h,getUser as Q}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-chrome.js";import{SHAPES as xt,whileLoading as kt}from"../lib/loading.js";import{helpPopovers as Je}from"../lib/help-popover.js";import{onceClosed as $t,openMenuAt as Qe,sidebarCount as Et,viewLifetime as Tt}from"../lib/tool-kit.js";import{pluginAccent as Ge}from"../lib/plugin-accent.js";import{reportRestart as St}from"../lib/server-restart.js";import{FILTERS as Ct,arrangeCatalogue as Nt,arrangePlugins as Mt,catalogueAction as ue,catalogueRow as At,checkScaffold as It,dependencyRows as Ot,formatPrice as pe,fmtReleased as Lt,needsAttention as Ut,planLines as Dt,pluginRow as Rt,pluginStatus as Ze,readSettings as Bt,settingsFields as et,slugifyPlugin as Ft,storeBuyLines as jt,updateFor as tt,bundleCard as Wt}from"../lib/plugins-arrange.js";const at=/^#\/plugins\/?(\?.*)?$/,nt=5e3,Vt=3e4,Pt=20*6e4,qt="#/plugins",Se="plugins.filter",me="plugins.draft",_t=`
|
|
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 h,getUser as Y}from"../api.js";import{addBannerAction as ke}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>`,
|
|
13
|
+
</div>`,zt=`
|
|
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 h,getUser as Y}from"../api.js";import{addBannerAction as ke}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>`,
|
|
22
|
+
</div>`,Ht=`
|
|
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>
|
|
@@ -34,7 +34,7 @@ import{api as h,getUser as Y}from"../api.js";import{addBannerAction as ke}from".
|
|
|
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>`,i=O=>String(O??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");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(`
|
|
37
|
+
</li>`,u=R=>String(R??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Ce(R){const $=document.createElement("template");return $.innerHTML=R.trim(),$.content.firstElementChild}const k=Tt(at);export const pluginsView={templateUrl:"/admin/js/templates/plugins.html",async onMount(R){k.reset();const $=R.get(0).querySelector(".plx")||R.get(0),m=()=>at.test(location.hash)&&$.isConnected,j=M.observable([]),P=M.observable([]),Ne=M.computed(()=>P.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"}})),p=M.observable({available:null,site:null,items:[]}),Me=M.observable(!0),be=M.observable(""),y=M.observable("");let Ae="all";try{Ae=Ct.includes(S.get(Se))?S.get(Se):"all"}catch{}const B=M.observable(Ae),G=M.observable(""),q=M.observable("all"),Ie=M.observable("");k.add(M.effect(()=>{const e=B.value;try{S.set(Se,e)}catch{}}));const Z=M.computed(()=>new Map((p.value.items||[]).map(e=>[e.slug,e.version]))),U=e=>(p.peek().items||[]).find(t=>t.slug===e),he=M.observable([]);k.add(M.effect(()=>{const e=Z.value;he.value=Mt(j.value,{filter:B.value,query:G.value,latest:e}).map(t=>({...Rt(t,e),accent:Ge(t.name)}))}));const st=M.computed(()=>{const e=j.value,t=Z.value,a=e.filter(n=>Ze(n).running).length;return{all:e.length,on:a,off:e.length-a,attention:e.filter(n=>Ut(n,t)).length}}),ee=M.computed(()=>(p.value.items||[]).filter(e=>ue(e)==="update").length),lt=M.computed(()=>j.value.length?"No plugins match.":"No plugins installed. Browse the catalogue, or Install from file in the banner."),fe=M.observable([]);k.add(M.effect(()=>{fe.value=Nt(p.value.items,{filter:q.value,query:Ie.value}).map(e=>{const t=At(e),a=t.action==="update"||t.action==="install"||t.action==="buy";return{...t,accent:Ge(e.slug),actCls:a?"btn-primary":"btn-ghost",actDisabled:!a}})}));const ot=M.computed(()=>{const e=p.value.items||[];return{all:e.length,installed:e.filter(t=>t.installed).length,available:e.filter(t=>ue(t)==="install").length,updates:ee.value}}),Oe=M.computed(()=>Wt(p.value.bundle)),te=e=>j.peek().find(t=>t.name===e);async function ge(){try{const[e,t]=await kt($.querySelector(".dm-loading-slot"),Promise.all([h.plugins.list(),h.tools.list().catch(()=>[])]),xt.iconRows);if(!m())return;j.value=Array.isArray(e)?e:[],P.value=Array.isArray(t)?t:[],be.value=""}catch(e){be.value=`Could not load the plugins: ${e.message||e}`}finally{Me.value=!1}}async function Le(){try{const e=await h.marketplace.catalogue();if(!m())return;p.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,vat:e?.vat||null,bundle:(e?.bundles||[]).find(t=>t.slug==="bundle-pro")||null},e?.bundles?.[0]?.pending&&ye(e.bundles[0].pending,{fast:!1}),e?.connection?.status==="pending"&&ve();for(const t of e?.pending||[])ye(t.id,{fast:!1})}catch{p.value={available:!1,site:null,items:[],failed:!0}}}const N=async()=>{await Promise.all([ge(),Le()]),Et(qt)};async function _(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 ${u(e.displayName||e.name)} ${n}? The server restarts to apply it, which takes a few seconds.`)||y.peek())return;const s=l=>a==="tool"?h.tools.update(e.name,{enabled:t,cascade:l}):h.plugins.update(e.name,{enabled:t,cascade:l});y.value=`Switching ${e.displayName||e.name} ${n}\u2026`;try{let l;try{l=await s(!1)}catch(i){if(i.status!==409||!i.body?.needsConfirm)throw i;const r=Dt(i.body.plan);if(y.value="",!await E.confirm(`<p>Switching ${u(e.displayName||e.name)} ${n} also means:</p><ul>${r.map(c=>`<li>${u(c)}</li>`).join("")}</ul><p>Go ahead?</p>`))return;y.value=`Switching ${e.displayName||e.name} ${n}\u2026`,l=await s(!0)}await St(l,{onStatus:i=>{y.value=i}}),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(l){E.toast(`Not switched ${n}: ${l.message||l}`,{type:"error"})}finally{y.value="",m()&&await N()}}async function V(e,{update:t=!1}={}){const a=u(e.displayName||e.slug),n=t?`<p>Update ${a} from ${u(e.installedVersion)} to ${u(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${u(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}),l=s?.action==="upgrade"?`${e.slug} updated${s.from?` from ${s.from}`:""} to ${s.version}.`:`${e.slug} ${s?.version??e.version} installed.`;E.toast(`${l} Restart the server to activate it.`,{type:"success",duration:6e3})}catch(s){E.toast(s.message||"Install failed.",{type:"error"})}m()&&await N()}}const O=new Map;k.add(()=>{for(const e of O.values())clearTimeout(e.timer);O.clear()});function ye(e,{fast:t=!0}={}){if(!e||O.has(e))return;const a={timer:null,until:Date.now()+(t?Pt:0)};O.set(e,a);const n=()=>{clearTimeout(a.timer),!(!m()||!O.has(e))&&(a.timer=setTimeout(()=>ne(e),Date.now()<a.until?nt:Vt))};a.next=n,n()}const Ue=e=>{const t=O.get(e);t&&clearTimeout(t.timer),O.delete(e)},ae=new Set;async function ne(e,{byHand:t=!1}={}){if(!m()||ae.has(e))return;ae.add(e),clearTimeout(O.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"}),ae.delete(e),O.get(e)?.next?.();return}ae.delete(e);const n=a.bundle?p.peek().bundle?.displayName||"The Pro bundle":U(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}),O.get(e)?.next?.();return}if(Ue(e),a.status==="paid"&&a.bundle){const s=a.included||[],l=s.filter(r=>r.installed&&!r.alreadyHere).length,i=s.filter(r=>!r.installed);E.toast(a.kind==="renew"?`${n}: updates renewed for all ${s.length} Tools.`:`${n} is paid for: ${l} Tool${l===1?"":"s"} installed${s.length-l-i.length?`, ${s.length-l-i.length} already here`:""}. They are switched off - turn on the ones you want, then restart the server.`+(i.length?` ${i.length} did not install (${i.map(r=>U(r.slug)?.displayName||r.slug).join(", ")}) - use Install on the Browse tab.`:""),{type:i.length?"warning":"success",duration:14e3})}else if(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(l=>l.installed).map(l=>U(l.slug)?.displayName||l.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(l=>/mongo/i.test(l))?" 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});m()&&await N()}async function it(e){if(e?.pending&&await E.confirm(`<p>Stop waiting for the payment for ${u(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})){Ue(e.pending);try{await h.marketplace.dropPurchase(e.pending)}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}async function rt(e){const t=await E.prompt(`Licence key for ${u(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||!m()))try{const a=await h.marketplace.enterKey(e.slug,String(t).trim());await N();const n=U(e.slug);a.updates&&n&&!n.installed?(E.toast(`Licence accepted for ${e.displayName||e.slug}.`,{type:"success"}),await V(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})}}function ct(e,t,a){return new Promise(n=>{let s=!1;const l=C=>{if(!s){s=!0,n(C);try{i.close()}catch{}}},i=E.modal({title:e.title,size:"md",onClose:()=>l(null)}),r=document.createElement("div");r.className="flex flex-col gap-3",e.lines.forEach((C,d)=>{const w=document.createElement("p");d&&(w.className="text-muted"),w.textContent=C,r.append(w)});const c=(C,d,w)=>{const D=document.createElement("label");D.className="form-group";const X=document.createElement("span");if(X.className="form-label",X.textContent=C,D.append(X,d),w){const H=document.createElement("small");H.className="text-muted",H.textContent=w,D.append(H)}return D},b=document.createElement("select");b.className="form-select",b.append(new Option("Choose\u2026",""));for(const C of t.countries)b.append(new Option(C.name,C.code));const f=document.createElement("input");f.className="form-input",f.maxLength=20,f.spellcheck=!1,f.placeholder="Only for a business with one";const v=document.createElement("p");v.className="text-sm text-danger",v.hidden=!0;const x=document.createElement("div");x.className="flex gap-2 justify-end";const T=document.createElement("button");T.type="button",T.className="btn btn-ghost",T.textContent="Cancel";const A=document.createElement("button");A.type="button",A.className="btn btn-primary",A.textContent=a,T.addEventListener("click",()=>l(null)),A.addEventListener("click",()=>{if(!b.value){v.textContent="Choose your country - it decides the VAT.",v.hidden=!1,b.focus();return}l({country:b.value,vatNumber:f.value.trim()})}),x.append(T,A),r.append(c("Your country",b,"It decides the VAT on this purchase."),c("EU VAT number",f,"A business with a valid EU VAT number pays no VAT (reverse charge)."),v,x),i.element.appendChild(r),i.open(),setTimeout(()=>b.focus(),60)})}async function De(e){if(y.peek())return;const t=jt(e,{site:p.peek().site,email:Q()?.email}),a=p.peek().vat;let n={};if(a?.countryRequired&&Array.isArray(a.countries)&&a.countries.length){const l=await ct(t,a,e.owned?"Renew":"Buy");if(!l)return;n=l}else{const l=t.lines.map((i,r)=>`<p${r?' class="text-muted"':""}>${u(i)}</p>`).join(" ");if(!await E.confirm(l,{title:t.title,confirmText:e.owned?"Renew":"Buy",cancelText:"Cancel",html:!0}))return}const s=window.open("","_blank");try{const l=await h.marketplace.buy(e.slug,n);s&&!s.closed?(s.opener=null,s.location.href=l.checkoutUrl):window.open(l.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}),ye(l.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}),l.vatNote&&E.toast(l.vatNote,{type:"warning",duration:1e4})}catch(l){try{s?.close()}catch{}E.toast(l.message||"The purchase could not be started.",{type:"error",duration:8e3})}m()&&await N()}let se=null,z=0;k.add(()=>clearTimeout(se));function ve(){z||(z=Date.now()+60*6e4),clearTimeout(se),!(!m()||Date.now()>z)&&(se=setTimeout(()=>we(!1),nt))}let le=!1;async function we(e){if(le||!m())return;le=!0;let t;try{t=await h.marketplace.connectCheck()}catch(n){e&&E.toast(n.message||"Could not ask just now.",{type:"error"}),le=!1,ve();return}le=!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}),ve();return}z=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}),m()&&await N()}async function dt(){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:Q()?.email||"you@example.com",defaultValue:Q()?.email||"",confirmText:"Email me the link"});if(!(e==null||!m()))try{const t=await h.marketplace.connect(String(e).trim()||Q()?.email||"");E.toast(`Link emailed to ${t.connection?.email}. Open it and choose Connect - this page picks it up.`,{type:"info",duration:9e3}),z=0,await N()}catch(t){E.toast(t.message||"Could not connect.",{type:"error",duration:8e3})}}async function ut(){const e=p.peek().connection;if(e&&!(e.status!=="pending"&&!await E.confirm(`<p>Disconnect this site from Domma (${u(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(se),z=0;try{await h.marketplace.disconnect()}catch(t){E.toast(t.message||"Could not do that.",{type:"error"})}m()&&await N()}}const Re=()=>{for(const e of[...O.keys()])ne(e);p.peek().connection?.status==="pending"&&we(!1)};window.addEventListener("focus",Re),k.add(()=>window.removeEventListener("focus",Re));function Be(e){if(e?.store){De(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 Fe(e,t){const n=U(e)?.tier==="paid"&&!U(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 ${u(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 l=(await h.marketplace.uninstall(e))?.release?.removed?" It is off your bill.":"";E.toast(`${t||e} uninstalled.${l} Restart the server to apply.`,{type:"success",duration:6e3})}catch(s){E.toast(`Uninstall failed: ${s.message||s}`,{type:"error"})}m()&&await N()}}async function je(e){try{await h.plugins.exportBundle(e.name)}catch(t){E.toast(t.message||"Export failed.",{type:"error"})}}const We=e=>{location.hash=`#/plugins/code/${encodeURIComponent(e.name)}`},K=$.querySelector(".plx-file");async function pt(e){if(y.peek())return;y.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(y.value="",n.code==="CONFLICT"&&!t.confirmUpgrade){if(!await E.confirm(`<p>${u(n.name)} ${u(n.installedVersion||"the installed version")} is already installed. Update it to ${u(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>${u(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>${u(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}y.value=`Installing ${e.name}\u2026`}}finally{y.value="",m()&&await N()}}const Ve=async()=>{const e=K.files?.[0];K.value="",e&&await pt(e)};K.addEventListener("change",Ve),k.add(()=>K.removeEventListener("change",Ve));const oe=new Set;let W=null,Pe=!1;function qe({title:e,size:t="md",panel:a,model:n,methods:s,dirty:l=()=>!1,form:i=null,cleanup:r=()=>{}}){const c=E.slideover({title:u(e),size:t,position:"right"});c.element.appendChild(a);const b=Je(a),f=M.applyBindings(n,a,{methods:s});i&&(W=i),oe.add(c),$t(c,()=>{r(),f.dispose(),b(),oe.delete(c),W===i&&(W=null)});const v=c.close.bind(c);let x=!1,T=!1;return c.close=async A=>{if(!x&&A!==!0&&l()){if(T)return;T=!0;const C=await E.confirm("Discard the changes you have not saved?");if(T=!1,!C)return}return x=!0,v()},I.scan(a),c.open(),c}function xe(e,t=null){const a=te(e);if(!a)return;const n=Ze(a),s=et(a),l=U(a.name),i=tt(a,Z.peek()),r=!!(i&&l?.entitled&&!l?.needsCms),b={...Object.fromEntries(s.map(o=>[o.key,o.value])),...Object.fromEntries(Object.entries(t||{}).filter(([o])=>!s.find(g=>g.key===o)?.secret))},f=Object.fromEntries(s.map(o=>[o.key,M.observable(b[o.key])])),v=M.computed(()=>Bt(s,Object.fromEntries(s.map(o=>[o.key,f[o.key].value])))),x=M.observable(!1),T=()=>Object.keys(v.peek().changed).length>0||Object.keys(v.peek().errors).length>0,A=[["Version",`v${a.version}${i?` (v${i} available)`:""}`],["Status",n.text+(a.supersededBy?` - replaced by ${a.supersededBy}`:"")],["Author",a.author],["Released",Lt(a.date)],["Licence",a.licence],["Slug",a.name]].filter(([,o])=>o),C=(o,g)=>{const F=`plx-set-${g}`,ce=o.help?` <span data-help="${u(o.help)}"></span>`:"",Y=`<label class="form-label" for="${F}">${u(o.label)}${ce}</label>`,J=`data-model="v${g}.value"`,de=`<small class="plx-err" data-bind-hidden="!err${g}.value" data-bind-text="err${g}.value"></small>`;if(o.type==="checkbox")return`<div class="plx-setting">${Y}<input id="${F}" type="checkbox" class="form-switch" ${J}></div>`;if(o.type==="select")return`<div>${Y}<select id="${F}" class="form-input" ${J}>${o.options.map(Ye=>`<option value="${u(Ye.value)}">${u(Ye.label)}</option>`).join("")}</select>${de}</div>`;if(o.type==="json")return`<div>${Y}<textarea id="${F}" class="form-input plx-json" rows="5" spellcheck="false" ${J}></textarea>${de}</div>`;if(o.type==="textarea")return`<div>${Y}<textarea id="${F}" class="form-input" rows="3" ${J}></textarea>${de}</div>`;const vt=o.type==="number"?"number":o.secret?"password":"text",wt=`${o.min!=null?` min="${u(o.min)}"`:""}${o.max!=null?` max="${u(o.max)}"`:""}`;return`<div>${Y}<input id="${F}" type="${vt}" class="form-input" autocomplete="${o.secret?"new-password":"off"}"${wt} ${J}>${de}</div>`},d=Ot(a,{plugins:j.peek(),tools:P.peek(),catalogue:p.peek().items||[]}),w={saving:x,needs:M.observable(d.needs),worksWith:M.observable(d.worksWith),hasNeeds:d.needs.length>0,hasWorksWith:d.worksWith.length>0,hasFields:s.length>0,cannot:M.computed(()=>x.value||!Object.keys(v.value.changed).length||Object.keys(v.value.errors).length>0),...Object.fromEntries(s.flatMap((o,g)=>[[`v${g}`,f[o.key]],[`err${g}`,M.computed(()=>v.value.errors[o.key]||"")]]))},D=Ce(`
|
|
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 h,getUser as Y}from"../api.js";import{addBannerAction as ke}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">${s.map(
|
|
54
|
+
<div class="plx-form">${s.map(C).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
|
-
${
|
|
60
|
-
${
|
|
59
|
+
${r?`<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${u(i)}</button>`:""}
|
|
60
|
+
${i&&l?.needsCms?`<span class="plx-hint">v${u(i)}: ${u(l.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 h,getUser as Y}from"../api.js";import{addBannerAction as ke}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>`);
|
|
68
|
+
</div>`);D.querySelector(".plx-desc").textContent=a.description||"",D.querySelectorAll(".plx-deps").forEach(o=>{o.innerHTML=Kt});const X=D.querySelector(".plx-facts");for(const[o,g]of A){const F=document.createElement("dt");F.textContent=o;const ce=document.createElement("dd");ce.textContent=g,X.append(F,ce)}async function H(){if(w.cannot.peek())return;const{changed:o}=v.peek();x.value=!0;try{await h.plugins.update(a.name,{settings:{...a.settings||{},...o}}),E.toast(`${a.displayName||a.name}: settings saved.`,{type:"success"}),re.close(!0),m()&&await ge()}catch(g){E.toast(`Not saved: ${g.message||g}`,{type:"error"})}finally{x.value=!1}}const Ee=o=>async()=>{await re.close(),oe.has(re)||o()},re=qe({title:a.displayName||a.name,size:"md",panel:D,model:w,dirty:T,form:s.length?{kind:"settings",name:a.name,dirty:T,values:()=>{const o={};for(const g of s)g.secret||(o[g.key]=f[g.key].peek());return o}}:null,methods:{save:H,cancel:()=>re.close(),toggle:Ee(()=>_(a,!a.enabled)),update:Ee(()=>V(l,{update:!0})),source:Ee(()=>We(a)),exportIt:()=>je(a)}});D.addEventListener("keydown",o=>{(o.ctrlKey||o.metaKey)&&o.key==="Enter"&&(o.preventDefault(),H())})}function _e(e=null){const t=Q(),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(([d,w])=>[d,w.peek()]))),s=()=>Object.fromEntries(Object.entries(a).map(([d,w])=>[d,w.peek()])),l=()=>JSON.stringify(s())!==n||!!e;let i=!!e?.slug;const r=M.effect(()=>{const d=a.displayName.value;i||(a.slug.value=Ft(d))}),c=M.observable(!1),b=M.computed(()=>It(Object.fromEntries(Object.entries(a).map(([d,w])=>[d,w.value])),j.value.map(d=>d.name))),f=d=>M.computed(()=>b.value.errors[d]||""),v={...a,saving:c,nameErr:f("displayName"),slugErr:f("slug"),descErr:f("description"),authorErr:f("author"),iconErr:f("icon"),cannot:M.computed(()=>c.value||Object.keys(b.value.errors).length>0)},x=Ce(`
|
|
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,7 +101,7 @@ import{api as h,getUser as Y}from"../api.js";import{addBannerAction as ke}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
|
|
104
|
+
</div>`);async function T(){if(v.cannot.peek())return;c.value=!0;const{payload:d}=b.peek();try{await h.plugins.scaffold(d),E.toast(`"${d.displayName}" created. Restart the server to activate it.`,{type:"success",duration:6e3}),A.close(!0),m()&&await N()}catch(w){E.toast(w.message||"Could not create the plugin.",{type:"error"})}finally{c.value=!1}}const A=qe({title:"New plugin",size:"sm",panel:x,model:v,dirty:l,form:{kind:"new",name:null,dirty:l,values:s},cleanup:()=>r(),methods:{create:T,cancel:()=>A.close()}}),C=x.querySelector("#plx-np-slug");C.addEventListener("input",()=>{i=!!C.value}),x.addEventListener("keydown",d=>{(d.ctrlKey||d.metaKey)&&d.key==="Enter"&&(d.preventDefault(),T())}),x.querySelector("#plx-np-name")?.focus()}function mt(e){const t=te(e);if(!t)return[];const a=U(t.name),n=tt(t,Z.peek()),s=!!y.peek();return[{header:t.displayName||t.name},{label:et(t).length?"Details and settings\u2026":"Details\u2026",icon:"settings",action:()=>xe(t.name)},...t.core?[]:[t.enabled?{label:"Switch off\u2026",icon:"pause",disabled:s,action:()=>_(t,!1)}:{label:"Switch on\u2026",icon:"play",disabled:s,action:()=>_(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:()=>V(a,{update:!0})}]:[],{type:"divider"},{label:"View source",icon:"code",disabled:t.sourceEditable===!1,action:()=>We(t)},{label:"Export .dcmsplugin",icon:"download",disabled:t.closedSource===!0,action:()=>je(t)},...t.core?[]:[{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:s,action:()=>Fe(t.name,t.displayName)}]]}function bt(e){const t=P.peek().find(n=>n.name===e);if(!t)return[];const a=!!y.peek();return[{header:t.displayName},t.enabled?{label:t.locked?"Switch off (locked)":"Switch off\u2026",icon:"pause",disabled:a||t.locked,action:()=>_(t,!1,"tool")}:{label:t.locked?"Switch on (locked)":"Switch on\u2026",icon:"play",disabled:a||t.locked,action:()=>_(t,!0,"tool")}]}const ht=e=>{const t=P.peek().find(a=>a.name===e);t&&_(t,!t.enabled,"tool")};function ft(e){const t=U(e);if(!t)return[];const a=ue(t),n=!!y.peek();return[{header:t.displayName||t.slug},...a==="install"?[{label:`Install v${t.version}\u2026`,icon:"download",disabled:n,action:()=>V(t)}]:[],...a==="update"?[{label:`Update to v${t.version}\u2026`,icon:"download",disabled:n,action:()=>V(t,{update:!0})}]:[],...t.installed?[{label:"Open in Installed",icon:"package",action:()=>{G.value=t.slug,B.value="all",Ke.activate?.(0)}},{type:"divider"},{label:"Uninstall\u2026",icon:"trash",danger:!0,disabled:n,action:()=>Fe(t.slug,t.displayName)}]:[],...a==="buy"?[{label:t.store?`${t.owned?"Renew updates":"Buy"} - ${t.owned?pe(t).replace(/^Renew /,""):pe(t)}\u2026`:`${t.licenceStatus==="expired"?"Renew":"Buy"}${pe(t)!=="Paid"?` - ${pe(t)}`:""}\u2026`,icon:"shopping-cart",action:()=>Be(t)}]:[],...t.store&&t.tier==="paid"&&!t.owned?[{label:"Enter licence key\u2026",icon:"key",action:()=>rt(t)}]:[],...a==="waiting"?[{label:"Paid? Check now",icon:"refresh-cw",action:()=>ne(t.pending,{byHand:!0})},{label:"Stop waiting\u2026",icon:"x",action:()=>it(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 gt(e){const t=U(e);if(!t)return;const a=ue(t);a==="install"?V(t):a==="update"?V(t,{update:!0}):a==="buy"?Be(t):a==="waiting"?ne(t.pending,{byHand:!0}):a==="needs-cms"?E.toast(t.needsCms,{type:"warning",duration:6e3}):t.installed&&(G.value=t.slug,B.value="all",Ke.activate?.(0))}function ke(e,t,a,n){const s=E.contextMenu(e,{cursor:"glyph",match:".plx-row",inherit:!1,density:"compact",items:r=>a(r.dataset[t])});k.add(()=>s?.destroy?.());const l=r=>{const c=r.target.closest(".plx-row");if(!c)return;const b=r.target.closest(".plx-kebab");if(b){Qe(b);return}if(r.target.closest(".plx-act")){r.target.closest("button").disabled||n(c.dataset[t]);return}n(c.dataset[t])},i=r=>{const c=r.target.closest(".plx-row");c&&(r.key==="F10"&&r.shiftKey?(r.preventDefault(),Qe(c)):r.key==="Enter"&&r.target===c&&n(c.dataset[t]))};e.addEventListener("click",l),e.addEventListener("keydown",i),k.add(()=>{e.removeEventListener("click",l),e.removeEventListener("keydown",i)})}const ie=$.querySelector(".plx-browse");ie.appendChild(Ce(`
|
|
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>
|
|
@@ -133,7 +133,17 @@ import{api as h,getUser as Y}from"../api.js";import{addBannerAction as ke}from".
|
|
|
133
133
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="connectCheck" data-bind-hidden="connStatus.value !== 'pending'">Check now</button>
|
|
134
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
135
|
</div>
|
|
136
|
+
<div class="plx-bundle" data-bind-hidden="!bundleView.value">
|
|
137
|
+
<div class="plx-bundle-head">
|
|
138
|
+
<span class="plx-icon" aria-hidden="true"><span data-icon="package" data-icon-size="17"></span></span>
|
|
139
|
+
<div class="plx-main"><strong data-bind-text="bundleView.value && bundleView.value.title"></strong>
|
|
140
|
+
<small data-bind-text="bundleView.value && bundleView.value.lead"></small></div>
|
|
141
|
+
<button type="button" class="btn btn-sm btn-primary plx-act" data-on-click="bundleBuy" data-bind-disabled="bundleView.value && bundleView.value.actDisabled" data-bind-text="bundleView.value && bundleView.value.actionText"></button>
|
|
142
|
+
</div>
|
|
143
|
+
<p class="plx-note" data-bind-text="bundleView.value && bundleView.value.note"></p>
|
|
144
|
+
<div class="plx-chips plx-bundle-tools"></div>
|
|
145
|
+
</div>
|
|
136
146
|
<p class="plx-note" data-bind-hidden="browseRows.value.length">Nothing in the catalogue matches.</p>
|
|
137
147
|
<div class="plx-list plx-catalogue" data-each="browseRows.value key=slug"></div>
|
|
138
148
|
</div>
|
|
139
|
-
</div>`)),
|
|
149
|
+
</div>`)),ie.querySelector(".plx-catalogue").innerHTML=Ht;const ze=$.querySelector(".plx-installed");ze.innerHTML=_t;const He=$.querySelector(".plx-tools");He.innerHTML=zt;const Ke=E.tabs($.querySelector(".plx-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),yt=M.applyBindings({plugins:j,tools:P,toolRows:Ne,catalogue:p,loading:Me,loadError:be,restarting:y,filter:B,query:G,rows:he,counts:st,emptyText:lt,updateCount:ee,updateCountText:M.computed(()=>`${ee.value} update${ee.value===1?"":"s"}`),browseFilter:q,browseQuery:Ie,browseRows:fe,browseCounts:ot,bundleView:Oe,siteText:M.computed(()=>p.value.site?p.value.mode==="store"?`From the Domma store, for ${p.value.site}. A Tool you buy is yours to keep, with a term of updates you can renew.`:`Licensed to ${p.value.site}.`:""),connStatus:M.computed(()=>p.value.connection?.status||""),connectText:M.computed(()=>{const e=p.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(()=>p.value.available===null?"loading":p.value.failed?"error":p.value.available?"list":p.value.mode==="owner"?"owner":"file")},$,{methods:{showAll:()=>{B.value="all"},showOn:()=>{B.value="on"},showOff:()=>{B.value="off"},showAttention:()=>{B.value="attention"},bAll:()=>{q.value="all"},bAvailable:()=>{q.value="available"},bInstalled:()=>{q.value="installed"},bUpdates:()=>{q.value="updates"},connectStart:()=>dt(),connectCheck:()=>we(!0),connectForget:()=>ut(),bundleBuy:()=>{const e=p.peek().bundle;e&&De({...e,bundle:!0})}}});k.add(()=>yt.dispose()),k.add(M.effect(()=>{const e=ie.querySelector(".plx-bundle-tools");e&&e.replaceChildren(...(Oe.value?.chips||[]).map(t=>{const a=document.createElement("span");return a.className=`plx-chip ${t.cls}`.trim(),a.textContent=t.text,t.cls==="is-ok"?a.title="Installed here":t.cls==="is-info"&&(a.title="Yours, not installed here"),a}))})),k.add(Je($,{position:"bottom"})),k.add(M.effect(()=>{he.value,Ne.value,fe.value,requestAnimationFrame(()=>{$.isConnected&&I.scan($)})})),ke(ze,"name",mt,e=>xe(e)),ke(He,"tool",bt,ht),ke(ie.querySelector(".plx-catalogue"),"slug",ft,gt),Te(R,{id:"plugins-guide",icon:"book",title:"Writing a Tool (guide)",onClick:()=>{location.hash="#/tutorials/plugin"}}),Te(R,{id:"plugins-install-file",icon:"upload",title:"Install from file (.dcmsplugin)",onClick:()=>K.click()});let $e=!1;try{$e=(await h.plugins.policy())?.signedOnly===!0}catch{}$e||Te(R,{id:"plugins-new",icon:"plus",title:"New plugin",onClick:()=>_e()});const Xe=e=>{(y.peek()||W?.dirty())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Xe),k.add(()=>window.removeEventListener("beforeunload",Xe)),k.add(()=>{if(W?.dirty())try{S.set(me,{kind:W.kind,name:W.name,values:W.values(),at:new Date().toISOString()})}catch{}Pe=!0,[...oe].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan($),await Promise.all([ge(),Le()]),!m())return;let L=null;try{L=S.get(me)}catch{}if(L?.values&&!Pe){try{S.remove?S.remove(me):S.set(me,null)}catch{}const e=L.kind==="new"?"the new plugin you started":`your settings for ${u(te(L.name)?.displayName||L.name)}`;(L.kind==="new"&&!$e||te(L.name))&&await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&m()&&(L.kind==="new"?_e(L.values):xe(L.name,L.values))}}};
|
|
@@ -146,6 +146,7 @@ Only `admin/**` and `public/**` are served; `plugin.js`, `config.js` and `data/`
|
|
|
146
146
|
| `settingsSchema` | The Marketplace **Configure** form - see [Settings in the Marketplace](#settings-in-the-marketplace-configure) |
|
|
147
147
|
| `tier` | `free` or `paid` - used by the marketplace catalogue |
|
|
148
148
|
| `closedSource` | `true` for a licensed plugin: an entitlement is required, and the source editor and export are refused |
|
|
149
|
+
| `hostedOnly` | `true` for a Tool that runs only on sites Domma hosts (Site Builder, Tool Builder): on a self-hosted site it is refused at install and does not load (state `hosted-only`). A managed site and the manager itself run it |
|
|
149
150
|
| `licence` | Overrides the licence line shown on the plugin's admin banner |
|
|
150
151
|
| `contentPaths` | Folders inside the plugin holding user-authored work; they are tracked in the site's git and preserved by `npx domma-cms update` |
|
|
151
152
|
| `npmDependencies`, `minCmsVersion` | Carried into the marketplace catalogue. `minCmsVersion` (e.g. `"0.92.2"`) is enforced: install and update refuse a plugin that needs a newer CMS (0.92.2). `npmDependencies` is informational |
|