domma-cms 1.47.3 → 1.47.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.47.4] - 2026-11-08
4
+
5
+ - **Security: files visitors send with a form are private.** They were saved to content/media/, served to anyone at `/media/<name>` and listed in the Media library - CVs and right-to-work documents among them. New uploads go to `content/form-uploads/<form>/<upload id>/` (kept out of the site repo by its own `.gitignore`) and are served only by `GET /api/forms/:slug/uploads/:id/:name`, to a signed-in user with the submissions inbox's permission (`collections` read) who can see the form, while a submission links to the file. Only PNG, JPEG, GIF, WebP and PDF are shown inline; everything else is a download, always with nosniff, `private, no-store` and a CSP that runs nothing. The submission panel shows pictures and opens files with the admin's sign-in; the notification email links to them and says to sign in (files are not attached). On first start a one-off migration moves the files existing submissions reference into the private store and rewrites the references - only real submissions (`meta.source: form:<slug>`) and only regular files (a link or folder is skipped); a file a page or other content also links to is copied and left in Media. The file route's CSP also has `frame-ancestors 'none'`. Webhooks, Actions and plugins that fetched a submission's file URL without signing in can no longer do so.
6
+ - Forms: the submission panel and the notification email show answers as the visitor saw them, not as stored. A dropdown, radio, checkbox group or chooser (picture choices) shows the option's label ("Faulty", not `faulty`), a single checkbox Yes or No (not `true`), a date 03/11/2026 (not `2026-11-03`), a time 14:05, and a file field its file names. A value the form no longer offers is shown as stored. The row summary, Copy and search use the same words. One helper does it for both (`answerLabel()`, `public/js/form-answers.mjs`), reading labels the way trigger messages do; the email escapes all of it. CSV and JSON exports still carry the stored values.
7
+ - Forms: deleting a submission (one, or Clear all) now deletes the files it uploaded. Only the files the form saved for that submission in its private store are touched - a reference in one of the form's file fields to `/api/forms/<this form>/uploads/...`, resolved through `fileIn` inside the store - and a file another entry still links to is kept. Nothing under /media is ever deleted this way, so a reference planted in an entry (a public create, a token, an editor) cannot remove a file a page uses, and a tampered reference such as `../../config/server.json` is refused.
8
+
3
9
  ## [1.47.3] - 2026-11-08
4
10
 
5
11
  - **Security: `{{field}}` in a block template escapes `'` as well**, so a value printed inside a single-quoted attribute cannot end it (`escapeHtmlText()` in markdown.js escaped `"` only).
@@ -1,2 +1,2 @@
1
- export const FILTERS=["inbox","new","spam"],WEEK_MS=6048e5;const g=new Set(["page-break","heading","paragraph","html","divider","spacer","banner"]);export function answerFields(e){return(e?.fields||[]).filter(t=>t&&t.name&&!g.has(t.type)).map(t=>({name:String(t.name),label:String(t.label||t.name),type:String(t.type||"text")}))}export const isFileRef=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.url=="string"&&(typeof e.name=="string"||e.name===void 0),fileRefsOf=e=>(Array.isArray(e)?e:[e]).filter(isFileRef),safeFileHref=e=>/^(https?:\/\/|\/(?!\/))/i.test(String(e||""))?String(e):"";export function answerText(e){return e==null?"":Array.isArray(e)?e.map(answerText).filter(Boolean).join(", "):typeof e=="boolean"?e?"Yes":"No":isFileRef(e)?e.name||e.url.split("/").pop()||"file":typeof e=="object"?JSON.stringify(e):String(e).trim()}export const isSpam=e=>e?.data?.spam===!0,createdAt=e=>e?.meta?.createdAt||"",isNew=(e,t=Date.now())=>{const n=Date.parse(createdAt(e));return Number.isFinite(n)&&t-n<6048e5};const u=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export function emailOf(e,t){const n=e?.data||{},a=t.find(r=>r.type==="email"&&u.test(answerText(n[r.name])));if(a)return answerText(n[a.name]);const i=t.find(r=>/e-?mail/i.test(r.name)&&u.test(answerText(n[r.name])));if(i)return answerText(n[i.name]);const c=t.find(r=>u.test(answerText(n[r.name])));return c?answerText(n[c.name]):""}const d=(e,t)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e;export function submissionRow(e,t,n=Date.now()){const a=e?.data||{},i=t.filter(m=>answerText(a[m.name])!==""),c=i.find(m=>/(^|_|-)(full[-_ ]?)?name$|^name/i.test(m.name)&&m.type!=="email"),r=emailOf(e,t),o=c||i.find(m=>answerText(a[m.name])===r&&r)||i[0],p=o?d(answerText(a[o.name]),80):"Empty submission",s=i.filter(m=>m!==o).slice(0,3).map(m=>`${m.label}: ${d(answerText(a[m.name]),60)}`),l=isSpam(e),f=isNew(e,n);return{id:String(e?.id??""),title:p,meta:s.join(" \xB7 ")||"No other answers",email:r,at:createdAt(e),spam:l,fresh:f&&!l,rowCls:[l&&"is-spam",f&&!l&&"is-new"].filter(Boolean).join(" ")}}export function arrangeSubmissions(e,{filter:t="inbox",query:n="",from:a="",to:i="",now:c=Date.now()}={}){const r=String(n).trim().toLowerCase(),o=a?Date.parse(`${a}T00:00:00`):null,p=i?Date.parse(`${i}T23:59:59.999`):null;return[...e||[]].filter(s=>t==="spam"?isSpam(s):!isSpam(s)).filter(s=>t!=="new"||isNew(s,c)).filter(s=>!r||Object.values(s?.data||{}).some(l=>answerText(l).toLowerCase().includes(r))).filter(s=>{if(o===null&&p===null)return!0;const l=Date.parse(createdAt(s));return Number.isFinite(l)?(o===null||l>=o)&&(p===null||l<=p):!1}).sort((s,l)=>String(createdAt(l)).localeCompare(String(createdAt(s))))}export function submissionCounts(e,t=Date.now()){const n=e||[],a=n.filter(isSpam).length;return{inbox:n.length-a,new:n.filter(i=>!isSpam(i)&&isNew(i,t)).length,spam:a,all:n.length}}export function submissionText(e,t,{formTitle:n="",when:a=""}={}){const i=e?.data||{},c=t.filter(o=>answerText(i[o.name])!=="").map(o=>`${o.label}: ${answerText(i[o.name])}`),r=[n&&`${n} - submission`,a&&`Submitted ${a}`].filter(Boolean);return[...r,...r.length?[""]:[],...c].join(`
1
+ import{answerLabel as g}from"../../../public/js/form-answers.mjs";export const FILTERS=["inbox","new","spam"],WEEK_MS=7*864e5;const y=new Set(["page-break","heading","paragraph","html","divider","spacer","banner"]);export function answerFields(e){return(e?.fields||[]).filter(t=>t&&t.name&&!y.has(t.type)).map(t=>({name:String(t.name),label:String(t.label||t.name),type:String(t.type||"text"),...Array.isArray(t.options)&&{options:t.options},...t.logic?.cascade&&{logic:{cascade:t.logic.cascade}}}))}export const isFileRef=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.url=="string"&&(typeof e.name=="string"||e.name===void 0),fileRefsOf=e=>(Array.isArray(e)?e:[e]).filter(isFileRef),safeFileHref=e=>/^(https?:\/\/|\/(?!\/))/i.test(String(e||""))?String(e):"";export function answerText(e){return e==null?"":Array.isArray(e)?e.map(answerText).filter(Boolean).join(", "):typeof e=="boolean"?e?"Yes":"No":isFileRef(e)?e.name||e.url.split("/").pop()||"file":typeof e=="object"?JSON.stringify(e):String(e).trim()}export const fieldText=(e,t)=>g(e,t),isSpam=e=>e?.data?.spam===!0,createdAt=e=>e?.meta?.createdAt||"",isNew=(e,t=Date.now())=>{const n=Date.parse(createdAt(e));return Number.isFinite(n)&&t-n<WEEK_MS};const d=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export function emailOf(e,t){const n=e?.data||{},r=t.find(i=>i.type==="email"&&d.test(answerText(n[i.name])));if(r)return answerText(n[r.name]);const a=t.find(i=>/e-?mail/i.test(i.name)&&d.test(answerText(n[i.name])));if(a)return answerText(n[a.name]);const m=t.find(i=>d.test(answerText(n[i.name])));return m?answerText(n[m.name]):""}const f=(e,t)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e;export function submissionRow(e,t,n=Date.now()){const r=e?.data||{},a=t.filter(c=>fieldText(c,r[c.name])!==""),m=a.find(c=>/(^|_|-)(full[-_ ]?)?name$|^name/i.test(c.name)&&c.type!=="email"),i=emailOf(e,t),s=m||a.find(c=>answerText(r[c.name])===i&&i)||a[0],p=s?f(fieldText(s,r[s.name]),80):"Empty submission",u=a.filter(c=>c!==s).slice(0,3).map(c=>`${c.label}: ${f(fieldText(c,r[c.name]),60)}`),o=isSpam(e),l=isNew(e,n);return{id:String(e?.id??""),title:p,meta:u.join(" \xB7 ")||"No other answers",email:i,at:createdAt(e),spam:o,fresh:l&&!o,rowCls:[o&&"is-spam",l&&!o&&"is-new"].filter(Boolean).join(" ")}}export function arrangeSubmissions(e,{filter:t="inbox",query:n="",from:r="",to:a="",now:m=Date.now(),fields:i=[]}={}){const s=String(n).trim().toLowerCase(),p=r?Date.parse(`${r}T00:00:00`):null,u=a?Date.parse(`${a}T23:59:59.999`):null;return[...e||[]].filter(o=>t==="spam"?isSpam(o):!isSpam(o)).filter(o=>t!=="new"||isNew(o,m)).filter(o=>!s||Object.values(o?.data||{}).some(l=>answerText(l).toLowerCase().includes(s))||i.some(l=>fieldText(l,o?.data?.[l.name]).toLowerCase().includes(s))).filter(o=>{if(p===null&&u===null)return!0;const l=Date.parse(createdAt(o));return Number.isFinite(l)?(p===null||l>=p)&&(u===null||l<=u):!1}).sort((o,l)=>String(createdAt(l)).localeCompare(String(createdAt(o))))}export function submissionCounts(e,t=Date.now()){const n=e||[],r=n.filter(isSpam).length;return{inbox:n.length-r,new:n.filter(a=>!isSpam(a)&&isNew(a,t)).length,spam:r,all:n.length}}export function submissionText(e,t,{formTitle:n="",when:r=""}={}){const a=e?.data||{},m=t.filter(s=>fieldText(s,a[s.name])!=="").map(s=>`${s.label}: ${fieldText(s,a[s.name])}`),i=[n&&`${n} - submission`,r&&`Submitted ${r}`].filter(Boolean);return[...i,...i.length?[""]:[],...m].join(`
2
2
  `)}
@@ -0,0 +1 @@
1
+ import{getToken as c,refreshAccessToken as s}from"/admin/js/api.js";export const isPrivateUpload=r=>/^\/api\/forms\/[^/?#]+\/uploads\/[^/?#]+\/[^/?#]+$/.test(String(r||""));const o=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf"]),l=/\.(png|jpe?g|gif|webp)$/i;export async function fetchPrivateFile(r){const t=n=>fetch(r,{headers:n?{Authorization:`Bearer ${n}`}:{}});let e=await t(c());if(e.status===401)try{e=await t(await s())}catch{}if(!e.ok)throw new Error(e.status===404?"That file is no longer there.":`Could not open the file (${e.status}).`);return e.blob()}export async function openPrivateFile(r,t="file"){const e=window.open("","_blank");try{const n=await fetchPrivateFile(r),a=URL.createObjectURL(n);if(o.has(n.type)&&e)e.opener=null,e.location.href=a;else{e?.close();const i=document.createElement("a");i.href=a,i.download=t,document.body.appendChild(i),i.click(),i.remove()}setTimeout(()=>URL.revokeObjectURL(a),6e4)}catch(n){e?.close(),E.toast(n.message,{type:"error"})}}export function wirePrivateLink(r,t){isPrivateUpload(t?.url)&&r.addEventListener("click",e=>{e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||(e.preventDefault(),openPrivateFile(t.url,t.name||"file"))})}export function privateThumbnail(r){if(!isPrivateUpload(r?.url)||!(l.test(r.url)||/^image\/(png|jpeg|gif|webp)$/.test(String(r.mime||""))))return null;const t=document.createElement("img");return t.alt=r.name||"",t.className="fsx-thumb",t.style.cssText="display:block;max-width:220px;max-height:160px;margin-top:4px;border-radius:4px;",fetchPrivateFile(r.url).then(e=>{if(!o.has(e.type)||e.type==="application/pdf"){t.remove();return}t.src=URL.createObjectURL(e),t.addEventListener("load",()=>URL.revokeObjectURL(t.src),{once:!0})}).catch(()=>t.remove()),t}
@@ -212,10 +212,19 @@
212
212
  <h3>File uploads</h3>
213
213
  <p>Send <code>multipart/form-data</code>. A file part whose name matches a <code>type: "file"</code> field is checked
214
214
  against that field's <code>file.maxSize</code> (bytes, default 5 MB) and <code>file.accept</code> (comma-separated
215
- MIME types, wildcards such as <code>image/*</code> allowed), saved to the media library under a prefixed safe name,
215
+ MIME types, wildcards such as <code>image/*</code> allowed), saved to a private store
216
+ (<code>content/form-uploads/&lt;form&gt;/&lt;upload id&gt;/</code>, never the media library) under a prefixed safe name,
216
217
  and stored on the entry as <code>{ "url", "name", "size", "mime" }</code>. A file part for an unknown field is
217
218
  ignored; an empty file input is skipped. The server-wide upload limit (<code>uploads.maxFileSize</code> in
218
219
  <code>config/server.json</code>) still applies.</p>
220
+ <p>The <code>url</code> is <code>/api/forms/&lt;slug&gt;/uploads/&lt;upload id&gt;/&lt;name&gt;</code>. It answers only a
221
+ signed-in user with the <code>collections</code> read permission (the one that opens the submissions inbox) who can
222
+ see the form, and only while a submission of the form links to the file: a Bearer token, or the admin's sign-in
223
+ cookie for a link opened in the browser. Anyone else gets <code>401</code> or <code>403</code>. PNG, JPEG, GIF, WebP
224
+ and PDF are sent inline; everything else as an <code>attachment</code> of type
225
+ <code>application/octet-stream</code>, always with <code>X-Content-Type-Options: nosniff</code>,
226
+ <code>Cache-Control: private, no-store</code> and a Content-Security-Policy that runs nothing. Deleting a submission
227
+ deletes its files.</p>
219
228
  <pre class="code-block"><code class="language-bash">curl -X POST https://example.com/api/forms/submit/apply \
220
229
  -F name='Ada Lovelace' \
221
230
  -F email=ada@example.com \
@@ -134,6 +134,12 @@ Subject Prefix: [Contact Form]</code></pre>
134
134
  <li>Forms accept pictures (not SVG), audio, video, PDFs, Office and OpenDocument files, text and CSV, and
135
135
  archives. Web pages, SVG files and scripts are always refused. Files are only saved once the submission
136
136
  has passed its spam and validation checks.</li>
137
+ <li>Files visitors send are <strong>private</strong>. They are not in Media and have no public address: they
138
+ open from the submission (pictures show there) for someone signed in who can read the form's submissions.
139
+ The email notification links to them; the link asks you to sign in first. Files are never attached to the
140
+ email. Deleting a submission deletes its files.</li>
141
+ <li>Files sent before this change were in Media. They are moved to the private store when the site first
142
+ starts on this version - or copied, and left in Media too, if a page or other content links to one.</li>
137
143
  </ul>
138
144
 
139
145
  <h3>Copying a form to another site</h3>
@@ -1,10 +1,10 @@
1
- import{api as k,apiRequest as ft}from"../api.js";import{addBannerAction as j}from"../lib/plugin-chrome.js";import{SHAPES as mt,showLoading as ht}from"../lib/loading.js";import{helpPopovers as ze}from"../lib/help-popover.js";import{onceClosed as yt,openMenuAt as je,sidebarCount as P,viewLifetime as vt}from"../lib/tool-kit.js";import{PAGE_SIZE as ce,SHOW_STEP as X,arrangeEntries as bt,listColumns as gt,canClear as Et,cellText as Pe,countText as kt,draftable as xt,fileRefsOf as wt,filterChoices as St,filterText as Ct,hasForm as $t,isFileValue as ve,safeFileHref as At,shownValue as be,snapshot as _e,typedValue as Mt,valueText as ge}from"../lib/collection-entries-arrange.js";import{fmtDate as Lt,fmtDateTime as _}from"../lib/dates.js";const Be=/^#\/collections\/[^/?#]+\/entries\/?(\?.*)?$/,B=p=>`collection-entries.draft.${p}`,U=p=>String(p??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function le(p){const m=document.createElement("template");return m.innerHTML=p.trim(),m.content.firstElementChild}const qt='<span class="cex-chip">{{text}}<button type="button" data-idx="{{idx}}" title="Remove this filter" aria-label="Remove filter {{text}}">\xD7</button></span>';function Tt(p){return`
1
+ import{wirePrivateLink as ft}from"/admin/js/lib/private-files.js";import{api as k,apiRequest as mt}from"../api.js";import{addBannerAction as j}from"../lib/plugin-chrome.js";import{SHAPES as ht,showLoading as yt}from"../lib/loading.js";import{helpPopovers as ze}from"../lib/help-popover.js";import{onceClosed as vt,openMenuAt as je,sidebarCount as P,viewLifetime as bt}from"../lib/tool-kit.js";import{PAGE_SIZE as ce,SHOW_STEP as X,arrangeEntries as gt,listColumns as Et,canClear as kt,cellText as Pe,countText as xt,draftable as wt,fileRefsOf as St,filterChoices as Ct,filterText as $t,hasForm as At,isFileValue as ve,safeFileHref as Mt,shownValue as be,snapshot as _e,typedValue as Lt,valueText as ge}from"../lib/collection-entries-arrange.js";import{fmtDate as qt,fmtDateTime as _}from"../lib/dates.js";const Be=/^#\/collections\/[^/?#]+\/entries\/?(\?.*)?$/,B=p=>`collection-entries.draft.${p}`,U=p=>String(p??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function le(p){const m=document.createElement("template");return m.innerHTML=p.trim(),m.content.firstElementChild}const Tt='<span class="cex-chip">{{text}}<button type="button" data-idx="{{idx}}" title="Remove this filter" aria-label="Remove filter {{text}}">\xD7</button></span>';function Nt(p){return`
2
2
  <tr class="cex-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
3
3
  <td class="cex-check"><input type="checkbox" class="cex-sel" aria-label="Select this entry" data-bind-checked="sel"></td>
4
- ${Array.from({length:p},(b,a)=>`<td data-col="${a}" title="{{t${a}}}">{{c${a}}}</td>`).join("")}
4
+ ${Array.from({length:p},(v,a)=>`<td data-col="${a}" title="{{t${a}}}">{{c${a}}}</td>`).join("")}
5
5
  <td class="cex-when" title="{{whenFull}}">{{when}}</td>
6
6
  <td class="cex-tools"><button type="button" class="cex-run" data-bind-hidden="!runs" title="Run one of this collection's actions">\u26A1 {{runs}}</button><button type="button" class="cex-kebab" aria-label="Actions for this entry" title="Actions">\u22EE</button></td>
7
- </tr>`}const Nt=(p,m)=>p?.type==="file"||ve(m?.[p?.name]);function He(p){const m=document.createElement("ul");m.className="cex-files";for(const b of wt(p)){const a=document.createElement("li"),l=At(b.url),c=document.createElement(l?"a":"span");l&&(c.href=l,c.target="_blank",c.rel="noopener"),c.textContent=ge(b),a.appendChild(c),m.appendChild(a)}return m}function It(p,m){const b={};return p.forEach(a=>{const l={};a.fullWidth?l.span=m:a.span>1&&(l.span=a.span),a.placeholder&&(l.placeholder=a.placeholder),a.helper&&(l.hint=a.helper),a.prefix&&(l.prefix=a.prefix),a.suffix&&(l.suffix=a.suffix);for(const u of["clear","stepper","counter"])a[u]===!0&&(l[u]=!0);const c=a.type==="checkbox"?"boolean":a.type==="date"?"string":a.type;b[a.name]={type:c,label:a.label,required:a.required,options:a.options,...Object.keys(l).length?{formConfig:l}:{}}}),b}function Ve(p,m){const b=CSS.escape(m);return[...p.querySelectorAll(`[name="${b}"], [name="${b}[]"]`)]}function ie(p,m){const b={};for(const a of m){const l=Ve(p,a.name);if(!l.length)continue;const c=l[0];c.type==="radio"?b[a.name]=l.find(u=>u.checked)?.value??"":c.type==="checkbox"&&(l.length>1||c.name.endsWith("[]"))?b[a.name]=l.filter(u=>u.checked).map(u=>u.value):c.type==="checkbox"?b[a.name]=c.checked:c.tagName==="SELECT"&&c.multiple?b[a.name]=[...c.selectedOptions].map(u=>u.value):b[a.name]=Mt(a,c.value)}return b}function Je(p,m,b){for(const a of m){if(!(a.name in b))continue;const l=b[a.name],c=Ve(p,a.name);if(!c.length)continue;const u=c[0];u.type==="radio"?c.forEach(r=>{r.checked=r.value===String(l)}):u.type==="checkbox"&&(c.length>1||u.name.endsWith("[]"))?c.forEach(r=>{r.checked=Array.isArray(l)&&l.includes(r.value)}):u.type==="checkbox"?u.checked=l===!0:u.tagName==="SELECT"&&u.multiple?[...u.options].forEach(r=>{r.selected=Array.isArray(l)&&l.includes(r.value)}):u.value=l??"",c.forEach(r=>r.dispatchEvent(new Event("input",{bubbles:!0})))}}const Ke=vt(Be);export const collectionEntriesView={templateUrl:"/admin/js/templates/collection-entries.html",async onMount(p){Ke.reset();const m=p.get(0).querySelector(".cex")||p.get(0),b=location.hash.match(/^#\/collections\/([^/?#]+)\/entries/),a=b?decodeURIComponent(b[1]):null,l=()=>Be.test(location.hash)&&m.isConnected&&location.hash.includes(`/collections/${encodeURIComponent(a)}/entries`),c=e=>(Ke.add(e),e);if(!a){E.toast("No collection selected.",{type:"error"});return}const u=M.observable(null),r=M.observable([]),x=M.observable(0),Y=M.observable(!0),H=M.observable(""),We=M.computed(()=>u.value!==null),re=M.observable(""),w=M.observable([]),Z=M.observable({key:"created",dir:"desc"}),g=M.observable([]),N=M.observable(X),V=M.observable([]),Q=M.observable({}),L=M.observable(!1);let ee=1;const te=()=>u.peek()?.fields||[],de=M.computed(()=>gt(u.value?.fields)),J=e=>r.peek().find(t=>t.id===e),Ee=e=>V.peek().filter(t=>{const n=Q.peek()[t.slug];return n==null||n.has(e)}),D=M.observable([]),ke=M.observable([]);c(M.effect(()=>{const e=bt(r.value,{filters:w.value,query:re.value,sort:Z.value});D.value=e})),c(M.effect(()=>{const e=de.value,t=new Set(g.value);Q.value,V.value,ke.value=D.value.slice(0,N.value).map(n=>{const o={id:n.id,sel:t.has(n.id),rowCls:t.has(n.id)?"is-selected":""};e.forEach((i,h)=>{const d=be(i,n.data?.[i.name]);o[`c${h}`]=Pe(d),o[`t${h}`]=ge(d)});const s=n.meta?.createdAt;o.when=s?Lt(s):"",o.whenFull=s?`Created ${_(s)}${n.meta?.updatedAt?` \xB7 changed ${_(n.meta.updatedAt)}`:""}`:"";const f=Ee(n.id).length;return o.runs=f?String(f):"",o})}));const Ge=M.computed(()=>w.value.map((e,t)=>({key:`${t}:${e.field}:${e.op}:${e.value}`,idx:t,text:Ct(e)}))),Xe=M.computed(()=>g.value.length),Ye={schema:u,loaded:r,loading:Y,loadError:H,ready:We,query:re,rows:ke,chips:Ge,busy:L,selectedCount:Xe,countLine:M.computed(()=>kt(D.value.length,r.value.length,x.value)),selectedText:M.computed(()=>`${g.value.length} selected`),canClear:M.computed(()=>Et(a)),introText:M.computed(()=>{const e=u.value;return e?`${e.description?`${e.description} - `:""}${(e.fields||[]).length} field${(e.fields||[]).length===1?"":"s"}${e.storage?.adapter==="mongodb"?", on MongoDB":""}.`:""}),emptyText:M.computed(()=>r.value.length?"No entries match the search or filters.":"No entries yet - Add entry in the banner makes one, or Import brings many."),moreText:M.computed(()=>{const e=D.value.length-N.value;if(e>0)return`Show ${Math.min(X,e)} more (${e} not shown)`;const t=x.value-r.value.length;return t>0?`Load the next ${Math.min(ce,t)} from the server`:""})};async function K({reset:e=!0,pending:t=null}={}){Y.value=!0;try{const n=e?Math.max(ce,r.peek().length):ce;e&&(ee=1);const o=await k.collections.listEntries(a,{limit:n,page:ee});if(t&&await t.done(),!l())return;const s=o?.entries||(Array.isArray(o)?o:[]);r.value=e?s:[...r.peek(),...s.filter(i=>!J(i.id))],x.value=Number(o?.total)||r.peek().length,e&&(ee=Math.max(1,Math.ceil(r.peek().length/ce)));const f=new Set(r.peek().map(i=>i.id));g.value=g.peek().filter(i=>f.has(i)),H.value="",await et()}catch(n){H.value=`Could not load the entries: ${n.message||n}`}finally{t&&await t.done(),Y.value=!1}}async function Ze(){ee+=1,await K({reset:!1})}async function Qe(){try{if((await ft("/actions/_count",{method:"GET"}).catch(()=>null))?.available===!1)return;const t=await k.actions.forCollection(a);V.value=Array.isArray(t)?t.filter(n=>n.canRun!==!1):[]}catch{V.value=[]}}async function et(){const e=V.peek().filter(o=>o.access?.rowLevel);if(!e.length||!r.peek().length)return;const t=r.peek().map(o=>o.id),n={...Q.peek()};await Promise.all(e.map(async o=>{try{n[o.slug]=new Set((await k.actions.checkAccess(o.slug,t)).allowed)}catch{n[o.slug]=null}})),Q.value=n}const W=e=>{const t=te()[0];return(t?Pe(be(t,e?.data?.[t.name]),40):"")||`Entry ${String(e?.id||"").slice(0,8)}`};async function xe(e){if(await E.confirm(`Delete \u201C${U(W(e))}\u201D? This cannot be undone.`))try{await k.collections.deleteEntry(a,e.id),r.value=r.peek().filter(t=>t.id!==e.id),x.value=Math.max(0,x.peek()-1),g.value=g.peek().filter(t=>t!==e.id),P("#/collections"),E.toast("Entry deleted.",{type:"success"})}catch(t){E.toast(`Not deleted: ${t.message||t}`,{type:"error"})}}async function tt(){const e=[...g.peek()];if(!e.length||!await E.confirm(`Delete ${e.length} entr${e.length===1?"y":"ies"}? This cannot be undone.`))return;L.value=!0;let t=0;const n=[];for(const o of e)try{await k.collections.deleteEntry(a,o),t++}catch(s){n.push(s.message||String(s))}L.value=!1,g.value=[],P("#/collections"),E.toast(n.length?`Deleted ${t}; ${n.length} refused (${n[0]}).`:`Deleted ${t} entr${t===1?"y":"ies"}.`,{type:n.length?"warning":"success",duration:n.length?7e3:4e3}),l()&&await K()}async function nt(){const e=u.peek();if(await E.confirm(`Delete ALL ${x.peek()} entries in \u201C${U(e?.title||a)}\u201D? This cannot be undone.`)){L.value=!0;try{await k.collections.clearEntries(a),r.value=[],x.value=0,g.value=[],P("#/collections"),E.toast("All entries deleted.",{type:"success"})}catch(t){E.toast(`Not cleared: ${t.message||t}`,{type:"error"})}finally{L.value=!1}}}async function at(e){try{const t=await k.collections.createEntry(a,{...e.data||{}});r.value=[t,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Duplicated - the copy is at the top.",{type:"success"})}catch(t){E.toast(`Not duplicated: ${t.message||t}`,{type:"error"})}}async function st(e,t){const n=e.trigger?.confirmMessage;if(!(n&&!await E.confirm(U(n)))){L.value=!0;try{const o=await k.actions.execute(e.slug,t.id);if(o?.success){const s=o.stepsCompleted??0;E.toast(`${e.trigger?.label||e.title||"Action"} done (${s} step${s===1?"":"s"}).`,{type:"success"}),l()&&await K()}else E.toast(o?.results?.find(s=>!s.success)?.error||"The action failed.",{type:"error"})}catch(o){E.toast(o.message||"The action failed.",{type:"error"})}finally{L.value=!1}}}async function we(e){try{await navigator.clipboard.writeText(e),E.toast("Copied.",{type:"success",duration:1500})}catch{E.toast("Copy failed - your browser refused the clipboard.",{type:"error"})}}function ue(e){const t=g.peek();g.value=t.includes(e)?t.filter(n=>n!==e):[...t,e]}function Se(e,t,n){w.value=[...w.peek(),{field:e.name,label:e.label||e.name,op:t,value:n}],N.value=X}const pe=new Set;let O=null,Ce=!1;function $e(e,t,n){const o=e.close.bind(e);let s=!1,f=!1;e.close=async i=>{if(!s&&i!==!0&&!Ce&&t()){if(f)return;f=!0;const h=await E.confirm(n);if(f=!1,!h)return}return s=!0,o()}}function ne(e,t=()=>{}){pe.add(e),yt(e,()=>{pe.delete(e),t()})}function z(e,t=null){const n=u.peek(),o=te().filter(y=>Nt(y,e?.data)),s=te().filter(y=>!o.includes(y)),f=Object.fromEntries(o.filter(y=>e?.data&&y.name in e.data).map(y=>[y.name,e.data[y.name]])),i=!!e,h=E.slideover({title:i?`Edit ${U(W(e))}`:"New entry",size:"md",position:"right"}),d=le(`
7
+ </tr>`}const It=(p,m)=>p?.type==="file"||ve(m?.[p?.name]);function He(p){const m=document.createElement("ul");m.className="cex-files";for(const v of St(p)){const a=document.createElement("li"),l=Mt(v.url),c=document.createElement(l?"a":"span");l&&(c.href=l,c.target="_blank",c.rel="noopener",ft(c,v)),c.textContent=ge(v),a.appendChild(c),m.appendChild(a)}return m}function Dt(p,m){const v={};return p.forEach(a=>{const l={};a.fullWidth?l.span=m:a.span>1&&(l.span=a.span),a.placeholder&&(l.placeholder=a.placeholder),a.helper&&(l.hint=a.helper),a.prefix&&(l.prefix=a.prefix),a.suffix&&(l.suffix=a.suffix);for(const u of["clear","stepper","counter"])a[u]===!0&&(l[u]=!0);const c=a.type==="checkbox"?"boolean":a.type==="date"?"string":a.type;v[a.name]={type:c,label:a.label,required:a.required,options:a.options,...Object.keys(l).length?{formConfig:l}:{}}}),v}function Ve(p,m){const v=CSS.escape(m);return[...p.querySelectorAll(`[name="${v}"], [name="${v}[]"]`)]}function ie(p,m){const v={};for(const a of m){const l=Ve(p,a.name);if(!l.length)continue;const c=l[0];c.type==="radio"?v[a.name]=l.find(u=>u.checked)?.value??"":c.type==="checkbox"&&(l.length>1||c.name.endsWith("[]"))?v[a.name]=l.filter(u=>u.checked).map(u=>u.value):c.type==="checkbox"?v[a.name]=c.checked:c.tagName==="SELECT"&&c.multiple?v[a.name]=[...c.selectedOptions].map(u=>u.value):v[a.name]=Lt(a,c.value)}return v}function Je(p,m,v){for(const a of m){if(!(a.name in v))continue;const l=v[a.name],c=Ve(p,a.name);if(!c.length)continue;const u=c[0];u.type==="radio"?c.forEach(r=>{r.checked=r.value===String(l)}):u.type==="checkbox"&&(c.length>1||u.name.endsWith("[]"))?c.forEach(r=>{r.checked=Array.isArray(l)&&l.includes(r.value)}):u.type==="checkbox"?u.checked=l===!0:u.tagName==="SELECT"&&u.multiple?[...u.options].forEach(r=>{r.selected=Array.isArray(l)&&l.includes(r.value)}):u.value=l??"",c.forEach(r=>r.dispatchEvent(new Event("input",{bubbles:!0})))}}const Ke=bt(Be);export const collectionEntriesView={templateUrl:"/admin/js/templates/collection-entries.html",async onMount(p){Ke.reset();const m=p.get(0).querySelector(".cex")||p.get(0),v=location.hash.match(/^#\/collections\/([^/?#]+)\/entries/),a=v?decodeURIComponent(v[1]):null,l=()=>Be.test(location.hash)&&m.isConnected&&location.hash.includes(`/collections/${encodeURIComponent(a)}/entries`),c=e=>(Ke.add(e),e);if(!a){E.toast("No collection selected.",{type:"error"});return}const u=M.observable(null),r=M.observable([]),x=M.observable(0),Y=M.observable(!0),H=M.observable(""),We=M.computed(()=>u.value!==null),re=M.observable(""),w=M.observable([]),Z=M.observable({key:"created",dir:"desc"}),g=M.observable([]),N=M.observable(X),V=M.observable([]),Q=M.observable({}),L=M.observable(!1);let ee=1;const te=()=>u.peek()?.fields||[],de=M.computed(()=>Et(u.value?.fields)),J=e=>r.peek().find(t=>t.id===e),Ee=e=>V.peek().filter(t=>{const n=Q.peek()[t.slug];return n==null||n.has(e)}),D=M.observable([]),ke=M.observable([]);c(M.effect(()=>{const e=gt(r.value,{filters:w.value,query:re.value,sort:Z.value});D.value=e})),c(M.effect(()=>{const e=de.value,t=new Set(g.value);Q.value,V.value,ke.value=D.value.slice(0,N.value).map(n=>{const o={id:n.id,sel:t.has(n.id),rowCls:t.has(n.id)?"is-selected":""};e.forEach((i,h)=>{const d=be(i,n.data?.[i.name]);o[`c${h}`]=Pe(d),o[`t${h}`]=ge(d)});const s=n.meta?.createdAt;o.when=s?qt(s):"",o.whenFull=s?`Created ${_(s)}${n.meta?.updatedAt?` \xB7 changed ${_(n.meta.updatedAt)}`:""}`:"";const f=Ee(n.id).length;return o.runs=f?String(f):"",o})}));const Ge=M.computed(()=>w.value.map((e,t)=>({key:`${t}:${e.field}:${e.op}:${e.value}`,idx:t,text:$t(e)}))),Xe=M.computed(()=>g.value.length),Ye={schema:u,loaded:r,loading:Y,loadError:H,ready:We,query:re,rows:ke,chips:Ge,busy:L,selectedCount:Xe,countLine:M.computed(()=>xt(D.value.length,r.value.length,x.value)),selectedText:M.computed(()=>`${g.value.length} selected`),canClear:M.computed(()=>kt(a)),introText:M.computed(()=>{const e=u.value;return e?`${e.description?`${e.description} - `:""}${(e.fields||[]).length} field${(e.fields||[]).length===1?"":"s"}${e.storage?.adapter==="mongodb"?", on MongoDB":""}.`:""}),emptyText:M.computed(()=>r.value.length?"No entries match the search or filters.":"No entries yet - Add entry in the banner makes one, or Import brings many."),moreText:M.computed(()=>{const e=D.value.length-N.value;if(e>0)return`Show ${Math.min(X,e)} more (${e} not shown)`;const t=x.value-r.value.length;return t>0?`Load the next ${Math.min(ce,t)} from the server`:""})};async function K({reset:e=!0,pending:t=null}={}){Y.value=!0;try{const n=e?Math.max(ce,r.peek().length):ce;e&&(ee=1);const o=await k.collections.listEntries(a,{limit:n,page:ee});if(t&&await t.done(),!l())return;const s=o?.entries||(Array.isArray(o)?o:[]);r.value=e?s:[...r.peek(),...s.filter(i=>!J(i.id))],x.value=Number(o?.total)||r.peek().length,e&&(ee=Math.max(1,Math.ceil(r.peek().length/ce)));const f=new Set(r.peek().map(i=>i.id));g.value=g.peek().filter(i=>f.has(i)),H.value="",await et()}catch(n){H.value=`Could not load the entries: ${n.message||n}`}finally{t&&await t.done(),Y.value=!1}}async function Ze(){ee+=1,await K({reset:!1})}async function Qe(){try{if((await mt("/actions/_count",{method:"GET"}).catch(()=>null))?.available===!1)return;const t=await k.actions.forCollection(a);V.value=Array.isArray(t)?t.filter(n=>n.canRun!==!1):[]}catch{V.value=[]}}async function et(){const e=V.peek().filter(o=>o.access?.rowLevel);if(!e.length||!r.peek().length)return;const t=r.peek().map(o=>o.id),n={...Q.peek()};await Promise.all(e.map(async o=>{try{n[o.slug]=new Set((await k.actions.checkAccess(o.slug,t)).allowed)}catch{n[o.slug]=null}})),Q.value=n}const W=e=>{const t=te()[0];return(t?Pe(be(t,e?.data?.[t.name]),40):"")||`Entry ${String(e?.id||"").slice(0,8)}`};async function xe(e){if(await E.confirm(`Delete \u201C${U(W(e))}\u201D? This cannot be undone.`))try{await k.collections.deleteEntry(a,e.id),r.value=r.peek().filter(t=>t.id!==e.id),x.value=Math.max(0,x.peek()-1),g.value=g.peek().filter(t=>t!==e.id),P("#/collections"),E.toast("Entry deleted.",{type:"success"})}catch(t){E.toast(`Not deleted: ${t.message||t}`,{type:"error"})}}async function tt(){const e=[...g.peek()];if(!e.length||!await E.confirm(`Delete ${e.length} entr${e.length===1?"y":"ies"}? This cannot be undone.`))return;L.value=!0;let t=0;const n=[];for(const o of e)try{await k.collections.deleteEntry(a,o),t++}catch(s){n.push(s.message||String(s))}L.value=!1,g.value=[],P("#/collections"),E.toast(n.length?`Deleted ${t}; ${n.length} refused (${n[0]}).`:`Deleted ${t} entr${t===1?"y":"ies"}.`,{type:n.length?"warning":"success",duration:n.length?7e3:4e3}),l()&&await K()}async function nt(){const e=u.peek();if(await E.confirm(`Delete ALL ${x.peek()} entries in \u201C${U(e?.title||a)}\u201D? This cannot be undone.`)){L.value=!0;try{await k.collections.clearEntries(a),r.value=[],x.value=0,g.value=[],P("#/collections"),E.toast("All entries deleted.",{type:"success"})}catch(t){E.toast(`Not cleared: ${t.message||t}`,{type:"error"})}finally{L.value=!1}}}async function at(e){try{const t=await k.collections.createEntry(a,{...e.data||{}});r.value=[t,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Duplicated - the copy is at the top.",{type:"success"})}catch(t){E.toast(`Not duplicated: ${t.message||t}`,{type:"error"})}}async function st(e,t){const n=e.trigger?.confirmMessage;if(!(n&&!await E.confirm(U(n)))){L.value=!0;try{const o=await k.actions.execute(e.slug,t.id);if(o?.success){const s=o.stepsCompleted??0;E.toast(`${e.trigger?.label||e.title||"Action"} done (${s} step${s===1?"":"s"}).`,{type:"success"}),l()&&await K()}else E.toast(o?.results?.find(s=>!s.success)?.error||"The action failed.",{type:"error"})}catch(o){E.toast(o.message||"The action failed.",{type:"error"})}finally{L.value=!1}}}async function we(e){try{await navigator.clipboard.writeText(e),E.toast("Copied.",{type:"success",duration:1500})}catch{E.toast("Copy failed - your browser refused the clipboard.",{type:"error"})}}function ue(e){const t=g.peek();g.value=t.includes(e)?t.filter(n=>n!==e):[...t,e]}function Se(e,t,n){w.value=[...w.peek(),{field:e.name,label:e.label||e.name,op:t,value:n}],N.value=X}const pe=new Set;let O=null,Ce=!1;function $e(e,t,n){const o=e.close.bind(e);let s=!1,f=!1;e.close=async i=>{if(!s&&i!==!0&&!Ce&&t()){if(f)return;f=!0;const h=await E.confirm(n);if(f=!1,!h)return}return s=!0,o()}}function ne(e,t=()=>{}){pe.add(e),vt(e,()=>{pe.delete(e),t()})}function z(e,t=null){const n=u.peek(),o=te().filter(y=>It(y,e?.data)),s=te().filter(y=>!o.includes(y)),f=Object.fromEntries(o.filter(y=>e?.data&&y.name in e.data).map(y=>[y.name,e.data[y.name]])),i=!!e,h=E.slideover({title:i?`Edit ${U(W(e))}`:"New entry",size:"md",position:"right"}),d=le(`
8
8
  <div class="cex-form">
9
9
  <div class="cex-fields"></div>
10
10
  <small class="cex-hint cex-when-line"></small>
@@ -15,7 +15,7 @@ import{api as k,apiRequest as ft}from"../api.js";import{addBannerAction as j}fro
15
15
  <button type="button" class="btn btn-sm btn-ghost" data-act="cancel">Cancel</button>
16
16
  <button type="button" class="btn btn-sm btn-primary" data-act="save"><span data-icon="check" data-icon-size="13"></span> <span class="cex-save-text"></span></button>
17
17
  </div>
18
- </div>`);d.querySelector(".cex-save-text").textContent=i?"Save":"Add entry";const v=d.querySelector(".cex-fields");for(const y of o){if(!ve(f[y.name]))continue;const $=document.createElement("div");$.className="cex-files-field";const T=document.createElement("span");T.textContent=y.label||y.name,$.append(T,He(f[y.name])),v.before($)}F.create(It(s,n?.columns||2),e?.data||{},{layout:n?.layout||"stacked",columns:n?.columns||2,showSubmitButton:!1}).renderTo(v),s.forEach(y=>{if(y.type!=="date"||!y.name)return;const $=v.querySelector(`[name="${CSS.escape(y.name)}"]`);$&&$.type!=="date"&&($.type="date")}),e?.data&&Je(v,s,e.data),i&&e.meta?.createdAt&&(d.querySelector(".cex-when-line").textContent=`Created ${_(e.meta.createdAt)}${e.meta.updatedAt?`, last changed ${_(e.meta.updatedAt)}`:""}${e.meta.source?` \xB7 via ${e.meta.source}`:""}.`),h.element.appendChild(d);const ut=_e(ie(v,s));t&&Je(v,s,t);const me=()=>_e(ie(v,s))!==ut,pt=d.querySelector(".cex-dirty"),he=()=>{pt.hidden=!me()};v.addEventListener("input",he),v.addEventListener("change",he),he();let ye=!1;async function Re(){if(ye)return;document.activeElement?.dispatchEvent?.(new Event("change",{bubbles:!0}));const y={...i?e.data:{},...ie(v,s),...f};ye=!0;const $=d.querySelector('[data-act="save"]');$.disabled=!0;try{if(i){const T=await k.collections.updateEntry(a,e.id,y);r.value=r.peek().map(Ue=>Ue.id===e.id?T:Ue),E.toast("Entry saved.",{type:"success"})}else{const T=await k.collections.createEntry(a,y);r.value=[T,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Entry added.",{type:"success"})}try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}h.close(!0)}catch(T){E.toast(T.message||"Not saved.",{type:"error"})}finally{ye=!1,$.disabled=!1}}d.querySelector('[data-act="save"]').addEventListener("click",Re),d.querySelector('[data-act="cancel"]').addEventListener("click",()=>h.close()),d.addEventListener("keydown",y=>{(y.ctrlKey||y.metaKey)&&(y.key==="Enter"||y.key==="s")&&(y.preventDefault(),Re())});const Fe={id:e?.id??null,dirty:me,values:()=>xt(ie(v,s),s)};O=Fe,ne(h,()=>{O===Fe&&(O=null)}),$e(h,me,"Discard the changes you have not saved?"),I.scan(d),h.open(),v.querySelector("input, select, textarea")?.focus()}function ot(e){const t=E.slideover({title:U(W(e)),size:"md",position:"right"}),n=le(`
18
+ </div>`);d.querySelector(".cex-save-text").textContent=i?"Save":"Add entry";const b=d.querySelector(".cex-fields");for(const y of o){if(!ve(f[y.name]))continue;const $=document.createElement("div");$.className="cex-files-field";const T=document.createElement("span");T.textContent=y.label||y.name,$.append(T,He(f[y.name])),b.before($)}F.create(Dt(s,n?.columns||2),e?.data||{},{layout:n?.layout||"stacked",columns:n?.columns||2,showSubmitButton:!1}).renderTo(b),s.forEach(y=>{if(y.type!=="date"||!y.name)return;const $=b.querySelector(`[name="${CSS.escape(y.name)}"]`);$&&$.type!=="date"&&($.type="date")}),e?.data&&Je(b,s,e.data),i&&e.meta?.createdAt&&(d.querySelector(".cex-when-line").textContent=`Created ${_(e.meta.createdAt)}${e.meta.updatedAt?`, last changed ${_(e.meta.updatedAt)}`:""}${e.meta.source?` \xB7 via ${e.meta.source}`:""}.`),h.element.appendChild(d);const ut=_e(ie(b,s));t&&Je(b,s,t);const me=()=>_e(ie(b,s))!==ut,pt=d.querySelector(".cex-dirty"),he=()=>{pt.hidden=!me()};b.addEventListener("input",he),b.addEventListener("change",he),he();let ye=!1;async function Re(){if(ye)return;document.activeElement?.dispatchEvent?.(new Event("change",{bubbles:!0}));const y={...i?e.data:{},...ie(b,s),...f};ye=!0;const $=d.querySelector('[data-act="save"]');$.disabled=!0;try{if(i){const T=await k.collections.updateEntry(a,e.id,y);r.value=r.peek().map(Ue=>Ue.id===e.id?T:Ue),E.toast("Entry saved.",{type:"success"})}else{const T=await k.collections.createEntry(a,y);r.value=[T,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Entry added.",{type:"success"})}try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}h.close(!0)}catch(T){E.toast(T.message||"Not saved.",{type:"error"})}finally{ye=!1,$.disabled=!1}}d.querySelector('[data-act="save"]').addEventListener("click",Re),d.querySelector('[data-act="cancel"]').addEventListener("click",()=>h.close()),d.addEventListener("keydown",y=>{(y.ctrlKey||y.metaKey)&&(y.key==="Enter"||y.key==="s")&&(y.preventDefault(),Re())});const Fe={id:e?.id??null,dirty:me,values:()=>wt(ie(b,s),s)};O=Fe,ne(h,()=>{O===Fe&&(O=null)}),$e(h,me,"Discard the changes you have not saved?"),I.scan(d),h.open(),b.querySelector("input, select, textarea")?.focus()}function ot(e){const t=E.slideover({title:U(W(e)),size:"md",position:"right"}),n=le(`
19
19
  <div class="cex-form">
20
20
  <dl class="cex-detail"></dl>
21
21
  <div class="cex-meta"></div>
@@ -24,7 +24,7 @@ import{api as k,apiRequest as ft}from"../api.js";import{addBannerAction as j}fro
24
24
  <span class="cex-spacer"></span>
25
25
  <button type="button" class="btn btn-sm btn-primary" data-act="edit"><span data-icon="edit" data-icon-size="13"></span> Edit</button>
26
26
  </div>
27
- </div>`),o=n.querySelector(".cex-detail");for(const i of te()){const h=ge(be(i,e.data?.[i.name])),d=document.createElement("dt");d.textContent=i.label||i.name;const v=document.createElement("dd");ve(e.data?.[i.name])?v.appendChild(He(e.data[i.name])):v.textContent=h===""?"-":h,o.append(d,v)}const s=n.querySelector(".cex-meta"),f=i=>{const h=document.createElement("span");h.textContent=i,s.appendChild(h)};f(`Id: ${e.id}`),e.meta?.createdAt&&f(`Created: ${_(e.meta.createdAt)}`),e.meta?.updatedAt&&f(`Changed: ${_(e.meta.updatedAt)}`),e.meta?.source&&f(`Source: ${e.meta.source}`),n.querySelector('[data-act="copy"]').addEventListener("click",()=>we(JSON.stringify(e,null,2))),n.querySelector('[data-act="edit"]').addEventListener("click",()=>{t.close(!0),z(e)}),t.element.appendChild(n),ne(t),I.scan(n),t.open()}function ct(){const e=E.slideover({title:"Import entries",size:"md",position:"right"}),t=le(`
27
+ </div>`),o=n.querySelector(".cex-detail");for(const i of te()){const h=ge(be(i,e.data?.[i.name])),d=document.createElement("dt");d.textContent=i.label||i.name;const b=document.createElement("dd");ve(e.data?.[i.name])?b.appendChild(He(e.data[i.name])):b.textContent=h===""?"-":h,o.append(d,b)}const s=n.querySelector(".cex-meta"),f=i=>{const h=document.createElement("span");h.textContent=i,s.appendChild(h)};f(`Id: ${e.id}`),e.meta?.createdAt&&f(`Created: ${_(e.meta.createdAt)}`),e.meta?.updatedAt&&f(`Changed: ${_(e.meta.updatedAt)}`),e.meta?.source&&f(`Source: ${e.meta.source}`),n.querySelector('[data-act="copy"]').addEventListener("click",()=>we(JSON.stringify(e,null,2))),n.querySelector('[data-act="edit"]').addEventListener("click",()=>{t.close(!0),z(e)}),t.element.appendChild(n),ne(t),I.scan(n),t.open()}function ct(){const e=E.slideover({title:"Import entries",size:"md",position:"right"}),t=le(`
28
28
  <div class="cex-form">
29
29
  <p class="cex-hint">A JSON array of entries, each with a "data" object of field values - what Export gives you.
30
30
  <span data-help="Each entry is added as new, with a new id and today's date (the Data Transfer plugin from the Marketplace keeps ids and dates). Entries are checked like any other save - one that fails, or points a reference at an entry that does not exist, is skipped and reported. Values are stored as given, including fields the collection does not have."></span></p>
@@ -40,11 +40,11 @@ import{api as k,apiRequest as ft}from"../api.js";import{addBannerAction as j}fro
40
40
  <button type="button" class="btn btn-sm btn-ghost" data-act="cancel">Cancel</button>
41
41
  <button type="button" class="btn btn-sm btn-primary" data-act="import"><span data-icon="upload" data-icon-size="13"></span> Import</button>
42
42
  </div>
43
- </div>`),n=t.querySelector("textarea"),o=t.querySelector(".cex-err"),s=t.querySelector(".cex-ok"),f=t.querySelector('input[type="file"]');t.querySelector('[data-act="file"]').addEventListener("click",()=>f.click()),f.addEventListener("change",async()=>{const h=f.files?.[0];f.value="",h&&(n.value=await h.text())}),t.querySelector('[data-act="cancel"]').addEventListener("click",()=>e.close());let i=!1;t.querySelector('[data-act="import"]').addEventListener("click",async()=>{o.hidden=!0,s.hidden=!0;let h;try{if(h=JSON.parse(n.value),!Array.isArray(h))throw new Error("it must be a JSON array")}catch(v){o.textContent=`Not valid: ${v.message}`,o.hidden=!1;return}const d=t.querySelector('[data-act="import"]');d.disabled=!0;try{const v=await k.collections.import(a,h);s.textContent=`Imported ${v.imported}; skipped ${v.skipped}.`,s.hidden=!1,i=!0,P("#/collections"),l()&&await K(),setTimeout(()=>e.close(!0),1200)}catch(v){o.textContent=v.message||"Import failed.",o.hidden=!1}finally{d.disabled=!1}}),e.element.appendChild(t),ne(e),$e(e,()=>!i&&n.value.trim()!=="","Discard the entries you pasted?"),ze(t),I.scan(t),e.open(),n.focus()}function lt(){const e=E.slideover({title:"Export entries",size:"sm",position:"right"}),t=le(`
43
+ </div>`),n=t.querySelector("textarea"),o=t.querySelector(".cex-err"),s=t.querySelector(".cex-ok"),f=t.querySelector('input[type="file"]');t.querySelector('[data-act="file"]').addEventListener("click",()=>f.click()),f.addEventListener("change",async()=>{const h=f.files?.[0];f.value="",h&&(n.value=await h.text())}),t.querySelector('[data-act="cancel"]').addEventListener("click",()=>e.close());let i=!1;t.querySelector('[data-act="import"]').addEventListener("click",async()=>{o.hidden=!0,s.hidden=!0;let h;try{if(h=JSON.parse(n.value),!Array.isArray(h))throw new Error("it must be a JSON array")}catch(b){o.textContent=`Not valid: ${b.message}`,o.hidden=!1;return}const d=t.querySelector('[data-act="import"]');d.disabled=!0;try{const b=await k.collections.import(a,h);s.textContent=`Imported ${b.imported}; skipped ${b.skipped}.`,s.hidden=!1,i=!0,P("#/collections"),l()&&await K(),setTimeout(()=>e.close(!0),1200)}catch(b){o.textContent=b.message||"Import failed.",o.hidden=!1}finally{d.disabled=!1}}),e.element.appendChild(t),ne(e),$e(e,()=>!i&&n.value.trim()!=="","Discard the entries you pasted?"),ze(t),I.scan(t),e.open(),n.focus()}function lt(){const e=E.slideover({title:"Export entries",size:"sm",position:"right"}),t=le(`
44
44
  <div class="cex-form">
45
45
  <p class="cex-hint">Every entry in the collection - not only the ones shown.</p>
46
46
  <div class="cex-export">
47
47
  <button type="button" class="btn btn-ghost" data-fmt="json"><span data-icon="download" data-icon-size="14"></span> Export as JSON</button>
48
48
  <button type="button" class="btn btn-ghost" data-fmt="csv"><span data-icon="download" data-icon-size="14"></span> Export as CSV</button>
49
49
  </div>
50
- </div>`);t.querySelectorAll("[data-fmt]").forEach(n=>n.addEventListener("click",async()=>{const o=n.dataset.fmt;try{const s=await fetch(`/api/collections/${encodeURIComponent(a)}/export?format=${o}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!s.ok)throw new Error(`${s.status}`);const f=await s.blob(),i=document.createElement("a");i.href=URL.createObjectURL(f),i.download=`${a}-entries.${o}`,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(i.href),1e3),e.close(!0)}catch(s){E.toast(`Export failed (${s.message}).`,{type:"error"})}})),e.element.appendChild(t),ne(e),I.scan(t),e.open()}function it(e,t){const n=J(e.dataset.id);if(!n)return[];const o=t?.event?.target?.closest?.("td[data-col]"),s=o?de.peek()[Number(o.dataset.col)]:null,f=Ee(n.id),i=g.peek().includes(n.id),h=s?St(s,n.data?.[s.name]):[];return[{header:W(n)},{label:"Edit\u2026",icon:"edit",action:()=>z(n)},{label:"See all of it\u2026",icon:"eye",action:()=>ot(n)},{label:"Duplicate",icon:"copy",action:()=>at(n)},{label:"Copy id",icon:"hash",action:()=>we(n.id)},{label:i?"Deselect":"Select",icon:"check",action:()=>ue(n.id)},...f.length?[{type:"divider"},...f.map(d=>({label:`${d.trigger?.label||d.title||d.slug}\u2026`,icon:d.trigger?.icon||"zap",disabled:L.peek(),action:()=>st(d,n)}))]:[],...s?[{type:"divider"},{label:`Filter by ${s.label||s.name}`,icon:"filter",submenu:[...h.map(d=>({label:d.label,action:()=>Se(s,d.op,d.value)})),{label:`${s.label||s.name} contains\u2026`,action:async()=>{const d=await E.prompt(`Show entries whose ${U(s.label||s.name)} contains`,{inputPlaceholder:"text"});d&&String(d).trim()&&Se(s,"contains",String(d).trim())}}]}]:[],...w.peek().length?[{label:`Clear filters (${w.peek().length})`,icon:"x",action:()=>{w.value=[]}}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>xe(n)}]}const q=m.querySelector(".cex-rows"),G=m.querySelector(".cex-head"),fe=m.querySelector(".cex-chips-list");fe.innerHTML=qt;const ae=ht(m.querySelector(".dm-loading-slot"),mt.table);try{u.value=await k.collections.get(a)}catch(e){H.value=`Could not load the collection: ${e.message||e}`}if(!l()){ae.done();return}if(!u.peek()&&(await ae.done(),!H.peek())){E.toast("Collection not found.",{type:"error"}),R.navigate("/collections");return}const Ae=de.peek();q.innerHTML=Tt(Ae.length),G.replaceChildren();const se=(e,t)=>{const n=document.createElement("th");return e&&(n.className=e),t&&n.append(t),G.appendChild(n),n},A=document.createElement("input");A.type="checkbox",A.title="Select every entry shown",A.setAttribute("aria-label","Select every entry shown"),se("cex-check",A);const Me=(e,t)=>{const n=document.createElement("button");return n.type="button",n.dataset.sort=e,n.append(document.createTextNode(t),Object.assign(document.createElement("span"),{className:"cex-sort"})),n};Ae.forEach(e=>se("",Me(e.name,e.label||e.name))),se("cex-when",Me("created","Created")),se("cex-tools"),c(M.effect(()=>{const e=Z.value;G.querySelectorAll("[data-sort]").forEach(t=>{t.querySelector(".cex-sort").textContent=t.dataset.sort===e.key?e.dir==="asc"?"\u25B2":"\u25BC":"",t.parentElement.setAttribute("aria-sort",t.dataset.sort===e.key?e.dir==="asc"?"ascending":"descending":"none")})})),c(M.effect(()=>{const e=D.value.map(n=>n.id),t=new Set(g.value);A.checked=e.length>0&&e.every(n=>t.has(n)),A.indeterminate=!A.checked&&e.some(n=>t.has(n))}));const Le=e=>{const t=e.target.closest("[data-sort]");if(!t)return;const n=Z.peek();Z.value={key:t.dataset.sort,dir:n.key===t.dataset.sort&&n.dir==="asc"?"desc":"asc"}};G.addEventListener("click",Le),A.addEventListener("change",()=>{const e=D.peek().map(t=>t.id);g.value=A.checked?[...new Set([...g.peek(),...e])]:g.peek().filter(t=>!e.includes(t))}),c(()=>G.removeEventListener("click",Le));const rt=M.applyBindings(Ye,m,{methods:{clearSelection:()=>{g.value=[]},deleteSelected:()=>tt(),clearAll:()=>nt(),clearFilters:()=>{w.value=[]},showMore:()=>{D.peek().length>N.peek()?N.value=N.peek()+X:Ze()}}});c(()=>rt.dispose()),c(ze(m,{position:"bottom"})),c(M.effect(()=>{re.value,w.value,N.value=X}));const qe=e=>{const t=e.target.closest("button[data-idx]");if(!t)return;const n=Number(t.dataset.idx);w.value=w.peek().filter((o,s)=>s!==n)};fe.addEventListener("click",qe),c(()=>fe.removeEventListener("click",qe));const dt=E.contextMenu(q,{cursor:"glyph",match:".cex-row",inherit:!1,density:"compact",items:(e,t)=>it(e,t)});c(()=>dt?.destroy?.());const Te=e=>{const t=e.target.closest(".cex-row");if(!t)return;if(e.target.closest(".cex-kebab, .cex-run")){je(e.target.closest(".cex-kebab, .cex-run"));return}if(e.target.closest(".cex-check"))return;const n=J(t.dataset.id);n&&z(n)},Ne=e=>{if(!e.target.matches(".cex-sel"))return;const t=e.target.closest(".cex-row");t&&ue(t.dataset.id)},Ie=e=>{const t=e.target.closest(".cex-row");if(!t||e.target!==t)return;const n=J(t.dataset.id);n&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),je(t)):e.key==="Enter"?(e.preventDefault(),z(n)):e.key===" "?(e.preventDefault(),ue(n.id)):e.key==="Delete"&&(e.preventDefault(),xe(n)))};q.addEventListener("click",Te),q.addEventListener("change",Ne),q.addEventListener("keydown",Ie),c(()=>{q.removeEventListener("click",Te),q.removeEventListener("change",Ne),q.removeEventListener("keydown",Ie)});const De=u.peek(),oe=p.get(0).querySelector(".dm-plugin-banner-name")?.querySelector(".dm-plugin-banner-sep");if(oe&&De?.title){for(;oe.nextSibling;)oe.nextSibling.remove();oe.after(document.createTextNode(De.title))}j(p,{id:"entries-back",icon:"arrow-left",title:"All collections",onClick:()=>{location.hash="#/collections"}}),j(p,{id:"entries-fields",icon:"edit-3",title:"Edit its fields and settings",onClick:()=>{location.hash=`#/collections/edit/${encodeURIComponent(a)}`}}),$t(a)&&j(p,{id:"entries-form",icon:"layout",title:"Open its form",onClick:()=>{location.hash=`#/forms/edit/${encodeURIComponent(a)}`}}),j(p,{id:"entries-export",icon:"download",title:"Export",onClick:()=>lt()}),j(p,{id:"entries-import",icon:"upload",title:"Import",onClick:()=>ct()}),j(p,{id:"entries-add",icon:"plus",title:"Add entry",onClick:()=>z(null)});const Oe=e=>{O?.dirty()&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Oe),c(()=>window.removeEventListener("beforeunload",Oe)),c(()=>{if(O?.dirty())try{S.set(B(a),{id:O.id,values:O.values(),at:new Date().toISOString()})}catch{}Ce=!0,[...pe].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(m),!u.peek()){Y.value=!1;return}if(await Qe(),!l()){ae.done();return}if(await K({pending:ae}),!l())return;let C=null;try{C=S.get(B(a))}catch{}if(C?.values){try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}let e=C.id?J(C.id):null;if(C.id&&!e&&(e=await k.collections.getEntry(a,C.id).catch(()=>null)),!l()||C.id&&!e)return;const t=e?`your changes to \u201C${U(W(e))}\u201D`:"a new entry",n=e?.meta?.updatedAt&&C.at&&e.meta.updatedAt>C.at?" It has been changed since - check before saving.":"";await E.confirm(`You left ${t} unsaved.${n} Pick up where you left off?`)&&l()&&z(e,C.values)}}};
50
+ </div>`);t.querySelectorAll("[data-fmt]").forEach(n=>n.addEventListener("click",async()=>{const o=n.dataset.fmt;try{const s=await fetch(`/api/collections/${encodeURIComponent(a)}/export?format=${o}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!s.ok)throw new Error(`${s.status}`);const f=await s.blob(),i=document.createElement("a");i.href=URL.createObjectURL(f),i.download=`${a}-entries.${o}`,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(i.href),1e3),e.close(!0)}catch(s){E.toast(`Export failed (${s.message}).`,{type:"error"})}})),e.element.appendChild(t),ne(e),I.scan(t),e.open()}function it(e,t){const n=J(e.dataset.id);if(!n)return[];const o=t?.event?.target?.closest?.("td[data-col]"),s=o?de.peek()[Number(o.dataset.col)]:null,f=Ee(n.id),i=g.peek().includes(n.id),h=s?Ct(s,n.data?.[s.name]):[];return[{header:W(n)},{label:"Edit\u2026",icon:"edit",action:()=>z(n)},{label:"See all of it\u2026",icon:"eye",action:()=>ot(n)},{label:"Duplicate",icon:"copy",action:()=>at(n)},{label:"Copy id",icon:"hash",action:()=>we(n.id)},{label:i?"Deselect":"Select",icon:"check",action:()=>ue(n.id)},...f.length?[{type:"divider"},...f.map(d=>({label:`${d.trigger?.label||d.title||d.slug}\u2026`,icon:d.trigger?.icon||"zap",disabled:L.peek(),action:()=>st(d,n)}))]:[],...s?[{type:"divider"},{label:`Filter by ${s.label||s.name}`,icon:"filter",submenu:[...h.map(d=>({label:d.label,action:()=>Se(s,d.op,d.value)})),{label:`${s.label||s.name} contains\u2026`,action:async()=>{const d=await E.prompt(`Show entries whose ${U(s.label||s.name)} contains`,{inputPlaceholder:"text"});d&&String(d).trim()&&Se(s,"contains",String(d).trim())}}]}]:[],...w.peek().length?[{label:`Clear filters (${w.peek().length})`,icon:"x",action:()=>{w.value=[]}}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>xe(n)}]}const q=m.querySelector(".cex-rows"),G=m.querySelector(".cex-head"),fe=m.querySelector(".cex-chips-list");fe.innerHTML=Tt;const ae=yt(m.querySelector(".dm-loading-slot"),ht.table);try{u.value=await k.collections.get(a)}catch(e){H.value=`Could not load the collection: ${e.message||e}`}if(!l()){ae.done();return}if(!u.peek()&&(await ae.done(),!H.peek())){E.toast("Collection not found.",{type:"error"}),R.navigate("/collections");return}const Ae=de.peek();q.innerHTML=Nt(Ae.length),G.replaceChildren();const se=(e,t)=>{const n=document.createElement("th");return e&&(n.className=e),t&&n.append(t),G.appendChild(n),n},A=document.createElement("input");A.type="checkbox",A.title="Select every entry shown",A.setAttribute("aria-label","Select every entry shown"),se("cex-check",A);const Me=(e,t)=>{const n=document.createElement("button");return n.type="button",n.dataset.sort=e,n.append(document.createTextNode(t),Object.assign(document.createElement("span"),{className:"cex-sort"})),n};Ae.forEach(e=>se("",Me(e.name,e.label||e.name))),se("cex-when",Me("created","Created")),se("cex-tools"),c(M.effect(()=>{const e=Z.value;G.querySelectorAll("[data-sort]").forEach(t=>{t.querySelector(".cex-sort").textContent=t.dataset.sort===e.key?e.dir==="asc"?"\u25B2":"\u25BC":"",t.parentElement.setAttribute("aria-sort",t.dataset.sort===e.key?e.dir==="asc"?"ascending":"descending":"none")})})),c(M.effect(()=>{const e=D.value.map(n=>n.id),t=new Set(g.value);A.checked=e.length>0&&e.every(n=>t.has(n)),A.indeterminate=!A.checked&&e.some(n=>t.has(n))}));const Le=e=>{const t=e.target.closest("[data-sort]");if(!t)return;const n=Z.peek();Z.value={key:t.dataset.sort,dir:n.key===t.dataset.sort&&n.dir==="asc"?"desc":"asc"}};G.addEventListener("click",Le),A.addEventListener("change",()=>{const e=D.peek().map(t=>t.id);g.value=A.checked?[...new Set([...g.peek(),...e])]:g.peek().filter(t=>!e.includes(t))}),c(()=>G.removeEventListener("click",Le));const rt=M.applyBindings(Ye,m,{methods:{clearSelection:()=>{g.value=[]},deleteSelected:()=>tt(),clearAll:()=>nt(),clearFilters:()=>{w.value=[]},showMore:()=>{D.peek().length>N.peek()?N.value=N.peek()+X:Ze()}}});c(()=>rt.dispose()),c(ze(m,{position:"bottom"})),c(M.effect(()=>{re.value,w.value,N.value=X}));const qe=e=>{const t=e.target.closest("button[data-idx]");if(!t)return;const n=Number(t.dataset.idx);w.value=w.peek().filter((o,s)=>s!==n)};fe.addEventListener("click",qe),c(()=>fe.removeEventListener("click",qe));const dt=E.contextMenu(q,{cursor:"glyph",match:".cex-row",inherit:!1,density:"compact",items:(e,t)=>it(e,t)});c(()=>dt?.destroy?.());const Te=e=>{const t=e.target.closest(".cex-row");if(!t)return;if(e.target.closest(".cex-kebab, .cex-run")){je(e.target.closest(".cex-kebab, .cex-run"));return}if(e.target.closest(".cex-check"))return;const n=J(t.dataset.id);n&&z(n)},Ne=e=>{if(!e.target.matches(".cex-sel"))return;const t=e.target.closest(".cex-row");t&&ue(t.dataset.id)},Ie=e=>{const t=e.target.closest(".cex-row");if(!t||e.target!==t)return;const n=J(t.dataset.id);n&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),je(t)):e.key==="Enter"?(e.preventDefault(),z(n)):e.key===" "?(e.preventDefault(),ue(n.id)):e.key==="Delete"&&(e.preventDefault(),xe(n)))};q.addEventListener("click",Te),q.addEventListener("change",Ne),q.addEventListener("keydown",Ie),c(()=>{q.removeEventListener("click",Te),q.removeEventListener("change",Ne),q.removeEventListener("keydown",Ie)});const De=u.peek(),oe=p.get(0).querySelector(".dm-plugin-banner-name")?.querySelector(".dm-plugin-banner-sep");if(oe&&De?.title){for(;oe.nextSibling;)oe.nextSibling.remove();oe.after(document.createTextNode(De.title))}j(p,{id:"entries-back",icon:"arrow-left",title:"All collections",onClick:()=>{location.hash="#/collections"}}),j(p,{id:"entries-fields",icon:"edit-3",title:"Edit its fields and settings",onClick:()=>{location.hash=`#/collections/edit/${encodeURIComponent(a)}`}}),At(a)&&j(p,{id:"entries-form",icon:"layout",title:"Open its form",onClick:()=>{location.hash=`#/forms/edit/${encodeURIComponent(a)}`}}),j(p,{id:"entries-export",icon:"download",title:"Export",onClick:()=>lt()}),j(p,{id:"entries-import",icon:"upload",title:"Import",onClick:()=>ct()}),j(p,{id:"entries-add",icon:"plus",title:"Add entry",onClick:()=>z(null)});const Oe=e=>{O?.dirty()&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Oe),c(()=>window.removeEventListener("beforeunload",Oe)),c(()=>{if(O?.dirty())try{S.set(B(a),{id:O.id,values:O.values(),at:new Date().toISOString()})}catch{}Ce=!0,[...pe].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(m),!u.peek()){Y.value=!1;return}if(await Qe(),!l()){ae.done();return}if(await K({pending:ae}),!l())return;let C=null;try{C=S.get(B(a))}catch{}if(C?.values){try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}let e=C.id?J(C.id):null;if(C.id&&!e&&(e=await k.collections.getEntry(a,C.id).catch(()=>null)),!l()||C.id&&!e)return;const t=e?`your changes to \u201C${U(W(e))}\u201D`:"a new entry",n=e?.meta?.updatedAt&&C.at&&e.meta.updatedAt>C.at?" It has been changed since - check before saving.":"";await E.confirm(`You left ${t} unsaved.${n} Pick up where you left off?`)&&l()&&z(e,C.values)}}};
@@ -1,4 +1,4 @@
1
- import{apiRequest as R}from"/admin/js/api.js";import{addBannerAction as Q}from"/admin/js/lib/plugin-chrome.js";import{SHAPES as Le,whileLoading as Re}from"/admin/js/lib/loading.js";import{helpPopovers as me}from"/admin/js/lib/help-popover.js";import{onceClosed as Oe,openMenuAt as pe,sidebarCount as Z,viewLifetime as Ie}from"/admin/js/lib/tool-kit.js";import{FILTERS as qe,answerFields as Ue,answerText as F,arrangeSubmissions as Fe,fileRefsOf as je,safeFileHref as ze,submissionCounts as Be,submissionRow as O,submissionText as Pe}from"/admin/js/lib/form-submissions-arrange.js";import{fmtDateTime as Ke}from"../lib/dates.js";import{openEmail as _e}from"../lib/mail-compose.js";const ue=/^#\/forms\/[^/?#]+\/submissions\/?(\?.*)?$/,ee="form-submissions.filter",He=`
1
+ import{apiRequest as O}from"/admin/js/api.js";import{addBannerAction as Q}from"/admin/js/lib/plugin-chrome.js";import{SHAPES as Re,whileLoading as Oe}from"/admin/js/lib/loading.js";import{helpPopovers as me}from"/admin/js/lib/help-popover.js";import{onceClosed as Ie,openMenuAt as pe,sidebarCount as Z,viewLifetime as qe}from"/admin/js/lib/tool-kit.js";import{FILTERS as Ue,answerFields as Fe,answerText as ee,arrangeSubmissions as Pe,fieldText as ue,fileRefsOf as je,safeFileHref as ze,submissionCounts as Be,submissionRow as q,submissionText as Ke}from"/admin/js/lib/form-submissions-arrange.js";import{fmtDateTime as _e}from"../lib/dates.js";import{openEmail as He}from"../lib/mail-compose.js";import{privateThumbnail as We,wirePrivateLink as Je}from"/admin/js/lib/private-files.js";const fe=/^#\/forms\/[^/?#]+\/submissions\/?(\?.*)?$/,te="form-submissions.filter",Ve=`
2
2
  <div class="fsx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
3
3
  <span class="fsx-dot" aria-hidden="true"></span>
4
4
  <span class="fsx-main"><strong>{{title}}</strong><small>{{meta}}</small></span>
@@ -8,4 +8,4 @@ import{apiRequest as R}from"/admin/js/api.js";import{addBannerAction as Q}from"/
8
8
  </span>
9
9
  <span class="fsx-when" title="{{whenFull}}">{{when}}</span>
10
10
  <button type="button" class="fsx-kebab" aria-label="Actions for this submission" title="Actions">\u22EE</button>
11
- </div>`,te=a=>String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),j=(a,i,p=`${i}s`)=>`${a} ${a===1?i:p}`,ne=a=>a?Ke(a):"";async function fe(a){try{return await navigator.clipboard.writeText(a),!0}catch{}try{const i=document.createElement("textarea");i.value=a,i.style.cssText="position:fixed;opacity:0;",document.body.appendChild(i),i.select();const p=document.execCommand("copy");return i.remove(),p}catch{return!1}}function he(a,i){const p=je(i);if(!p.length||p.length!==(Array.isArray(i)?i.length:1)){a.textContent=F(i);return}const m=document.createElement("ul");m.className="fsx-files";for(const d of p){const u=document.createElement("li"),c=ze(d.url),y=document.createElement(c?"a":"span");if(c&&(y.href=c,y.target="_blank",y.rel="noopener"),y.textContent=F(d),u.appendChild(y),Number(d.size)>0){const N=document.createElement("small");N.textContent=` ${Number(d.size)<1024?`${d.size} B`:`${Math.round(Number(d.size)/1024)} KB`}`,u.appendChild(N)}m.appendChild(u)}a.appendChild(m)}const x=Ie(ue);export const formSubmissionsView={templateUrl:"/admin/js/templates/form-submissions.html",async onMount(a){x.reset();const i=a.get(0).querySelector(".fsx")||a.get(0),p=()=>ue.test(location.hash)&&i.isConnected,m=decodeURIComponent((location.hash.match(/^#\/forms\/([^/?#]+)\/submissions/)||[])[1]||"");if(!m){E.toast("No form selected.",{type:"error"});return}const d=encodeURIComponent(m),u=M.observable(null),c=M.observable([]),y=M.observable(!0),N=M.observable("");let se="inbox";try{se=qe.includes(S.get(ee))?S.get(ee):"inbox"}catch{}const v=M.observable(se),oe=M.observable(""),z=M.observable(""),B=M.observable("");x.add(M.effect(()=>{const e=v.value;try{S.set(ee,e)}catch{}}));const T=M.computed(()=>Ue(u.value||{})),P=M.observable([]);x.add(M.effect(()=>{const e=Date.now(),t=Fe(c.value,{filter:v.value,query:oe.value,from:z.value,to:B.value,now:e}),n=T.value;P.value=t.map(r=>{const s=O(r,n,e);return{...s,when:s.at?D(s.at).fromNow():"",whenFull:ne(s.at)}})}));const be=M.computed(()=>Be(c.value)),ye=M.computed(()=>{const e=P.value.length,t=c.value.length;return t?e===t?j(t,"submission"):`${e} of ${j(t,"submission")}`:""}),Ee=M.computed(()=>c.value.length?v.value==="spam"?"Nothing marked as spam.":"No submissions match.":"No submissions yet - they appear here as people send the form."),we=M.computed(()=>u.value?`What people sent through "${u.value.title||m}".`:"What people sent through this form."),q=e=>c.peek().find(t=>String(t.id)===String(e));async function ge(){try{const[e,t]=await Re(i.querySelector(".dm-loading-slot"),Promise.all([R(`/forms/${d}`),R(`/forms/${d}/submissions`)]),Le.rows);if(!p())return;u.value=e||null,c.value=Array.isArray(t)?t:[],N.value="",xe(e?.title||m)}catch(e){if(!p())return;N.value=`Could not load the submissions: ${e.message||e}`}finally{y.value=!1}}function xe(e){const t=a.get(0).querySelector(".dm-plugin-banner-name"),n=t?.lastChild;n&&n.nodeType===Node.TEXT_NODE&&t.querySelector(".dm-plugin-banner-sep")&&(n.textContent=`${e} submissions`),document.title=`${e} - Submissions - Domma CMS`}const K=(e,t)=>ce(e.id,()=>ve(e,t)),_=e=>ce(e.id,()=>Ce(e));async function ve(e,t){try{const n=await R(`/forms/${d}/submissions/${encodeURIComponent(e.id)}/spam`,{method:"POST",body:JSON.stringify({spam:t})});return c.value=c.peek().map(r=>String(r.id)===String(e.id)?{...r,data:n?.entry?.data||{...r.data,spam:t}}:r),E.toast(t?"Marked as spam - it is under Spam now.":"Back in the inbox.",{type:"success"}),Z("#/forms"),!0}catch(n){return E.toast(`Not changed: ${n.message||n}`,{type:"error"}),!1}}async function Ce(e){const t=O(e,T.peek()).title;if(!await E.confirm(`Delete the submission from "${te(t)}"? This cannot be undone.`,{confirmText:"Delete"}))return!1;try{return await R(`/forms/${d}/submissions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c.value=c.peek().filter(n=>String(n.id)!==String(e.id)),E.toast("Submission deleted.",{type:"success"}),Z("#/forms"),!0}catch(n){return E.toast(`Not deleted: ${n.message||n}`,{type:"error"}),!1}}let H=!1;async function ke(){if(!H){H=!0;try{await Se()}finally{H=!1}}}async function Se(){const e=c.peek().length;if(!e){E.toast("There are no submissions to clear.",{type:"info"});return}const t=u.peek()?.title||m;if(await E.confirm(`Delete all ${j(e,"submission")} to "${te(t)}", spam included? This cannot be undone - Export them first if you may need them.`))try{await R(`/forms/${d}/submissions`,{method:"DELETE"}),c.value=[],E.toast("All submissions cleared.",{type:"success"}),Z("#/forms")}catch(n){E.toast(`Not cleared: ${n.message||n}`,{type:"error"})}}const ae=async e=>{const t=Pe(e,T.peek(),{formTitle:u.peek()?.title||m,when:ne(e.meta?.createdAt)});E.toast(await fe(t)?"Copied.":"Copy failed.",{type:"info"})},$e=async e=>{E.toast(await fe(e)?`Copied ${e}.`:"Copy failed.",{type:"info"})},ie=e=>{const t=O(e,T.peek()).email;t&&_e({to:[t],subject:`Re: ${u.peek()?.title||m}`})};async function Ne(e,t){try{const n=await fetch(`/api/forms/${d}/submissions/${e}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);const r=await n.blob(),s=document.createElement("a");return s.href=URL.createObjectURL(r),s.download=t,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(s.href),1e3),!0}catch(n){return E.toast(`Export failed: ${n.message||n}`,{type:"error"}),!1}}const W=new Set,U=new Set;function re(e,t,n,r="md"){if(U.has(e))return null;U.add(e);let s;try{s=E.slideover({title:te(t),size:r,position:"right"}),s.element.appendChild(n);const h=me(n);return W.add(s),Oe(s,()=>{U.delete(e),W.delete(s),h()}),I.scan(n),s.open(),s}catch(h){U.delete(e);try{s?.destroy?.(),s?.element?.remove()}catch{}return E.toast(`Could not open it: ${h.message||h}`,{type:"error"}),null}}const J=new Set;async function ce(e,t){const n=String(e);if(J.has(n))return!1;J.add(n);try{return await t()}finally{J.delete(n)}}function Te(){const e=c.peek().length,t=document.createElement("div");t.className="fsx-export";const n=document.createElement("p");n.className="fsx-note",n.textContent=e?`All ${j(e,"submission")}, spam included.`:"There are no submissions yet - the file will be empty.",t.appendChild(n);let r;const s=(h,C,G,X,A)=>{const l=document.createElement("button");l.type="button",l.className="btn btn-ghost";const k=document.createElement("span");k.setAttribute("data-icon",C),l.append(k,document.createTextNode(` ${h}`));const L=document.createElement("span");L.setAttribute("data-help",A),l.addEventListener("click",async()=>{if(!l.disabled){l.disabled=!0;try{await Ne(G,`${m}-submissions.${X}`)&&r?.close()}finally{l.disabled=!1}}});const o=document.createElement("div");o.append(l,L),t.appendChild(o)};s("Export as CSV","file-text","export","csv","One row per submission, one column per question - opens in Excel, Numbers or Google Sheets."),s("Export as JSON","code","export/json","json","Every submission exactly as stored, with its id and dates - for importing elsewhere or keeping a full copy."),r=re("export","Export submissions",t,"sm")}function V(e){if(!e)return;const t=T.peek(),n=O(e,t),r=document.createElement("div");r.className="fsx-detail";const s=document.createElement("div");s.className="fsx-facts";const h=o=>{const f=document.createElement("span");f.textContent=o,s.appendChild(f)};e.meta?.createdAt&&h(`Sent ${ne(e.meta.createdAt)} (${D(e.meta.createdAt).fromNow()})`),e.meta?.ip&&h(`IP ${e.meta.ip}`),n.spam&&h("Marked as spam"),r.appendChild(s);const C=document.createElement("dl");C.className="fsx-answers";const G=t.filter(o=>F(e.data?.[o.name])!=="");for(const o of G){const f=document.createElement("div");f.className="fsx-answer";const g=document.createElement("dt");g.textContent=o.label;const $=document.createElement("dd");he($,e.data[o.name]),f.append(g,$),C.appendChild(f)}const X=new Set(t.map(o=>o.name));for(const[o,f]of Object.entries(e.data||{})){if(X.has(o)||o==="spam"||F(f)==="")continue;const g=document.createElement("div");g.className="fsx-answer";const $=document.createElement("dt");$.textContent=`${o} (no longer on the form)`;const b=document.createElement("dd");he(b,f),g.append($,b),C.appendChild(g)}if(C.children.length)r.appendChild(C);else{const o=document.createElement("p");o.className="fsx-note",o.textContent="Nothing was filled in.",r.appendChild(o)}const A=document.createElement("div");A.className="fsx-actions";const l=(o,f,g,$)=>{const b=document.createElement("button");b.type="button",b.className=`btn btn-sm ${g}`;const Y=document.createElement("span");return Y.setAttribute("data-icon",f),Y.setAttribute("data-icon-size","13"),b.append(Y,document.createTextNode(` ${o}`)),b.addEventListener("click",$),A.appendChild(b),b};let k;l("Copy","copy","btn-ghost",()=>ae(e)),n.email&&l("Email them","mail","btn-ghost",()=>ie(e)),l(n.spam?"Not spam":"Mark as spam",n.spam?"inbox":"alert-triangle","btn-ghost",async()=>{await K(e,!n.spam)&&k?.close()});const L=document.createElement("span");L.className="fsx-spacer",A.appendChild(L),l("Delete","trash","btn-ghost text-danger",async()=>{await _(e)&&k?.close()}),l("Close","x","btn-ghost",()=>k?.close()),r.appendChild(A),k=re(`sub:${e.id}`,n.title,r)}function Me(e){const t=q(e);if(!t)return[];const n=O(t,T.peek());return[{header:n.title},{label:"Open\u2026",icon:"eye",action:()=>V(t)},{label:"Copy submission",icon:"copy",action:()=>ae(t)},{type:"divider"},{label:n.email?`Copy ${n.email}`:"Copy email",icon:"at-sign",disabled:!n.email,action:()=>$e(n.email)},{label:"Email them\u2026",icon:"mail",disabled:!n.email,action:()=>ie(t)},{type:"divider"},n.spam?{label:"Not spam - back to the inbox",icon:"inbox",action:()=>K(t,!1)}:{label:"Mark as spam",icon:"alert-triangle",action:()=>K(t,!0)},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>_(t)}]}const w=i.querySelector(".fsx-list");w.innerHTML=He;const Ae=M.applyBindings({loading:y,loadError:N,filter:v,query:oe,from:z,to:B,rows:P,counts:be,summary:ye,emptyText:Ee,intro:we},i,{methods:{showInbox:()=>{v.value="inbox"},showNew:()=>{v.value="new"},showSpam:()=>{v.value="spam"},clearDates:()=>{z.value="",B.value=""}}});x.add(()=>Ae.dispose()),x.add(me(i,{position:"bottom"}));const De=E.contextMenu(w,{cursor:"glyph",match:".fsx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});x.add(()=>De?.destroy?.());const le=e=>{const t=e.target.closest(".fsx-row");if(!t)return;const n=e.target.closest(".fsx-kebab");if(n){pe(n);return}V(q(t.dataset.id))},de=e=>{const t=e.target.closest(".fsx-row");if(!(!t||e.target!==t)){if(e.key==="F10"&&e.shiftKey)e.preventDefault(),pe(t);else if(e.key==="Enter")V(q(t.dataset.id));else if(e.key==="Delete"){e.preventDefault();const n=q(t.dataset.id);n&&_(n)}}};w.addEventListener("click",le),w.addEventListener("keydown",de),x.add(()=>{w.removeEventListener("click",le),w.removeEventListener("keydown",de)}),Q(a,{id:"form-submissions-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),Q(a,{id:"form-submissions-export",icon:"download",title:"Export (CSV or JSON)",onClick:Te}),Q(a,{id:"form-submissions-clear",icon:"trash",title:"Clear all submissions",onClick:ke}),x.add(()=>{[...W].forEach(e=>{try{e.close()}catch{}})}),I.scan(i),await ge(),p()&&requestAnimationFrame(()=>{w.isConnected&&I.scan(w)})}};
11
+ </div>`,ne=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),P=(i,a,u=`${a}s`)=>`${i} ${i===1?a:u}`,se=i=>i?_e(i):"";async function he(i){try{return await navigator.clipboard.writeText(i),!0}catch{}try{const a=document.createElement("textarea");a.value=i,a.style.cssText="position:fixed;opacity:0;",document.body.appendChild(a),a.select();const u=document.execCommand("copy");return a.remove(),u}catch{return!1}}function be(i,a,u=null){const m=je(a);if(!m.length||m.length!==(Array.isArray(a)?a.length:1)){i.textContent=u?ue(u,a):ee(a);return}const f=document.createElement("ul");f.className="fsx-files";for(const l of m){const c=document.createElement("li"),T=ze(l.url),h=document.createElement(T?"a":"span");if(T&&(h.href=T,h.target="_blank",h.rel="noopener",Je(h,l)),h.textContent=ee(l),c.appendChild(h),Number(l.size)>0){const b=document.createElement("small");b.textContent=` ${Number(l.size)<1024?`${l.size} B`:`${Math.round(Number(l.size)/1024)} KB`}`,c.appendChild(b)}const L=We(l);L&&c.appendChild(L),f.appendChild(c)}i.appendChild(f)}const v=qe(fe);export const formSubmissionsView={templateUrl:"/admin/js/templates/form-submissions.html",async onMount(i){v.reset();const a=i.get(0).querySelector(".fsx")||i.get(0),u=()=>fe.test(location.hash)&&a.isConnected,m=decodeURIComponent((location.hash.match(/^#\/forms\/([^/?#]+)\/submissions/)||[])[1]||"");if(!m){E.toast("No form selected.",{type:"error"});return}const f=encodeURIComponent(m),l=M.observable(null),c=M.observable([]),T=M.observable(!0),h=M.observable("");let L="inbox";try{L=Ue.includes(S.get(te))?S.get(te):"inbox"}catch{}const b=M.observable(L),oe=M.observable(""),j=M.observable(""),z=M.observable("");v.add(M.effect(()=>{const e=b.value;try{S.set(te,e)}catch{}}));const C=M.computed(()=>Fe(l.value||{})),B=M.observable([]);v.add(M.effect(()=>{const e=Date.now(),t=Pe(c.value,{filter:b.value,query:oe.value,from:j.value,to:z.value,now:e,fields:C.value}),n=C.value;B.value=t.map(r=>{const s=q(r,n,e);return{...s,when:s.at?D(s.at).fromNow():"",whenFull:se(s.at)}})}));const ye=M.computed(()=>Be(c.value)),Ee=M.computed(()=>{const e=B.value.length,t=c.value.length;return t?e===t?P(t,"submission"):`${e} of ${P(t,"submission")}`:""}),we=M.computed(()=>c.value.length?b.value==="spam"?"Nothing marked as spam.":"No submissions match.":"No submissions yet - they appear here as people send the form."),ge=M.computed(()=>l.value?`What people sent through "${l.value.title||m}".`:"What people sent through this form."),U=e=>c.peek().find(t=>String(t.id)===String(e));async function xe(){try{const[e,t]=await Oe(a.querySelector(".dm-loading-slot"),Promise.all([O(`/forms/${f}`),O(`/forms/${f}/submissions`)]),Re.rows);if(!u())return;l.value=e||null,c.value=Array.isArray(t)?t:[],h.value="",ve(e?.title||m)}catch(e){if(!u())return;h.value=`Could not load the submissions: ${e.message||e}`}finally{T.value=!1}}function ve(e){const t=i.get(0).querySelector(".dm-plugin-banner-name"),n=t?.lastChild;n&&n.nodeType===Node.TEXT_NODE&&t.querySelector(".dm-plugin-banner-sep")&&(n.textContent=`${e} submissions`),document.title=`${e} - Submissions - Domma CMS`}const K=(e,t)=>ce(e.id,()=>Ce(e,t)),_=e=>ce(e.id,()=>ke(e));async function Ce(e,t){try{const n=await O(`/forms/${f}/submissions/${encodeURIComponent(e.id)}/spam`,{method:"POST",body:JSON.stringify({spam:t})});return c.value=c.peek().map(r=>String(r.id)===String(e.id)?{...r,data:n?.entry?.data||{...r.data,spam:t}}:r),E.toast(t?"Marked as spam - it is under Spam now.":"Back in the inbox.",{type:"success"}),Z("#/forms"),!0}catch(n){return E.toast(`Not changed: ${n.message||n}`,{type:"error"}),!1}}async function ke(e){const t=q(e,C.peek()).title;if(!await E.confirm(`Delete the submission from "${ne(t)}"? This cannot be undone.`,{confirmText:"Delete"}))return!1;try{return await O(`/forms/${f}/submissions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c.value=c.peek().filter(n=>String(n.id)!==String(e.id)),E.toast("Submission deleted.",{type:"success"}),Z("#/forms"),!0}catch(n){return E.toast(`Not deleted: ${n.message||n}`,{type:"error"}),!1}}let H=!1;async function Se(){if(!H){H=!0;try{await $e()}finally{H=!1}}}async function $e(){const e=c.peek().length;if(!e){E.toast("There are no submissions to clear.",{type:"info"});return}const t=l.peek()?.title||m;if(await E.confirm(`Delete all ${P(e,"submission")} to "${ne(t)}", spam included? This cannot be undone - Export them first if you may need them.`))try{await O(`/forms/${f}/submissions`,{method:"DELETE"}),c.value=[],E.toast("All submissions cleared.",{type:"success"}),Z("#/forms")}catch(n){E.toast(`Not cleared: ${n.message||n}`,{type:"error"})}}const ae=async e=>{const t=Ke(e,C.peek(),{formTitle:l.peek()?.title||m,when:se(e.meta?.createdAt)});E.toast(await he(t)?"Copied.":"Copy failed.",{type:"info"})},Ne=async e=>{E.toast(await he(e)?`Copied ${e}.`:"Copy failed.",{type:"info"})},ie=e=>{const t=q(e,C.peek()).email;t&&He({to:[t],subject:`Re: ${l.peek()?.title||m}`})};async function Te(e,t){try{const n=await fetch(`/api/forms/${f}/submissions/${e}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);const r=await n.blob(),s=document.createElement("a");return s.href=URL.createObjectURL(r),s.download=t,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(s.href),1e3),!0}catch(n){return E.toast(`Export failed: ${n.message||n}`,{type:"error"}),!1}}const W=new Set,F=new Set;function re(e,t,n,r="md"){if(F.has(e))return null;F.add(e);let s;try{s=E.slideover({title:ne(t),size:r,position:"right"}),s.element.appendChild(n);const y=me(n);return W.add(s),Ie(s,()=>{F.delete(e),W.delete(s),y()}),I.scan(n),s.open(),s}catch(y){F.delete(e);try{s?.destroy?.(),s?.element?.remove()}catch{}return E.toast(`Could not open it: ${y.message||y}`,{type:"error"}),null}}const J=new Set;async function ce(e,t){const n=String(e);if(J.has(n))return!1;J.add(n);try{return await t()}finally{J.delete(n)}}function Me(){const e=c.peek().length,t=document.createElement("div");t.className="fsx-export";const n=document.createElement("p");n.className="fsx-note",n.textContent=e?`All ${P(e,"submission")}, spam included.`:"There are no submissions yet - the file will be empty.",t.appendChild(n);let r;const s=(y,k,G,X,A)=>{const d=document.createElement("button");d.type="button",d.className="btn btn-ghost";const $=document.createElement("span");$.setAttribute("data-icon",k),d.append($,document.createTextNode(` ${y}`));const R=document.createElement("span");R.setAttribute("data-help",A),d.addEventListener("click",async()=>{if(!d.disabled){d.disabled=!0;try{await Te(G,`${m}-submissions.${X}`)&&r?.close()}finally{d.disabled=!1}}});const o=document.createElement("div");o.append(d,R),t.appendChild(o)};s("Export as CSV","file-text","export","csv","One row per submission, one column per question - opens in Excel, Numbers or Google Sheets."),s("Export as JSON","code","export/json","json","Every submission exactly as stored, with its id and dates - for importing elsewhere or keeping a full copy."),r=re("export","Export submissions",t,"sm")}function V(e){if(!e)return;const t=C.peek(),n=q(e,t),r=document.createElement("div");r.className="fsx-detail";const s=document.createElement("div");s.className="fsx-facts";const y=o=>{const p=document.createElement("span");p.textContent=o,s.appendChild(p)};e.meta?.createdAt&&y(`Sent ${se(e.meta.createdAt)} (${D(e.meta.createdAt).fromNow()})`),e.meta?.ip&&y(`IP ${e.meta.ip}`),n.spam&&y("Marked as spam"),r.appendChild(s);const k=document.createElement("dl");k.className="fsx-answers";const G=t.filter(o=>ue(o,e.data?.[o.name])!=="");for(const o of G){const p=document.createElement("div");p.className="fsx-answer";const x=document.createElement("dt");x.textContent=o.label;const N=document.createElement("dd");be(N,e.data[o.name],o),p.append(x,N),k.appendChild(p)}const X=new Set(t.map(o=>o.name));for(const[o,p]of Object.entries(e.data||{})){if(X.has(o)||o==="spam"||ee(p)==="")continue;const x=document.createElement("div");x.className="fsx-answer";const N=document.createElement("dt");N.textContent=`${o} (no longer on the form)`;const w=document.createElement("dd");be(w,p),x.append(N,w),k.appendChild(x)}if(k.children.length)r.appendChild(k);else{const o=document.createElement("p");o.className="fsx-note",o.textContent="Nothing was filled in.",r.appendChild(o)}const A=document.createElement("div");A.className="fsx-actions";const d=(o,p,x,N)=>{const w=document.createElement("button");w.type="button",w.className=`btn btn-sm ${x}`;const Y=document.createElement("span");return Y.setAttribute("data-icon",p),Y.setAttribute("data-icon-size","13"),w.append(Y,document.createTextNode(` ${o}`)),w.addEventListener("click",N),A.appendChild(w),w};let $;d("Copy","copy","btn-ghost",()=>ae(e)),n.email&&d("Email them","mail","btn-ghost",()=>ie(e)),d(n.spam?"Not spam":"Mark as spam",n.spam?"inbox":"alert-triangle","btn-ghost",async()=>{await K(e,!n.spam)&&$?.close()});const R=document.createElement("span");R.className="fsx-spacer",A.appendChild(R),d("Delete","trash","btn-ghost text-danger",async()=>{await _(e)&&$?.close()}),d("Close","x","btn-ghost",()=>$?.close()),r.appendChild(A),$=re(`sub:${e.id}`,n.title,r)}function Ae(e){const t=U(e);if(!t)return[];const n=q(t,C.peek());return[{header:n.title},{label:"Open\u2026",icon:"eye",action:()=>V(t)},{label:"Copy submission",icon:"copy",action:()=>ae(t)},{type:"divider"},{label:n.email?`Copy ${n.email}`:"Copy email",icon:"at-sign",disabled:!n.email,action:()=>Ne(n.email)},{label:"Email them\u2026",icon:"mail",disabled:!n.email,action:()=>ie(t)},{type:"divider"},n.spam?{label:"Not spam - back to the inbox",icon:"inbox",action:()=>K(t,!1)}:{label:"Mark as spam",icon:"alert-triangle",action:()=>K(t,!0)},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>_(t)}]}const g=a.querySelector(".fsx-list");g.innerHTML=Ve;const Le=M.applyBindings({loading:T,loadError:h,filter:b,query:oe,from:j,to:z,rows:B,counts:ye,summary:Ee,emptyText:we,intro:ge},a,{methods:{showInbox:()=>{b.value="inbox"},showNew:()=>{b.value="new"},showSpam:()=>{b.value="spam"},clearDates:()=>{j.value="",z.value=""}}});v.add(()=>Le.dispose()),v.add(me(a,{position:"bottom"}));const De=E.contextMenu(g,{cursor:"glyph",match:".fsx-row",inherit:!1,density:"compact",items:e=>Ae(e.dataset.id)});v.add(()=>De?.destroy?.());const le=e=>{const t=e.target.closest(".fsx-row");if(!t)return;const n=e.target.closest(".fsx-kebab");if(n){pe(n);return}V(U(t.dataset.id))},de=e=>{const t=e.target.closest(".fsx-row");if(!(!t||e.target!==t)){if(e.key==="F10"&&e.shiftKey)e.preventDefault(),pe(t);else if(e.key==="Enter")V(U(t.dataset.id));else if(e.key==="Delete"){e.preventDefault();const n=U(t.dataset.id);n&&_(n)}}};g.addEventListener("click",le),g.addEventListener("keydown",de),v.add(()=>{g.removeEventListener("click",le),g.removeEventListener("keydown",de)}),Q(i,{id:"form-submissions-back",icon:"arrow-left",title:"All forms",onClick:()=>{location.hash="#/forms"}}),Q(i,{id:"form-submissions-export",icon:"download",title:"Export (CSV or JSON)",onClick:Me}),Q(i,{id:"form-submissions-clear",icon:"trash",title:"Clear all submissions",onClick:Se}),v.add(()=>{[...W].forEach(e=>{try{e.close()}catch{}})}),I.scan(a),await xe(),u()&&requestAnimationFrame(()=>{g.isConnected&&I.scan(g)})}};
@@ -546,10 +546,13 @@ Examples of where they appear: `projects` uses `boolean`, `notifications` uses `
546
546
  - **File uploads**. A form `file` field switches the submission to `multipart/form-data`.
547
547
  - The server checks each file against the field's `file.accept` (MIME list, wildcards such as `image/*` allowed) and `file.maxSize` (default 5 MB).
548
548
  - `multiple: true` takes several files, up to `file.maxFiles` (default 5, at most 20; the form editor's Several files / Most files). One bad file or one too many refuses the submission.
549
- - The filename is cleaned and given a uuid prefix, and the file is saved to `content/media/` - only after every other check has passed.
550
- - The entry stores `{url, name, size, mime}`, or a list of them for a `multiple` field.
551
- - Files are publicly reachable under `/media/`.
552
- Where: `parseMultipartForm()` in `server/routes/api/forms.js`; `docs/configuration.md`. Since: 0.20.0.
549
+ - The filename is cleaned and given a uuid prefix, and the file is saved - only after every other check has passed - to a **private store**, `content/form-uploads/<form slug>/<upload id>/<name>` (one uuid folder per submission; never `content/media/`, so not public and not in the Media library). The store writes its own `*` `.gitignore`, so a site repo never commits a visitor's file. Every path goes through `fileIn` (`server/services/formUploads.js`).
550
+ - The entry stores `{url, name, size, mime}`, or a list of them for a `multiple` field. `url` is `/api/forms/<slug>/uploads/<upload id>/<name>`.
551
+ - **Served only to a signed-in user** with `collections` read (the inbox's permission, checked by `requirePermission`) who can see the form (project scope), and only while a submission of that form links to the file. Credentials: Bearer, or the `dm_session` cookie for a browser following a link (a side-effect-free read, the one kind of route that cookie may serve). PNG, JPEG, GIF, WebP and PDF go inline; everything else is an `attachment` as `application/octet-stream`; always `nosniff`, `Cache-Control: private, no-store` and a CSP with `default-src 'none'` and `frame-ancestors 'none'` (plus `sandbox` for all but PDF). An anonymous browser gets a "Sign in to view this file" page.
552
+ - The admin's submission panel and collection entries open a file with the Bearer token (`admin/js/lib/private-files.js`) and show image thumbnails. The notification email links to the route and says sign-in is needed; files are never attached.
553
+ - Deleting a submission (or Clear all) deletes its files in the private store, unless another entry still links to one (`submissionUploads()` / `removeSubmissionUploads()`). Nothing under `/media/` is ever deleted this way: an old reference is the migration's to move, and a planted one may be a file a page uses.
554
+ - **Migration** (`server/services/form-uploads-migration.js`, once per site, marker `form-uploads-private` in `content/.migrations.json`): files that existing submissions (entries with `meta.source: form:<slug>` only) reference as `/media/<8 hex>-<name>` in one of the form's file fields - regular files only, never a link or folder (`lstat`) - are copied into the store and the references rewritten; the Media copy is then removed unless the name appears anywhere else in `content/` or `config/` text (a page, block, other collection), in which case it is left (copied, not moved). Never overwrites; a missing file keeps its reference; progress in `content/form-uploads/.migration.json`; logs counts.
555
+ Where: `parseMultipartForm()` / `saveFormFiles()` in `server/routes/api/forms.js`; `server/services/formUploads.js`; `docs/configuration.md`. Since: 0.20.0; private since [Unreleased].
553
556
 
554
557
  ### Entries screen
555
558
 
@@ -895,7 +898,7 @@ Where: `server/services/presetCollections.js` (`PRESETS`, `seedAll()`), `server/
895
898
  Settings: `settings.honeypot`, `settings.rateLimitPerMinute`.
896
899
  - **What happens on submit**:
897
900
  - **Store**: to the form's own collection, or to another collection chosen in `actions.collection`. Several forms can share one collection, and each submission is stamped `source: form:<slug>`.
898
- - **Email notification**: to recipients with a subject prefix, using the site's SMTP settings. **Forms > Test email** sends a test message.
901
+ - **Email notification**: to recipients with a subject prefix, using the site's SMTP settings, with each answer as its label (as the submissions view shows it), escaped. **Forms > Test email** sends a test message.
899
902
  - **Webhook**: POST (or another method) of `{form, data}`.
900
903
  - **CMS Action**: `settings.actionSlug`, which receives the signed-in submitter as `{{user.*}}`.
901
904
  - **Success message or redirect**: `successRedirect` supports `{{entryId}}`.
@@ -906,7 +909,7 @@ Where: `server/services/presetCollections.js` (`PRESETS`, `seedAll()`), `server/
906
909
  - **Submissions view**.
907
910
  - One row per submission, named after the sender.
908
911
  - Filters: Inbox, New this week, Spam, plus search across every answer and a date range.
909
- - Click a row to see everything that was sent.
912
+ - Click a row to see everything that was sent. Answers read as the visitor saw them: an option's label (dropdown, radio, checkbox group, chooser), Yes/No for a single checkbox, dd/mm/yyyy dates, HH:mm times, file names. A value the form no longer offers shows as stored. The notification email shows the same (`answerLabel()` in `public/js/form-answers.mjs`); CSV and JSON exports keep the stored values.
910
913
  - Right-click to copy it, copy or email the sender, mark it as spam or delete it.
911
914
  - Banner: Export (CSV or JSON), Clear all.
912
915
  - The Forms list badge shows submissions in the last 7 days.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.47.3",
3
+ "version": "1.47.4",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -0,0 +1 @@
1
+ import{fileRefs as c}from"./form-files.mjs";const b={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",pound:"\xA3",euro:"\u20AC",copy:"\xA9",reg:"\xAE"};export function plainLabel(e){return String(e).replace(/<[^>]*>/g,"").replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,(t,n)=>{if(n[0]==="#"){const r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);return Number.isFinite(r)&&r>31?String.fromCodePoint(r):" "}return b[n.toLowerCase()]??t})}function g(e){const t=Array.isArray(e?.options)?e.options:[],n=e?.logic?.cascade;if(!n)return t;const r=Object.values(n.mapping||{}).filter(Array.isArray).flat();return[...t,...r,...Array.isArray(n.defaultOptions)?n.defaultOptions:[]]}function a(e,t){const n=String(t);for(const r of e)if(r&&typeof r=="object"){if(r.value!==void 0&&String(r.value)===n)return plainLabel(r.label!=null&&r.label!==""?r.label:r.value)}else if(r!=null&&String(r)===n)return plainLabel(r)}export function optionLabel(e,t){const n=a(g(e),t);return n===void 0?String(t):n}const A=new Set(["select","multiselect","radio","checkbox-group","chooser"]),x=new Set(["true","on","yes","1"]),h=new Set(["false","off","no","0"]),j=e=>String(e).padStart(2,"0");function p(e){const t=String(e).trim(),n=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?)?$/.exec(t);if(!n)return t;const r=`${n[3]}/${n[2]}/${n[1]}`;return n[4]?`${r} ${n[4]}:${n[5]}`:r}function S(e){const t=String(e).trim(),n=/^(\d{1,2}):(\d{2})(?::\d{2}(?:\.\d+)?)?$/.exec(t);return n&&Number(n[1])<24?`${j(n[1])}:${n[2]}`:t}function u(e){if(e==null)return"";if(Array.isArray(e))return e.map(u).filter(Boolean).join(", ");if(typeof e=="boolean")return e?"Yes":"No";const t=c(e);return t.length?t.map(n=>n.name||n.url.split("/").pop()||"file").join(", "):typeof e=="object"?JSON.stringify(e):String(e).trim()}export function answerLabel(e,t){if(t==null||t==="")return"";const n=e&&e.type;if(!n)return u(t);if(n==="file"||c(t).length){const i=c(t);return i.length?i.map(f=>f.name||f.url.split("/").pop()||"file").join(", "):u(t)}if(n==="checkbox"&&!Array.isArray(t)){if(typeof t=="boolean")return t?"Yes":"No";const i=String(t).trim().toLowerCase();return x.has(i)?"Yes":h.has(i)?"No":String(t).trim()}const r=g(e);if(A.has(n)||r.length){const i=Array.isArray(t)?t:[t],f=o=>{if(o==null||o==="")return"";if(typeof o=="object")return u(o);const d=a(r,o);if(d!==void 0)return d;const l=String(o);if(l.includes(",")){const m=l.split(",").map(s=>s.trim()).filter(Boolean),y=m.map(s=>a(r,s));if(m.length&&y.every(s=>s!==void 0))return y.join(", ")}return l.trim()};return i.map(f).filter(Boolean).join(", ")}return n==="date"?Array.isArray(t)?t.map(p).join(", "):p(t):n==="time"?Array.isArray(t)?t.map(S).join(", "):S(t):n==="datetime"||n==="datetime-local"?p(t):u(t)}
@@ -29,7 +29,7 @@ import {deleteForm, ensureCollectionForForm, ensureFormsDir, listForms, maxSubmi
29
29
  import {executeAction} from '../../services/actions.js';
30
30
  // The same rules the browser draws the buttons by (a Cancel link must be safe).
31
31
  import {buttonSettingsProblems, formClassProblems, publicButtonSettings} from '../../../public/js/form-submit.mjs';
32
- import {cleanUploadName, countRefusal, fileRefusal, submissionTooLarge, fileRules, fileValueText, isFileValue} from '../../../public/js/form-files.mjs';
32
+ import {cleanUploadName, countRefusal, fileRefs, fileRefusal, submissionTooLarge, fileRules, fileValueText, isFileValue} from '../../../public/js/form-files.mjs';
33
33
  import {sanitiseCsv} from '../../../public/js/collection-export.mjs';
34
34
  import {originOf, trustedOrigin} from '../../services/passwordReset.js';
35
35
  import {createTransport, mailFailure, sendFormEmail, TEST_EMAIL_FAILED} from '../../services/email.js';
@@ -47,9 +47,10 @@ import {
47
47
  import {getConfig} from '../../config.js';
48
48
  import {authenticate, requireAdmin, requirePermission} from '../../middleware/auth.js';
49
49
  import {hooks} from '../../services/hooks.js';
50
- import {parseCookies, SESSION_COOKIE} from '../../services/viewerSession.js';
50
+ import {parseCookies, readSessionToken, SESSION_COOKIE} from '../../services/viewerSession.js';
51
+ import {getUserById} from '../../services/users.js';
51
52
  import {pluginDenialFor} from '../../services/collectionAccess.js';
52
- import {deleteMedia, saveMedia} from '../../services/content.js';
53
+ import {deleteUpload, disposition, openUpload, parseUploadUrl, saveUpload, servedAs, statUpload, uploadUrl, validParts} from '../../services/formUploads.js';
53
54
  import {formMayCollect, servedType} from '../../services/mediaTypes.js';
54
55
  import {v4 as uuidv4} from 'uuid';
55
56
  import {ago, clip, plural} from '../../services/sidebarBadges.js';
@@ -252,7 +253,12 @@ function fileFieldsOnly(form, body, pending) {
252
253
  * Write the files of a submission that passed every check, into the reference objects
253
254
  * parseMultipartForm() left in `body`. Only the fields that will be kept are written -
254
255
  * nothing a bot, a rate-limited or refused submission or a switched-off field sent
255
- * reaches content/media/.
256
+ * is stored.
257
+ *
258
+ * They go to the private store (services/formUploads.js), one folder per submission:
259
+ * content/form-uploads/<form slug>/<upload id>/<8 hex>-<name> - never content/media/,
260
+ * so no visitor's file is public or in the Media library. Each reference's url is the
261
+ * admin-only route that serves it.
256
262
  *
257
263
  * If one cannot be written, the ones already written for this submission are removed
258
264
  * and the error is thrown - a submission keeps all its files or none.
@@ -260,10 +266,12 @@ function fileFieldsOnly(form, body, pending) {
260
266
  * @param {Map<string, {buffer: Buffer, filename: string}[]>} pending
261
267
  * @param {object} body
262
268
  * @param {Set<string>} keep - field names the submission keeps
263
- * @returns {Promise<string[]>} the media file names written (for removeFormFiles)
269
+ * @param {string} slug - the form's
270
+ * @returns {Promise<{slug: string, id: string, name: string}[]>} what was written (for removeFormFiles)
264
271
  */
265
- async function saveFormFiles(pending, body, keep) {
272
+ async function saveFormFiles(pending, body, keep, slug) {
266
273
  const written = [];
274
+ const uploadId = uuidv4();
267
275
  try {
268
276
  for (const [name, files] of pending) {
269
277
  if (!keep.has(name)) {
@@ -272,8 +280,8 @@ async function saveFormFiles(pending, body, keep) {
272
280
  }
273
281
  const refs = Array.isArray(body[name]) ? body[name] : [body[name]];
274
282
  for (let i = 0; i < files.length; i++) {
275
- const saved = await saveNewMedia(files[i]);
276
- written.push(saved.name);
283
+ const saved = await saveNewUpload(slug, uploadId, files[i]);
284
+ written.push(saved);
277
285
  refs[i].url = saved.url;
278
286
  }
279
287
  }
@@ -288,10 +296,10 @@ async function saveFormFiles(pending, body, keep) {
288
296
  * Write one visitor file under a new name. Never over another file: a clash of the random
289
297
  * prefix picks another, and a write that fails part way removes what it wrote.
290
298
  */
291
- async function saveNewMedia(file) {
299
+ async function saveNewUpload(slug, uploadId, file) {
292
300
  for (let tries = 0; ; tries++) {
293
301
  try {
294
- return await saveMedia(safeFilename(file.filename), file.buffer, {exclusive: true});
302
+ return await saveUpload(slug, uploadId, safeFilename(file.filename), file.buffer);
295
303
  } catch (err) {
296
304
  if (err.code !== 'EEXIST' || tries >= 4) throw err;
297
305
  }
@@ -299,9 +307,71 @@ async function saveNewMedia(file) {
299
307
  }
300
308
 
301
309
  /** Remove a submission's written files again (it was not stored after all). Never throws. */
302
- async function removeFormFiles(names) {
303
- for (const name of names || []) {
304
- try { await deleteMedia(name); } catch { /* already gone */ }
310
+ async function removeFormFiles(written) {
311
+ for (const f of written || []) {
312
+ try { await deleteUpload(f.slug, f.id, f.name); } catch { /* already gone */ }
313
+ }
314
+ }
315
+
316
+ /**
317
+ * The files a form saved for one submission: the references in its file fields
318
+ * to the private store (services/formUploads.js) under THIS form's slug.
319
+ * Nothing else is ever the form's to delete - not another address, a path,
320
+ * another form's folder, a field the form does not define as a file field,
321
+ * and never anything under /media/. A /media/ reference may be an old upload
322
+ * (form-uploads-migration.js moves the real ones into the store at boot) or a
323
+ * reference planted through a public create, a token or an editor pointing at
324
+ * a file a page uses, so it is left alone. Each name is checked again at the
325
+ * file (fileIn, in deleteUpload), so a tampered reference never reaches outside
326
+ * the store.
327
+ *
328
+ * @param {object} form
329
+ * @param {object} entry
330
+ * @returns {{url: string, slug: string, id: string, name: string}[]}
331
+ */
332
+ export function submissionUploads(form, entry) {
333
+ const out = new Map();
334
+ for (const f of form?.fields || []) {
335
+ if (!f || f.type !== 'file' || !f.name) continue;
336
+ for (const ref of fileRefs(entry?.data?.[f.name])) {
337
+ const up = parseUploadUrl(ref.url);
338
+ if (!up || up.slug !== form.slug) continue;
339
+ out.set(ref.url, {url: ref.url, ...up});
340
+ }
341
+ }
342
+ return [...out.values()];
343
+ }
344
+
345
+ /**
346
+ * After submissions are deleted, delete the files the form saved for them - but
347
+ * not a file another entry left in the collection still links to (an imported
348
+ * or copied entry). If the rest of the collection cannot be read, the files stay:
349
+ * an orphaned upload is better than a broken link. Never throws.
350
+ *
351
+ * @param {object} form
352
+ * @param {object[]} removed - the entries that were deleted
353
+ * @param {{warn: Function}} [log]
354
+ */
355
+ async function removeSubmissionUploads(form, removed, log = console) {
356
+ const files = new Map((removed || []).flatMap(e => submissionUploads(form, e)).map(u => [u.url, u]));
357
+ if (!files.size) return;
358
+ try {
359
+ const left = await listEntries(submissionsCollectionFor(form), {limit: 0});
360
+ for (const e of left.entries || []) {
361
+ for (const v of Object.values(e?.data || {})) {
362
+ for (const ref of fileRefs(v)) files.delete(ref.url);
363
+ }
364
+ }
365
+ } catch (err) {
366
+ log.warn(`[forms] Kept the files of deleted "${form?.slug}" submissions: the collection could not be read (${err.message})`);
367
+ return;
368
+ }
369
+ for (const up of files.values()) {
370
+ try {
371
+ await deleteUpload(up.slug, up.id, up.name);
372
+ } catch (err) {
373
+ log.warn(`[forms] Could not delete the upload "${up.name}" of a "${form?.slug}" submission: ${err.message}`);
374
+ }
305
375
  }
306
376
  }
307
377
 
@@ -819,17 +889,23 @@ export async function formsRoutes(fastify) {
819
889
  if (!(await canSeeForm(request.user, form))) return reply.status(404).send({ error: 'Form not found.' });
820
890
  if (await refusedPluginTarget(request, reply, form)) return;
821
891
  const target = submissionsCollectionFor(form);
892
+ const removed = [];
822
893
  try {
823
894
  // Its own collection: clear it. A shared one: delete only this form's
824
895
  // entries (one at a time - parallel writes to a file collection lose updates).
896
+ const mine = await submissionsOf(form);
825
897
  if (target === form.slug) {
826
898
  await clearEntries(target);
899
+ removed.push(...mine);
827
900
  } else {
828
- for (const e of await submissionsOf(form)) await deleteEntry(target, e.id);
901
+ for (const e of mine) { await deleteEntry(target, e.id); removed.push(e); }
829
902
  }
830
903
  } catch {
904
+ await removeSubmissionUploads(form, removed, fastify.log);
831
905
  return reply.status(404).send({ error: 'Collection not found for this form.' });
832
906
  }
907
+ // Their uploads go with them (only the files the form saved for them).
908
+ await removeSubmissionUploads(form, removed, fastify.log);
833
909
  forgetStats(slug);
834
910
  return { ok: true };
835
911
  });
@@ -850,16 +926,85 @@ export async function formsRoutes(fastify) {
850
926
  if (!(await canSeeForm(request.user, form))) return reply.status(404).send({ error: 'Form not found.' });
851
927
  if (await refusedPluginTarget(request, reply, form)) return;
852
928
  const target = submissionsCollectionFor(form);
929
+ let entry;
853
930
  try {
854
- if (!isSubmissionOf(form, await getEntry(target, id))) return reply.status(404).send({ error: 'Submission not found.' });
931
+ entry = await getEntry(target, id);
932
+ if (!isSubmissionOf(form, entry)) return reply.status(404).send({ error: 'Submission not found.' });
855
933
  await deleteEntry(target, id);
856
934
  } catch {
857
935
  return reply.status(404).send({ error: 'Submission not found.' });
858
936
  }
937
+ // Its uploads go with it (only the files the form saved for it).
938
+ await removeSubmissionUploads(form, [entry], fastify.log);
859
939
  forgetStats(slug);
860
940
  return { ok: true };
861
941
  });
862
942
 
943
+ // -----------------------------------------------------------------------
944
+ // GET /forms/:slug/uploads/:id/:name - one visitor upload, to a signed-in
945
+ // user who may read the form's submissions (the inbox's own permission),
946
+ // and only while a submission of this form links to it.
947
+ //
948
+ // Signed in means the Bearer token the admin sends, or - for a link opened
949
+ // from the notification email or the entry screen, which a browser follows
950
+ // with no header - the dm_session cookie login sets (services/viewerSession.js).
951
+ // This is a read with no side effects, the one kind of route that cookie
952
+ // may serve. Sent inline only as PNG, JPEG, GIF, WebP or PDF; anything else
953
+ // is an attachment of type application/octet-stream. Always nosniff,
954
+ // private/no-store, and a CSP under which nothing in the file can run.
955
+ // -----------------------------------------------------------------------
956
+ const signedInForFile = async (request, reply) => {
957
+ if (request.headers.authorization) return authenticate(request, reply);
958
+ let decoded = null;
959
+ const raw = readSessionToken(request);
960
+ if (raw) { try { decoded = fastify.jwt.verify(raw); } catch { decoded = null; } }
961
+ if (!decoded || decoded.type !== 'access') {
962
+ const html = /text\/html/i.test(String(request.headers.accept || ''));
963
+ reply.code(401).header('Cache-Control', 'private, no-store').header('X-Content-Type-Options', 'nosniff');
964
+ if (!html) return reply.send({statusCode: 401, error: 'Unauthorised', message: 'Sign in to view this file.'});
965
+ return reply.type('text/html; charset=utf-8').header('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'")
966
+ .send('<!doctype html><meta charset="utf-8"><title>Sign in to view this file</title>'
967
+ + '<body style="font-family:sans-serif;max-width:32rem;margin:3rem auto;padding:0 1rem">'
968
+ + '<h1 style="font-size:1.3rem">Sign in to view this file</h1>'
969
+ + '<p>Files sent with a form are private. <a href="/admin/">Sign in to the admin</a>, then open this link again.</p>');
970
+ }
971
+ request.user = decoded;
972
+ const user = decoded.id ? await getUserById(decoded.id) : null;
973
+ request.user.projects = Array.isArray(user?.projects) ? user.projects : [];
974
+ };
975
+
976
+ fastify.get('/forms/:slug/uploads/:id/:name', {preHandler: [signedInForFile, requirePermission('collections', 'read')]}, async (request, reply) => {
977
+ const {slug, id, name} = request.params;
978
+ reply.header('X-Content-Type-Options', 'nosniff').header('Cache-Control', 'private, no-store');
979
+ const notFound = () => reply.status(404).send({error: 'File not found.'});
980
+ if (!validParts(slug, id, name)) return notFound();
981
+ let form;
982
+ try { form = await readForm(slug); } catch { return notFound(); }
983
+ if (!(await canSeeForm(request.user, form))) return notFound();
984
+ if (await refusedPluginTarget(request, reply, form)) return;
985
+ const url = uploadUrl(slug, id, name);
986
+ let ref = null;
987
+ try {
988
+ for (const e of await submissionsOf(form)) {
989
+ if (!submissionUploads(form, e).some(u => u.url === url)) continue;
990
+ for (const v of Object.values(e.data || {})) ref = ref || fileRefs(v).find(r => r.url === url) || null;
991
+ break;
992
+ }
993
+ } catch { return notFound(); }
994
+ if (!ref) return notFound();
995
+ const st = await statUpload(slug, id, name);
996
+ if (!st) return notFound();
997
+ const {type, inline} = servedAs(name);
998
+ reply.header('Content-Type', type)
999
+ .header('Content-Length', st.size)
1000
+ .header('Content-Disposition', disposition(inline, ref.name || name))
1001
+ .header('Content-Security-Policy', inline && type === 'application/pdf'
1002
+ ? "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data: blob:; object-src 'self'; frame-ancestors 'none'"
1003
+ : "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; frame-ancestors 'none'; sandbox")
1004
+ .header('Cross-Origin-Resource-Policy', 'same-origin');
1005
+ return reply.send(openUpload(st.file));
1006
+ });
1007
+
863
1008
  // -----------------------------------------------------------------------
864
1009
  // POST /forms/:slug/submissions/:id/spam - flag or unflag one submission.
865
1010
  // Merged server-side (updateEntry replaces `data` wholesale), in the field
@@ -1034,7 +1179,7 @@ export async function formsRoutes(fastify) {
1034
1179
  let writtenFiles = [];
1035
1180
  if (pendingFiles?.size) {
1036
1181
  try {
1037
- writtenFiles = await saveFormFiles(pendingFiles, body, record ? visibleFieldNames : new Set());
1182
+ writtenFiles = await saveFormFiles(pendingFiles, body, record ? visibleFieldNames : new Set(), slug);
1038
1183
  } catch (err) {
1039
1184
  fastify.log.warn(`[forms] Saving the files of a "${slug}" submission failed: ${err.message}`);
1040
1185
  return reply.status(500).send({error: 'Your files could not be saved, so the submission was not sent. Please try again.'});
package/server/server.js CHANGED
@@ -366,6 +366,18 @@ try {
366
366
  app.log.warn(`[collections] Number-field repair skipped: ${err.message}`);
367
367
  }
368
368
 
369
+ // Visitors' form uploads out of content/media/ into the private store - one-shot, resumable.
370
+ try {
371
+ const {migrateFormUploads} = await import('./services/form-uploads-migration.js');
372
+ const r = await migrateFormUploads();
373
+ if (r.ran && (r.entries || r.missing || r.skipped)) {
374
+ app.log.info(`[forms] Form uploads made private: ${r.entries} submission(s) updated, ${r.moved} file(s) moved, ${r.copied} copied (also used elsewhere, so left in Media), ${r.missing} missing, ${r.skipped} skipped`);
375
+ }
376
+ if (r.pending.length) app.log.warn(`[forms] Form-uploads migration will retry next start for: ${r.pending.slice(0, 20).join(', ')}`);
377
+ } catch (err) {
378
+ app.log.warn(`[forms] Form-uploads migration skipped: ${err.message}`);
379
+ }
380
+
369
381
  /*
370
382
  * An admin change clears the response cache.
371
383
  *
@@ -492,7 +504,9 @@ app.addHook('onSend', async (request, reply) => {
492
504
  const url = request.raw.url || '';
493
505
  if (!url.startsWith('/api/')) return;
494
506
  if (url.startsWith('/api/v1/') || url.startsWith('/api/x/') || url.startsWith('/api/content/v1/')) return;
495
- reply.header('Cache-Control', 'no-store, must-revalidate');
507
+ // A route that already said private + no-store (a visitor's form upload) keeps it.
508
+ const own = String(reply.getHeader('cache-control') || '');
509
+ reply.header('Cache-Control', /\bprivate\b/.test(own) && /\bno-store\b/.test(own) ? own : 'no-store, must-revalidate');
496
510
  reply.header('Pragma', 'no-cache');
497
511
  reply.header('Expires', '0');
498
512
  if (RUNNING_CMS_VERSION && request.headers.authorization) reply.header('X-Domma-CMS-Version', RUNNING_CMS_VERSION);
@@ -6,6 +6,13 @@ import nodemailer from 'nodemailer';
6
6
  import {signedOnly} from './codePolicy.js';
7
7
  import {normaliseMailHost, resolveMailHost} from './mailHost.js';
8
8
  import {fileRefs, fileUrl, fileValueText} from '../../public/js/form-files.mjs';
9
+ import {answerLabel} from '../../public/js/form-answers.mjs';
10
+
11
+ /** Form field types that lay a form out rather than ask anything - no row in the email. */
12
+ const LAYOUT_FIELD_TYPES = new Set(['page-break', 'heading', 'paragraph', 'html', 'divider', 'spacer', 'banner']);
13
+
14
+ /** Text for a plain-text email part: line breaks kept, every other control character a space. */
15
+ const plainText = (s) => String(s ?? '').replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, ' ');
9
16
 
10
17
  /**
11
18
  * What a person is told when mail could not be sent. The mail server's own
@@ -283,25 +290,31 @@ export async function sendEmail(transport, {from, fromName, to, subject, html, t
283
290
  * Send an HTML + plain-text form submission notification email.
284
291
  * Builds a generic table of field→value pairs from the submitted data.
285
292
  *
286
- * @param {import('nodemailer').Transporter} transport
287
- * A file field's value (one reference, or a list from a `multiple` field) is shown
288
- * as a link per file, made absolute with `baseUrl` (site.json) when the site has one.
293
+ * Each answer reads as the admin's submission screen shows it (answerLabel,
294
+ * public/js/form-answers.mjs): an option's label rather than its stored value,
295
+ * Yes/No for a single checkbox, dd/mm/yyyy dates. A file field's value (one
296
+ * reference, or a list from a `multiple` field) is shown as a link per file,
297
+ * made absolute with `baseUrl` (site.json) when the site has one; the link needs
298
+ * sign-in, which the email says. Files are never attached. Everything a
299
+ * visitor or an author wrote is escaped in the HTML part, and the plain-text
300
+ * part carries no control characters but line breaks.
289
301
  *
290
302
  * @param {import('nodemailer').Transporter} transport
291
- * @param {{ from: string, fromName: string, to: string, subject: string, formTitle: string, fields: Array<{name: string, label: string, type?: string}>, data: Record<string, unknown>, baseUrl?: string }} opts
303
+ * @param {{ from: string, fromName: string, to: string, subject: string, formTitle: string, fields: Array<{name: string, label: string, type?: string, options?: object[]}>, data: Record<string, unknown>, baseUrl?: string }} opts
292
304
  * @returns {Promise<void>}
293
305
  * @throws {Error} If sending the email fails.
294
306
  */
295
307
  export async function sendFormEmail(transport, { from, fromName, to, subject, formTitle, fields, data, baseUrl = '' }) {
308
+ const asked = (fields || []).filter(f => f && f.name && !LAYOUT_FIELD_TYPES.has(f.type));
296
309
  const isFile = (field) => field.type === 'file' && fileRefs(data[field.name]).length > 0;
297
310
  const fileLinks = (val) => fileRefs(val).map((f) => {
298
311
  const url = fileUrl(f, baseUrl);
299
312
  const name = escapeHtml(f.name || url);
300
313
  return /^(https?:\/\/|\/)/i.test(url) ? `<a href="${escapeHtml(url)}">${name}</a>` : name;
301
314
  }).join('<br>');
302
- const rows = fields.map(field => {
315
+ const rows = asked.map(field => {
303
316
  const val = data[field.name] ?? '';
304
- const safe = isFile(field) ? fileLinks(val) : escapeHtml(String(val)).replace(/\n/g, '<br>');
317
+ const safe = isFile(field) ? fileLinks(val) : escapeHtml(plainText(answerLabel(field, val))).replace(/\n/g, '<br>');
305
318
  const safeLabel = escapeHtml(field.label || field.name);
306
319
  return `
307
320
  <tr>
@@ -310,24 +323,30 @@ export async function sendFormEmail(transport, { from, fromName, to, subject, fo
310
323
  </tr>`.trim();
311
324
  }).join('\n');
312
325
 
313
- const plainRows = fields.map(field => {
326
+ const plainRows = asked.map(field => {
314
327
  const val = data[field.name] ?? '';
315
- return `${field.label || field.name}: ${isFile(field) ? fileValueText(val, {base: baseUrl}) : val}`;
328
+ const shown = isFile(field) ? fileValueText(val, {base: baseUrl}) : answerLabel(field, val);
329
+ return `${plainText(field.label || field.name)}: ${plainText(shown)}`;
316
330
  }).join('\n');
317
331
 
332
+ // Visitors' files are private (services/formUploads.js): their links open for a signed-in admin only.
333
+ const hasFiles = asked.some(isFile);
334
+ const FILES_NOTE = 'Files sent with the form are private: sign in to the admin to view them.';
335
+
318
336
  const html = `
319
337
  <!DOCTYPE html>
320
338
  <html>
321
339
  <body style="font-family:sans-serif;max-width:640px;margin:0 auto;padding:20px;">
322
340
  <h2 style="color:#333;margin-bottom:4px;">New Form Submission</h2>
323
- <p style="color:#888;margin-top:0;font-size:.9rem;">${escapeHtml(formTitle)}</p>
341
+ <p style="color:#888;margin-top:0;font-size:.9rem;">${escapeHtml(formTitle ?? '')}</p>
324
342
  <table style="width:100%;border-collapse:collapse;margin-top:16px;">
325
343
  ${rows}
326
- </table>
344
+ </table>${hasFiles ? `
345
+ <p style="color:#888;font-size:.85rem;margin-top:12px;">${escapeHtml(FILES_NOTE)}</p>` : ''}
327
346
  </body>
328
347
  </html>`.trim();
329
348
 
330
- const text = `New form submission: ${formTitle}\n\n${plainRows}`;
349
+ const text = `New form submission: ${plainText(formTitle ?? '')}\n\n${plainRows}${hasFiles ? `\n\n${FILES_NOTE}` : ''}`;
331
350
 
332
351
  try {
333
352
  const info = await transport.sendMail({
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Form-uploads migration - one-off move of visitors' form uploads out of
3
+ * content/media/ into the private store (services/formUploads.js).
4
+ *
5
+ * Before uploads were private, saveFormFiles() wrote each file to
6
+ * content/media/<8 hex>-<name>, served to anyone at /media/ and listed in the
7
+ * Media library. This finds every file a form SUBMISSION (an entry stamped
8
+ * `meta.source: 'form:<slug>'`) references that way - in one of the form's file
9
+ * fields, with exactly that shape, resolved through fileIn inside the media root,
10
+ * and a regular file (never a link or a folder) - and nothing else in Media:
11
+ *
12
+ * 1. copies it to content/form-uploads/<form slug>/<entry id>/<name>
13
+ * (never over a file already there: one there is a previous run's copy);
14
+ * 2. rewrites the reference to the admin-only route (uploadUrl);
15
+ * 3. removes the media copy - unless the file's name appears anywhere else in
16
+ * the site's content (a page, block, menu, view, config, another
17
+ * collection's data, an entry that is not a submission), where removing it
18
+ * would break a link. Then the media copy is left: COPIED, not moved.
19
+ *
20
+ * The "used elsewhere" test is a text search for the stored name (it carries a
21
+ * random 8-hex prefix, so a match is not a coincidence) over content/ and
22
+ * config/ text files, minus the submissions themselves. Collections kept in
23
+ * MongoDB are searched only for the forms' own collections.
24
+ *
25
+ * Idempotent and resumable: a reference already private is skipped; a missing
26
+ * file is skipped (and counted) with its reference left as it was; the media
27
+ * copies still to remove are recorded in content/form-uploads/.migration.json
28
+ * as each entry is rewritten, and are removed only once no submission still
29
+ * links to them. The marker (content/.migrations.json) is written when a run
30
+ * finishes with nothing left to retry.
31
+ */
32
+ import fs from 'fs/promises';
33
+ import {existsSync} from 'fs';
34
+ import path from 'path';
35
+ import {config} from '../config.js';
36
+ import {fileRefs} from '../../public/js/form-files.mjs';
37
+ import {fileIn} from './safePath.js';
38
+ import {formUploadsRoot, keepUploadsOutOfGit, parseUploadUrl, uploadPath, uploadUrl, validParts} from './formUploads.js';
39
+
40
+ export const MIGRATION_ID = 'form-uploads-private';
41
+
42
+ /** What saveFormFiles() stored before uploads were private. */
43
+ const LEGACY_URL = /^\/media\/([0-9a-f]{8}-[\w.-]{1,200})$/;
44
+ const TEXT_FILE = /\.(md|markdown|json|html?|txt|css|js|mjs|ya?ml|xml|csv)$/i;
45
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
46
+
47
+ const contentRoot = () => path.dirname(path.resolve(config.content.collectionsDir));
48
+ const defaultMarkerPath = () => path.join(contentRoot(), '.migrations.json');
49
+
50
+ async function readJson(file, fallback) {
51
+ try { return JSON.parse(await fs.readFile(file, 'utf8')) ?? fallback; } catch { return fallback; }
52
+ }
53
+
54
+ /** The collection a form's submissions are in, and whether an entry is one of them (as routes/api/forms.js). */
55
+ const collectionOf = (form) => (form?.actions?.collection?.enabled && form.actions.collection.slug) ? form.actions.collection.slug : form?.slug;
56
+ /**
57
+ * A real submission of the form: stamped `meta.source: 'form:<slug>'` by the submit
58
+ * route. Only these are migrated - an entry made any other way (the admin, a token,
59
+ * a public create, an import) may carry a planted /media/ reference, and must not
60
+ * pull a Media file out of public view.
61
+ */
62
+ const isSubmissionOf = (form, entry) => entry?.meta?.source === `form:${form.slug}`;
63
+
64
+ /** The legacy media name a reference points at, or null. */
65
+ export function legacyName(ref) {
66
+ const m = LEGACY_URL.exec(String(ref?.url || ''));
67
+ return m && m[1] !== '.' && m[1] !== '..' ? m[1] : null;
68
+ }
69
+
70
+ /** Every text file under dir, skipping the folders in `skip` (absolute paths). */
71
+ async function* textFiles(dir, skip) {
72
+ let list;
73
+ try { list = await fs.readdir(dir, {withFileTypes: true}); } catch { return; }
74
+ for (const d of list) {
75
+ const p = path.join(dir, d.name);
76
+ if (skip.has(p)) continue;
77
+ if (d.isDirectory()) yield* textFiles(p, skip);
78
+ else if (d.isFile() && TEXT_FILE.test(d.name)) yield p;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Run the migration.
84
+ *
85
+ * @param {{markerPath?: string, mediaDir?: string, uploadsRoot?: string, searchRoots?: string[], force?: boolean, log?: {info: Function, warn: Function}}} [opts]
86
+ * @returns {Promise<{ran: boolean, entries: number, moved: number, copied: number, missing: number, skipped: number, pending: string[]}>}
87
+ */
88
+ export async function migrateFormUploads({
89
+ markerPath = defaultMarkerPath(),
90
+ mediaDir = path.resolve(config.content.mediaDir),
91
+ uploadsRoot = formUploadsRoot(),
92
+ searchRoots = [contentRoot(), path.resolve(contentRoot(), '..', 'config')],
93
+ force = false
94
+ } = {}) {
95
+ const result = {ran: false, entries: 0, moved: 0, copied: 0, missing: 0, skipped: 0, pending: []};
96
+ const marker = await readJson(markerPath, {});
97
+ if (marker[MIGRATION_ID] && !force) return result;
98
+ result.ran = true;
99
+
100
+ const {listForms} = await import('./forms.js');
101
+ const {getAdapter} = await import('./adapterRegistry.js');
102
+ const cache = await import('./cache/index.js');
103
+
104
+ const progressFile = path.join(uploadsRoot, '.migration.json');
105
+ const progress = await readJson(progressFile, {remove: []});
106
+ const toRemove = new Set(Array.isArray(progress.remove) ? progress.remove : []);
107
+ const saveProgress = async () => {
108
+ keepUploadsOutOfGit(uploadsRoot);
109
+ await fs.writeFile(progressFile, JSON.stringify({remove: [...toRemove]}, null, 2) + '\n');
110
+ };
111
+
112
+ // 1. The forms, their submissions, and the legacy files those reference.
113
+ const forms = (await listForms()).filter(f => f && f.slug);
114
+ const work = []; // {form, collection, adapter, entries}
115
+ const submissionFiles = new Set(); // data.json files of the forms' collections - searched entry by entry instead
116
+ let haystack = ''; // text of everything that is not a submission
117
+ for (const form of forms) {
118
+ const slug = collectionOf(form);
119
+ if (!form.fields?.some(f => f?.type === 'file')) continue;
120
+ try {
121
+ const adapter = await getAdapter(slug);
122
+ const entries = await adapter.all(slug);
123
+ work.push({form, slug, adapter, entries});
124
+ submissionFiles.add(path.join(path.resolve(config.content.collectionsDir), slug));
125
+ } catch {
126
+ result.pending.push(form.slug);
127
+ }
128
+ }
129
+ // A collection's entries that are no form's submission (several forms may share one) are "elsewhere".
130
+ for (const slug of new Set(work.map(w => w.slug))) {
131
+ const sharing = forms.filter(f => collectionOf(f) === slug);
132
+ const {entries} = work.find(w => w.slug === slug);
133
+ for (const e of entries) if (!sharing.some(f => isSubmissionOf(f, e))) haystack += JSON.stringify(e.data ?? {}) + '\n';
134
+ }
135
+ const work2 = work.filter(w => w.entries.some(e => isSubmissionOf(w.form, e)
136
+ && w.form.fields.some(f => f?.type === 'file' && fileRefs(e.data?.[f.name]).some(legacyName))));
137
+
138
+ if (work2.length || toRemove.size) {
139
+ // 2. Where else a name appears: content/ and config/ text, minus media, the store,
140
+ // and the forms' own collection folders (their other entries were added above).
141
+ const skip = new Set([mediaDir, uploadsRoot, ...submissionFiles]);
142
+ for (const root of searchRoots) {
143
+ for await (const file of textFiles(root, skip)) {
144
+ try {
145
+ const st = await fs.stat(file);
146
+ if (st.size <= MAX_TEXT_BYTES) haystack += await fs.readFile(file, 'utf8') + '\n';
147
+ } catch { /* unreadable: not a use */ }
148
+ }
149
+ }
150
+ }
151
+ const usedElsewhere = (name) => haystack.includes(name);
152
+
153
+ // 3. Copy, rewrite, record.
154
+ for (const {form, slug, adapter, entries} of work2) {
155
+ let changed = 0;
156
+ for (const entry of entries) {
157
+ if (!isSubmissionOf(form, entry) || !entry?.data) continue;
158
+ let touched = false;
159
+ const data = {...entry.data};
160
+ const moved = [];
161
+ try { for (const f of form.fields) {
162
+ if (f?.type !== 'file' || !f.name || data[f.name] == null) continue;
163
+ const one = !Array.isArray(data[f.name]);
164
+ const list = (one ? [data[f.name]] : data[f.name]).map(ref => {
165
+ const name = legacyName(ref);
166
+ if (!name) return ref;
167
+ if (!validParts(form.slug, String(entry.id ?? ''), name)) { result.skipped++; return ref; }
168
+ let src;
169
+ try { src = fileIn(mediaDir, name); } catch { result.skipped++; return ref; }
170
+ return {ref, name, src};
171
+ });
172
+ const next = [];
173
+ for (const item of list) {
174
+ if (!item || !item.src) { next.push(item); continue; }
175
+ const {ref, name, src} = item;
176
+ const dest = uploadPath(form.slug, String(entry.id), name, uploadsRoot);
177
+ // Only a regular file: lstat does not follow a link, and copyFile would.
178
+ const kind = await fs.lstat(src).then(st => (st.isFile() ? 'file' : 'other'), () => 'none');
179
+ if (kind === 'other') { result.skipped++; next.push(ref); continue; }
180
+ if (kind === 'none' && !existsSync(dest)) { result.missing++; next.push(ref); continue; }
181
+ if (!existsSync(dest)) {
182
+ await fs.mkdir(path.dirname(dest), {recursive: true});
183
+ keepUploadsOutOfGit(uploadsRoot);
184
+ await fs.copyFile(src, dest, fs.constants.COPYFILE_EXCL).catch((err) => { if (err.code !== 'EEXIST') throw err; });
185
+ }
186
+ next.push({...ref, url: uploadUrl(form.slug, String(entry.id), name)});
187
+ moved.push(name);
188
+ touched = true;
189
+ }
190
+ data[f.name] = one ? next[0] : next;
191
+ } } catch {
192
+ // A copy that failed (a full disk): this entry is left as it was, for the next start.
193
+ result.pending.push(`${form.slug}/${entry.id}`);
194
+ continue;
195
+ }
196
+ if (!touched) continue;
197
+ // Recorded before the rewrite: a run cut short after it still removes the media copy next time.
198
+ const removing = moved.filter(name => !usedElsewhere(name));
199
+ for (const name of removing) toRemove.add(name);
200
+ try {
201
+ await saveProgress();
202
+ await adapter.update(slug, entry.id, {...entry, data});
203
+ } catch {
204
+ result.pending.push(`${form.slug}/${entry.id}`);
205
+ continue;
206
+ }
207
+ result.copied += moved.length - removing.length;
208
+ result.moved += removing.length;
209
+ entry.data = data;
210
+ changed++;
211
+ }
212
+ result.entries += changed;
213
+ if (changed) await cache.invalidateTags([`collection:${slug}`]).catch(() => {});
214
+ }
215
+
216
+ // 4. Remove the media copies no submission links to any more (and nothing else uses).
217
+ // Only a name a submission now links to in the store, with the copy there - so
218
+ // whatever the progress file says, nothing else in Media is ever removed.
219
+ const stillLinked = new Set();
220
+ const migrated = new Set();
221
+ for (const {form, entries} of work) {
222
+ for (const e of entries) {
223
+ if (!isSubmissionOf(form, e)) continue;
224
+ for (const f of form.fields) {
225
+ if (f?.type !== 'file' || !f.name) continue;
226
+ for (const ref of fileRefs(e.data?.[f.name])) {
227
+ const n = legacyName(ref);
228
+ if (n) { stillLinked.add(n); continue; }
229
+ const priv = parseUploadUrl(ref.url);
230
+ if (priv && priv.slug === form.slug && existsSync(uploadPath(priv.slug, priv.id, priv.name, uploadsRoot))) migrated.add(priv.name);
231
+ }
232
+ }
233
+ }
234
+ }
235
+ for (const name of [...toRemove]) {
236
+ if (!migrated.has(name) || stillLinked.has(name) || usedElsewhere(name)) { toRemove.delete(name); continue; }
237
+ try {
238
+ const file = fileIn(mediaDir, name);
239
+ if (!(await fs.lstat(file)).isFile()) { toRemove.delete(name); continue; }
240
+ await fs.unlink(file);
241
+ } catch (err) {
242
+ if (err.code !== 'ENOENT') { result.pending.push(name); continue; }
243
+ }
244
+ toRemove.delete(name);
245
+ }
246
+ if (toRemove.size) await saveProgress();
247
+ else await fs.rm(progressFile, {force: true});
248
+
249
+ if (!result.pending.length) {
250
+ const latest = await readJson(markerPath, {});
251
+ await fs.writeFile(markerPath, JSON.stringify({...latest, [MIGRATION_ID]: new Date().toISOString()}, null, 2) + '\n');
252
+ }
253
+ return result;
254
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Form uploads - the private store for files visitors send with a form.
3
+ *
4
+ * A visitor's file (a CV, a right-to-work document, a photo of a fault) is not
5
+ * site content: it is kept out of content/media/ - so it is neither served at
6
+ * /media/ to anyone with the address nor listed in the admin's Media library -
7
+ * and out of the site repo. Layout:
8
+ *
9
+ * content/form-uploads/<form slug>/<upload id>/<8 hex>-<cleaned name>
10
+ *
11
+ * The upload id is one uuid per submission (the entry id is not known until
12
+ * the entry is written, after its files), or the entry id for a file moved here
13
+ * by form-uploads-migration.js. Every path is built with fileIn
14
+ * (services/safePath.js), one plain segment at a time, so no stored reference
15
+ * can name a file outside this folder.
16
+ *
17
+ * A submission stores each file as {url, name, size, mime}, where url is the
18
+ * admin-only route that serves it (routes/api/forms.js):
19
+ *
20
+ * /api/forms/<form slug>/uploads/<upload id>/<stored name>
21
+ *
22
+ * @module services/formUploads
23
+ */
24
+ import fs from 'fs/promises';
25
+ import {createReadStream, existsSync, mkdirSync, writeFileSync} from 'fs';
26
+ import path from 'path';
27
+ import {config} from '../config.js';
28
+ import {fileIn} from './safePath.js';
29
+
30
+ /** content/form-uploads - beside content/media, never inside it. */
31
+ export function formUploadsRoot() {
32
+ return path.join(path.dirname(path.resolve(config.content.mediaDir)), 'form-uploads');
33
+ }
34
+
35
+ /** An upload id: a uuid for a new submission, an entry id for a migrated one. */
36
+ const UPLOAD_ID = /^[A-Za-z0-9_-]{1,80}$/;
37
+ /** A stored name: eight hex characters, a dash and the cleaned upload name (cleanUploadName). */
38
+ const STORED_NAME = /^[0-9a-f]{8}-[\w.-]{1,200}$/;
39
+
40
+ /** Whether the three parts of a private reference have the shapes this store writes. */
41
+ export function validParts(slug, id, name) {
42
+ return typeof slug === 'string' && slug !== '' && UPLOAD_ID.test(String(id || ''))
43
+ && STORED_NAME.test(String(name || '')) && name !== '.' && name !== '..';
44
+ }
45
+
46
+ /**
47
+ * The file for slug/id/name, inside the store. Throws (statusCode 404) for any
48
+ * part that is not one plain segment of the expected shape.
49
+ */
50
+ export function uploadPath(slug, id, name, root = formUploadsRoot()) {
51
+ if (!validParts(slug, id, name)) {
52
+ throw Object.assign(new Error('Not found'), {statusCode: 404, code: 'ENOENT'});
53
+ }
54
+ return fileIn(fileIn(fileIn(root, slug), id), name);
55
+ }
56
+
57
+ /** The route a stored reference points at. */
58
+ export function uploadUrl(slug, id, name) {
59
+ return `/api/forms/${encodeURIComponent(slug)}/uploads/${encodeURIComponent(id)}/${encodeURIComponent(name)}`;
60
+ }
61
+
62
+ const URL_RE = /^\/api\/forms\/([^/?#]+)\/uploads\/([^/?#]+)\/([^/?#]+)$/;
63
+
64
+ /**
65
+ * The parts of a private reference's url, or null when it is not one (or has
66
+ * parts of the wrong shape).
67
+ *
68
+ * @param {string} url
69
+ * @returns {{slug: string, id: string, name: string}|null}
70
+ */
71
+ export function parseUploadUrl(url) {
72
+ const m = URL_RE.exec(String(url || ''));
73
+ if (!m) return null;
74
+ let slug, id, name;
75
+ try { [slug, id, name] = m.slice(1).map(decodeURIComponent); } catch { return null; }
76
+ return validParts(slug, id, name) ? {slug, id, name} : null;
77
+ }
78
+
79
+ /**
80
+ * Keep the store out of git: a `*` .gitignore inside it (so a site repo
81
+ * never commits a visitor's file, whatever its own .gitignore says). Never throws.
82
+ */
83
+ export function keepUploadsOutOfGit(root = formUploadsRoot()) {
84
+ try {
85
+ mkdirSync(root, {recursive: true});
86
+ const ignore = path.join(root, '.gitignore');
87
+ if (!existsSync(ignore)) writeFileSync(ignore, '# Visitors\' form uploads - private, never committed.\n*\n');
88
+ } catch { /* never fail a submission over this */ }
89
+ }
90
+
91
+ /**
92
+ * Write one file of a submission. Never over another file: EEXIST is thrown for
93
+ * the caller to pick another name, and a write that fails part way is removed.
94
+ *
95
+ * @returns {Promise<{slug: string, id: string, name: string, url: string}>}
96
+ */
97
+ export async function saveUpload(slug, id, name, buffer, root = formUploadsRoot()) {
98
+ const file = uploadPath(slug, id, name, root);
99
+ keepUploadsOutOfGit(root);
100
+ await fs.mkdir(path.dirname(file), {recursive: true});
101
+ try {
102
+ await fs.writeFile(file, buffer, {flag: 'wx'});
103
+ } catch (err) {
104
+ if (err.code !== 'EEXIST') await fs.rm(file, {force: true}).catch(() => {});
105
+ throw err;
106
+ }
107
+ return {slug, id, name, url: uploadUrl(slug, id, name)};
108
+ }
109
+
110
+ /**
111
+ * A stored file to serve: its path and size, or null when it is not there (or
112
+ * is not a regular file).
113
+ */
114
+ export async function statUpload(slug, id, name, root = formUploadsRoot()) {
115
+ let file;
116
+ try { file = uploadPath(slug, id, name, root); } catch { return null; }
117
+ try {
118
+ const st = await fs.lstat(file);
119
+ return st.isFile() ? {file, size: st.size} : null;
120
+ } catch { return null; }
121
+ }
122
+
123
+ export const openUpload = (file) => createReadStream(file);
124
+
125
+ /**
126
+ * Delete one stored file, and its submission folder once empty. Answers false
127
+ * when there was nothing to delete. Throws (404) for a reference of the wrong shape.
128
+ */
129
+ export async function deleteUpload(slug, id, name, root = formUploadsRoot()) {
130
+ const file = uploadPath(slug, id, name, root);
131
+ let st;
132
+ try { st = await fs.lstat(file); } catch (err) { if (err.code === 'ENOENT') return false; throw err; }
133
+ if (!st.isFile()) return false;
134
+ await fs.unlink(file);
135
+ await fs.rmdir(path.dirname(file)).catch(() => {}); // only when empty
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * How a file is sent: inline only for the kinds a browser shows without
141
+ * running anything (PNG, JPEG, GIF, WebP, PDF), as an attachment otherwise.
142
+ *
143
+ * @param {string} name - the stored name
144
+ * @returns {{type: string, inline: boolean}}
145
+ */
146
+ export function servedAs(name) {
147
+ const ext = path.extname(String(name || '')).toLowerCase();
148
+ const inline = {'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
149
+ '.webp': 'image/webp', '.pdf': 'application/pdf'}[ext];
150
+ return inline ? {type: inline, inline: true} : {type: 'application/octet-stream', inline: false};
151
+ }
152
+
153
+ /**
154
+ * A Content-Disposition value: `inline` or `attachment`, an ASCII fallback
155
+ * name and the UTF-8 one (RFC 6266 / 5987).
156
+ */
157
+ export function disposition(inline, displayName) {
158
+ const raw = String(displayName || 'file').replace(/[\u0000-\u001f\u007f"\\/]/g, '_').slice(0, 200) || 'file';
159
+ const ascii = raw.replace(/[^\x20-\x7e]/g, '_');
160
+ return `${inline ? 'inline' : 'attachment'}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(raw)}`;
161
+ }