domma-cms 1.47.6 → 1.48.1

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.
@@ -1,4 +1,4 @@
1
- import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-chrome.js";import{helpPopovers as ie}from"../lib/help-popover.js";import{onceClosed as le,openMenuAt as re,sidebarCount as Me,viewLifetime as Ae}from"../lib/tool-kit.js";import{FILTERS as Le,arrangeTokens as Oe,checkToken as Ie,countStates as $e,scopesToText as Ne,toLocalInput as Pe,tokenRow as qe,tokenState as ce}from"../lib/api-tokens-arrange.js";const de=/^#\/api-tokens\/?(\?.*)?$/,De="#/api-tokens",D="api-tokens.draft",H="api-tokens.filter",Re=`
1
+ import{api as C,getUser as Fe}from"../api.js";import{addBannerAction as _e}from"../lib/plugin-chrome.js";import{helpPopovers as ke}from"../lib/help-popover.js";import{onceClosed as xe,openMenuAt as we,sidebarCount as Ue,viewLifetime as ze}from"../lib/tool-kit.js";import{FILTERS as Ke,arrangeTokens as He,checkToken as Ge,countStates as Ye,RECIPE_CONTENT as Je,recipeContentScopes as Ve,recipePayload as We,recipeReport as Qe,recipeRows as Xe,recipeUnavailable as Ze,scopesToText as et,toLocalInput as tt,tokenRow as at,tokenState as ge}from"../lib/api-tokens-arrange.js";import{connectionFile as nt,connectionFileName as ot,handoverLink as st,sealConnection as it}from"../../../public/js/token-handover.mjs";const Ee=/^#\/api-tokens\/?(\?.*)?$/,lt="#/api-tokens",Q="api-tokens.draft",ne="api-tokens.filter",ct=`
2
2
  <div class="atx-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
3
3
  <span class="atx-icon" aria-hidden="true"><span data-icon="key" data-icon-size="16"></span></span>
4
4
  <span class="atx-main"><strong>{{name}}</strong><small><code>{{hint}}</code> \xB7 {{meta}}</small></span>
@@ -8,7 +8,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
8
8
  </span>
9
9
  <span class="atx-used" data-bind-text="used"></span>
10
10
  <button type="button" class="atx-kebab" aria-label="Actions for {{name}}" title="Actions">\u22EE</button>
11
- </div>`,L=c=>String(c??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function pe(c){const d=document.createElement("template");return d.innerHTML=c.trim(),d.content.firstElementChild}async function ue(c){try{return await navigator.clipboard.writeText(c),!0}catch{return!1}}const l=Ae(de);export const apiTokensView={templateUrl:"/admin/js/templates/api-tokens.html",async onMount(c){l.reset();const d=c.get(0).querySelector(".atx")||c.get(0),O=()=>de.test(location.hash)&&d.isConnected,x=M.observable([]),j=M.observable([]),R=M.observable(!0),F=M.observable("");let U="all";try{U=Le.includes(S.get(H))?S.get(H):"all"}catch{}const r=M.observable(U),h=M.observable(""),Y=M.observable("");l.add(M.effect(()=>{const e=r.value;try{S.set(H,e)}catch{}}));const _=M.observable([]);l.add(M.effect(()=>{const e=Date.now();_.value=Oe(x.value,{filter:r.value,project:h.value,query:Y.value},e).map(t=>qe(t,e))}));const V=M.computed(()=>$e(x.value)),fe=M.computed(()=>x.value.length?"No tokens match.":"No API tokens yet - New token in the banner makes one."),C=e=>x.peek().find(t=>t.id===e);async function J(){try{const[e,t]=await Promise.all([g.apiTokens.list(),g.projects.list().catch(()=>[])]);if(!O())return;x.value=Array.isArray(e)?e:[],j.value=Array.isArray(t)?t:[],F.value="",ke()}catch(e){F.value=`Could not load the tokens: ${e.message||e}`}finally{R.value=!1}}const $=async()=>{Me(De),O()&&await J()};async function W(e,t){if(!(!t&&!await E.confirm(`Switch off "${L(e.name)}"? Callers using it are refused until it is switched back on.`)))try{await g.apiTokens.update(e.id,{enabled:t}),E.toast(`"${e.name}" ${t?"switched on":"switched off"}.`,{type:"success"}),await $()}catch(a){E.toast(`Not changed: ${a.message||a}`,{type:"error"})}}async function me(e){if(await E.confirm(`Revoke "${L(e.name)}"? Anything using it loses access at once. This cannot be undone - a new token would have a different value.`))try{await g.apiTokens.revoke(e.id),E.toast(`Revoked "${e.name}".`,{type:"success"}),await $()}catch(t){E.toast(`Not revoked: ${t.message||t}`,{type:"error"})}}let b=null,y=null;const T=new Set;let ve=!1;function G(e,t,a){const s=e.close.bind(e);let o=!1,u=!1;return e.close=async v=>{if(!o&&v!==!0&&t()){if(u)return;u=!0;const N=await E.confirm(a);if(u=!1,!N)return}return o=!0,s()},()=>{o=!0}}function A(e=null,t=null){const a=e?C(e):null;if(e&&!a){E.toast("That token is no longer there.",{type:"warning"});return}const s=!a,o=j.peek();if(s&&!o.length){E.toast("Make a project first - a token works inside one.",{type:"warning"});return}const u={name:a?.name??"",project:a?.project??(h.peek()||o[0]?.slug||""),expires:Pe(a?.expiresAt),scopes:Ne(a?.scopes),enabled:a?a.enabled!==!1:!0,draftsOnly:a?a.draftsOnly===!0:!1,...t||{}},v=Object.fromEntries(Object.entries(u).map(([n,i])=>[n,M.observable(i)])),N=n=>JSON.stringify(Object.fromEntries(Object.entries(n).map(([i,z])=>[i,typeof z=="boolean"?z:String(z??"")]))),ee=()=>Object.fromEntries(Object.keys(v).map(n=>[n,v[n].peek()])),ge=N(u),te=()=>N(ee())!==ge||!!t,P=M.observable(!1),B=M.computed(()=>Ie(Object.fromEntries(Object.keys(v).map(n=>[n,v[n].value])),{isNew:s,projects:j.value.map(n=>n.slug)})),q=n=>M.computed(()=>B.value.errors[n]||""),Ee=a?ce(a):null,ae={...v,saving:P,isNew:s,notNew:!s,nameErr:q("name"),projectErr:q("project"),scopesErr:q("scopes"),expiresErr:q("expires"),cannot:M.computed(()=>P.value||Object.keys(B.value.errors).length>0),saveText:s?"Create token":"Save",fixedProject:a?`${a.project} - fixed for the token's life (revoke and make a new one to move it)`:"",hint:a?`dcms_\u2026${a.tokenHint||"????"}${Ee?.state==="expired"?" - expired: set a later date to bring it back":""}`:""},f=E.slideover({title:s?"New API token":`Edit ${L(a.name)}`,size:"md",position:"right"}),w=pe(`
11
+ </div>`,O=y=>String(y??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function je(y){const k=document.createElement("template");return k.innerHTML=y.trim(),k.content.firstElementChild}async function oe(y){try{return await navigator.clipboard.writeText(y),!0}catch{return!1}}const b=ze(Ee);export const apiTokensView={templateUrl:"/admin/js/templates/api-tokens.html",async onMount(y){b.reset();const k=y.get(0).querySelector(".atx")||y.get(0),Y=()=>Ee.test(location.hash)&&k.isConnected,R=M.observable([]),B=M.observable([]),X=M.observable(!0),Z=M.observable("");let se="all";try{se=Ke.includes(S.get(ne))?S.get(ne):"all"}catch{}const v=M.observable(se),L=M.observable(""),ie=M.observable("");b.add(M.effect(()=>{const e=v.value;try{S.set(ne,e)}catch{}}));const ee=M.observable([]);b.add(M.effect(()=>{const e=Date.now();ee.value=He(R.value,{filter:v.value,project:L.value,query:ie.value},e).map(t=>at(t,e))}));const le=M.computed(()=>Ye(R.value)),Ce=M.computed(()=>R.value.length?"No tokens match.":"No API tokens yet - New token in the banner makes one."),F=e=>R.peek().find(t=>t.id===e);async function ce(){try{const[e,t]=await Promise.all([C.apiTokens.list(),C.projects.list().catch(()=>[])]);if(!Y())return;R.value=Array.isArray(e)?e:[],B.value=Array.isArray(t)?t:[],Z.value="",$e()}catch(e){Z.value=`Could not load the tokens: ${e.message||e}`}finally{X.value=!1}}const J=async()=>{Ue(lt),Y()&&await ce()};async function re(e,t){if(!(!t&&!await E.confirm(`Switch off "${O(e.name)}"? Callers using it are refused until it is switched back on.`)))try{await C.apiTokens.update(e.id,{enabled:t}),E.toast(`"${e.name}" ${t?"switched on":"switched off"}.`,{type:"success"}),await J()}catch(o){E.toast(`Not changed: ${o.message||o}`,{type:"error"})}}async function Se(e){if(await E.confirm(`Revoke "${O(e.name)}"? Anything using it loses access at once. This cannot be undone - a new token would have a different value.`))try{await C.apiTokens.revoke(e.id),E.toast(`Revoked "${e.name}".`,{type:"success"}),await J()}catch(t){E.toast(`Not revoked: ${t.message||t}`,{type:"error"})}}let $=null,N=null;const _=new Set;let Te=!1;function de(e,t,o){const u=e.close.bind(e);let w=!1,h=!1;return e.close=async s=>{if(!w&&s!==!0&&t()){if(h)return;h=!0;const c=await E.confirm(o);if(h=!1,!c)return}return w=!0,u()},()=>{w=!0}}function U(e=null,t=null){const o=e?F(e):null;if(e&&!o){E.toast("That token is no longer there.",{type:"warning"});return}const u=!o,w=B.peek();if(u&&!w.length){E.toast("Make a project first - a token works inside one.",{type:"warning"});return}const h={name:o?.name??"",project:o?.project??(L.peek()||w[0]?.slug||""),expires:tt(o?.expiresAt),scopes:et(o?.scopes),enabled:o?o.enabled!==!1:!0,draftsOnly:o?o.draftsOnly===!0:!1,bot:!1,botEdit:!1,...t||{}},s=Object.fromEntries(Object.entries(h).map(([a,i])=>[a,M.observable(i)])),c=a=>JSON.stringify(Object.fromEntries(Object.entries(a).map(([i,n])=>[i,typeof n=="boolean"?n:String(n??"")]))),z=()=>Object.fromEntries(Object.keys(s).map(a=>[a,s[a].peek()])),K=c(h),H=()=>c(z())!==K||!!t,f=M.observable(!1),d=M.computed(()=>Ge(Object.fromEntries(Object.keys(s).map(a=>[a,s[a].value])),{isNew:u,projects:B.value.map(a=>a.slug)})),p=a=>M.computed(()=>d.value.errors[a]||""),V=o?ge(o):null,l={list:[],chosen:new Set,content:new Set,mayOpen:!0,project:null},W=M.computed(()=>u&&s.bot.value===!0),he={...s,saving:f,isNew:u,notNew:!u,botOn:W,botOff:M.computed(()=>!W.value),nameErr:p("name"),projectErr:p("project"),scopesErr:p("scopes"),expiresErr:p("expires"),cannot:M.computed(()=>f.value||Object.keys(d.value.errors).length>0),saveText:u?"Create token":"Save",fixedProject:o?`${o.project} - fixed for the token's life (revoke and make a new one to move it)`:"",hint:o?`dcms_\u2026${o.tokenHint||"????"}${V?.state==="expired"?" - expired: set a later date to bring it back":""}`:""},g=E.slideover({title:u?"New API token":`Edit ${O(o.name)}`,size:"md",position:"right"}),j=je(`
12
12
  <div class="atx-form">
13
13
  <div>
14
14
  <label class="form-label" for="atx-f-name">Name <span class="text-danger">*</span></label>
@@ -25,7 +25,17 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
25
25
  <label class="form-label">Token</label>
26
26
  <div class="atx-fixed"><code data-bind-text="hint"></code><br><span data-bind-text="fixedProject"></span></div>
27
27
  </div>
28
- <div>
28
+ <div class="atx-setting" data-bind-hidden="notNew">
29
+ <label class="form-label" for="atx-f-bot">Bot that writes drafts
30
+ <span data-help-title="Bot that writes drafts" data-help="For Grok, a script or another site that writes content for you. Tick the collections it may write to: the token is scoped to them with Drafts only on, and each one is opened to tokens (never wider than it is). A collection without a draft status gets a Status field (draft / published). Everything the bot writes waits as a draft for a person to publish."></span></label>
31
+ <input id="atx-f-bot" type="checkbox" class="form-switch" data-model="bot.value">
32
+ </div>
33
+ <div class="atx-recipe" data-bind-hidden="botOff.value">
34
+ <div class="atx-recipe-content"></div>
35
+ <div class="atx-recipe-list"><small class="atx-hint">Loading the collections\u2026</small></div>
36
+ <label class="atx-recipe-edit"><input type="checkbox" data-model="botEdit.value"> It may also change its own drafts (never a published entry)</label>
37
+ </div>
38
+ <div data-bind-hidden="botOn.value">
29
39
  <label class="form-label" for="atx-f-scopes">Scopes
30
40
  <span data-help-title="Scopes" data-help="Leave empty and the token may use every collection in its project that allows token access, and the Content API where it is set to API tokens. Otherwise one line each: a collection's slug, then a colon and the verbs it may use - create, read, update, delete (no verbs means all four), for example jobs: read. For the Content API, a line of @pages, @menus, @site or @search - read-only, no verbs. A token with only collection lines gets no content."></span></label>
31
41
  <textarea id="atx-f-scopes" class="form-input font-mono" rows="4" placeholder="jobs: read&#10;enquiries: create, read&#10;@pages" data-model="scopes.value"></textarea>
@@ -37,7 +47,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
37
47
  <input id="atx-f-expires" type="datetime-local" class="form-input" data-model="expires.value">
38
48
  <small class="atx-err" data-bind-hidden="!expiresErr.value" data-bind-text="expiresErr.value"></small>
39
49
  </div>
40
- <div class="atx-setting">
50
+ <div class="atx-setting" data-bind-hidden="botOn.value">
41
51
  <label class="form-label" for="atx-f-drafts">Drafts only
42
52
  <span data-help-title="Drafts only" data-help="For a bot or another site writing on your behalf. Everything it creates is saved as a draft, whatever it sends, so nothing reaches the public until a person publishes it. It may change or delete its drafts but never a published entry, and it cannot write to a collection that has no draft status (a Status field with a draft option, as Blog posts have)."></span></label>
43
53
  <input id="atx-f-drafts" type="checkbox" class="form-switch" data-model="draftsOnly.value">
@@ -54,7 +64,7 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
54
64
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">
55
65
  <span data-icon="check" data-icon-size="13"></span> <span data-bind-text="saveText"></span></button>
56
66
  </div>
57
- </div>`),ne=w.querySelector("#atx-f-project");for(const n of o){const i=document.createElement("option");i.value=n.slug,i.textContent=`${n.name||n.slug} (${n.slug})`,ne.appendChild(i)}let K=()=>{};async function se(){if(ae.cannot.peek())return;P.value=!0;const{payload:n}=B.peek();try{if(s){const i=await g.apiTokens.create(n);K(),f.close(),await $(),he(i?.plaintext,n.name)}else await g.apiTokens.update(a.id,n),E.toast("Saved.",{type:"success"}),K(),f.close(),await $()}catch(i){E.toast(`Not saved: ${i.message||i}`,{type:"error"})}finally{P.value=!1}}f.element.appendChild(w);const je=ie(w),Se=M.applyBindings(ae,w,{methods:{save:se,cancel:()=>f.close()}});ne.value=v.project.peek();const Ce=n=>{(n.ctrlKey||n.metaKey)&&n.key==="Enter"&&(n.preventDefault(),se())};w.addEventListener("keydown",Ce);const oe={id:a?.id??null,dirty:te,values:ee};b=oe,T.add(f),le(f,()=>{Se.dispose(),je(),T.delete(f),b===oe&&(b=null)}),K=G(f,te,"Discard the changes you have not saved?"),I.scan(w),f.open(),w.querySelector("#atx-f-name")?.focus()}function he(e,t){if(!e){E.toast("The token was made, but its value did not come back - revoke it and make another.",{type:"error"});return}let a=!1;const s=E.slideover({title:"Token created",size:"sm",position:"right"}),o=pe(`
67
+ </div>`),me=j.querySelector("#atx-f-project");for(const a of w){const i=document.createElement("option");i.value=a.slug,i.textContent=`${a.name||a.slug} (${a.slug})`,me.appendChild(i)}const qe=j.querySelector(".atx-recipe-content");for(const a of Je){const i=document.createElement("label");i.className=`atx-recipe-row is-${a.resource==="pages"?"ok":"attention"}`;const n=document.createElement("input");n.type="checkbox",n.addEventListener("change",()=>{n.checked?l.content.add(a.resource):l.content.delete(a.resource)});const m=document.createElement("span"),r=document.createElement("strong");r.textContent=a.label;const q=document.createElement("small");q.textContent=a.note,m.append(r,document.createElement("br"),q),i.append(n,m),qe.appendChild(i)}const P=j.querySelector(".atx-recipe-list");function be(){const a=Xe(l.list,l.chosen,{edit:s.botEdit.peek()}).filter(n=>n.ok);if(P.replaceChildren(),!l.mayOpen){const n=document.createElement("small");n.className="atx-err",n.textContent="A bot token opens its collections to tokens, which needs permission to change collections (collections.update).",P.appendChild(n)}if(!a.length){const n=document.createElement("small");n.className="atx-hint",n.textContent="No collection in this project can take a bot. Make one, or pick another project.",P.appendChild(n)}for(const n of a){const m=document.createElement("label");m.className=`atx-recipe-row is-${n.tone}${n.ok?"":" is-off"}`;const r=document.createElement("input");r.type="checkbox",r.checked=n.chosen,r.disabled=!n.ok||!l.mayOpen,r.addEventListener("change",()=>{r.checked?l.chosen.add(n.slug):l.chosen.delete(n.slug)});const q=document.createElement("span"),ae=document.createElement("strong");ae.textContent=n.title;const D=document.createElement("code");D.textContent=n.slug;const G=document.createElement("small");G.textContent=n.note,q.append(ae," ",D,document.createElement("br"),G),m.append(r,q),P.appendChild(m)}const i=Ze(l.list);if(i){const n=document.createElement("small");n.className="atx-hint",n.textContent=i,P.appendChild(n)}}async function Ie(){const a=s.project.peek();if(!(!u||!s.bot.peek()||!a||l.project===a)){l.project=a,l.chosen.clear();try{const i=await C.apiTokens.recipe(a);if(l.project!==a)return;l.list=i?.collections||[],l.mayOpen=i?.mayOpen!==!1}catch(i){l.list=[],P.textContent=`Could not load the collections: ${i.message||i}`;return}be()}}const Re=[M.effect(()=>{s.bot.value,s.project.value,Ie()}),M.effect(()=>{s.botEdit.value,l.list.length&&be()})];let te=()=>{};async function ve(){if(he.cannot.peek())return;const{payload:a}=d.peek();let i=a;if(W.peek()){const n=We(l.list,l.chosen,{edit:s.botEdit.peek()}),m=Ve([...l.content],{edit:s.botEdit.peek()});if(!n&&!m.length){E.toast("Tick at least one thing for the bot to write.",{type:"warning"});return}i={...a,scopes:m,draftsOnly:!0,recipe:n||{collections:[]}}}f.value=!0;try{if(u){let n;try{n=await C.apiTokens.create(i)}catch(r){if(r.status!==409||!Array.isArray(r.body?.others))throw r;const q=r.body.others.map(D=>`<li><strong>${O(D.slug)}</strong> (${O(D.verb)}): ${D.tokens.map(G=>`${O(G.name)}${G.draftsOnly?" (drafts only)":" - <em>may publish</em>"}`).join(", ")}</li>`).join("");if(!await E.confirm(`Opening these collections to tokens also lets these existing tokens write to them:<ul>${q}</ul>Narrow those tokens' scopes first if they should not. Go ahead anyway?`)){f.value=!1;return}n=await C.apiTokens.create({...i,recipe:{...i.recipe,confirmOthers:!0}})}te(),g.close(),await J();const m=W.peek()&&l.list.some(r=>l.chosen.has(r.slug)&&r.hasAuthor);Oe(n?.plaintext,a.name,{token:n?.token,report:Qe(n?.collections||[]),authorId:m&&Fe()?.id||null})}else await C.apiTokens.update(o.id,a),E.toast("Saved.",{type:"success"}),te(),g.close(),await J()}catch(n){E.toast(`Not saved: ${n.message||n}`,{type:"error"})}finally{f.value=!1}}g.element.appendChild(j);const Pe=ke(j),De=M.applyBindings(he,j,{methods:{save:ve,cancel:()=>g.close()}});me.value=s.project.peek();const Be=a=>{(a.ctrlKey||a.metaKey)&&a.key==="Enter"&&(a.preventDefault(),ve())};j.addEventListener("keydown",Be);const ye={id:o?.id??null,dirty:H,values:z};$=ye,_.add(g),xe(g,()=>{for(const a of Re)try{typeof a=="function"?a():a?.dispose?.()}catch{}De.dispose(),Pe(),_.delete(g),$===ye&&($=null)}),te=de(g,H,"Discard the changes you have not saved?"),I.scan(j),g.open(),j.querySelector("#atx-f-name")?.focus()}function Oe(e,t,{token:o=null,report:u=[],authorId:w=null}={}){if(!e){E.toast("The token was made, but its value did not come back - revoke it and make another.",{type:"error"});return}let h=!1;const s=E.slideover({title:"Token created",size:"sm",position:"right"}),c=je(`
58
68
  <div class="atx-secret">
59
69
  <p class="atx-warn"><strong>Copy it now.</strong> This is the only time it is shown - only a fingerprint is kept. If it is lost, revoke it and make another.</p>
60
70
  <code class="atx-token"></code>
@@ -64,4 +74,21 @@ import{api as g}from"../api.js";import{addBannerAction as Te}from"../lib/plugin-
64
74
  <button type="button" class="btn btn-sm btn-primary atx-copy"><span data-icon="copy" data-icon-size="13"></span> Copy</button>
65
75
  <button type="button" class="btn btn-sm btn-ghost atx-done">Done</button>
66
76
  </div>
67
- </div>`);o.querySelector(".atx-token").textContent=e,o.querySelector(".atx-copy").addEventListener("click",async()=>{await ue(e)?(a=!0,o.querySelector(".copied-note").hidden=!1):E.toast("Copy failed - select the token and copy it by hand.",{type:"error"})}),o.querySelector(".atx-done").addEventListener("click",()=>s.close()),s.element.appendChild(o);const u={copied:()=>a};s.__dmSecret=!0,y=u,T.add(s),le(s,()=>{T.delete(s),y===u&&(y=null),e=null}),G(s,()=>!a,`You have not copied the token for "${L(t)}". Once this closes it can never be shown again. Close anyway?`),I.scan(o),s.open()}function be(e){const t=C(e);if(!t)return[];const{state:a}=ce(t);return[{header:t.name||"Token"},{label:"Edit\u2026",icon:"edit",action:()=>A(t.id)},t.enabled===!1?{label:"Switch on",icon:"play",action:()=>W(t,!0)}:{label:"Switch off\u2026",icon:"pause",disabled:a==="expired",action:()=>W(t,!1)},{type:"divider"},{label:"Copy its ending",icon:"copy",action:async()=>{E.toast(await ue(`dcms_\u2026${t.tokenHint||""}`)?"Copied the ending - the token itself is never shown again.":"Copy failed.",{type:"info"})}},{label:`Show only ${t.project}`,icon:"filter",disabled:h.peek()===t.project,action:()=>{h.value=t.project,ye()}},{type:"divider"},{label:"Revoke\u2026",icon:"trash",danger:!0,action:()=>me(t)}]}const m=d.querySelector(".atx-list");m.innerHTML=Re;const k=d.querySelector(".atx-project"),ye=()=>{k&&(k.value=h.peek())};function ke(){if(!k)return;const e=h.peek();for(;k.options.length>1;)k.remove(1);for(const t of j.peek()){const a=document.createElement("option");a.value=t.slug,a.textContent=t.name||t.slug,k.appendChild(a)}k.value=e}const we=M.applyBindings({tokens:x,projects:j,loading:R,loadError:F,filter:r,project:h,query:Y,rows:_,counts:V,emptyText:fe},d,{methods:{showAll:()=>{r.value="all"},showActive:()=>{r.value="active"},showExpiring:()=>{r.value="expiring"},showExpired:()=>{r.value="expired"},showDisabled:()=>{r.value="disabled"}}});l.add(()=>we.dispose()),l.add(ie(d,{position:"bottom"})),l.add(M.effect(()=>{_.value,requestAnimationFrame(()=>{m.isConnected&&I.scan(m)})})),l.add(M.effect(()=>{const e=V.value,t=r.peek();t!=="all"&&!R.value&&!e[t]&&(r.value="all")}));const xe=E.contextMenu(m,{cursor:"glyph",match:".atx-row",inherit:!1,density:"compact",items:e=>be(e.dataset.id)});l.add(()=>xe?.destroy?.());const Q=e=>{const t=e.target.closest(".atx-row");if(!t)return;const a=e.target.closest(".atx-kebab");if(a){re(a);return}A(t.dataset.id)},X=e=>{const t=e.target.closest(".atx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),re(t)):e.key==="Enter"&&e.target===t&&A(t.dataset.id))};m.addEventListener("click",Q),m.addEventListener("keydown",X),l.add(()=>{m.removeEventListener("click",Q),m.removeEventListener("keydown",X)}),Te(c,{id:"api-tokens-new",icon:"plus",title:"New token",onClick:()=>A()});const Z=e=>{(b?.dirty()||y&&!y.copied())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Z),l.add(()=>window.removeEventListener("beforeunload",Z)),l.add(()=>{if(b?.dirty())try{S.set(D,{id:b.id,values:b.values(),at:new Date().toISOString()})}catch{}ve=!0,[...T].forEach(e=>{if(!(y&&e.__dmSecret&&!y.copied()))try{e.close(!0)}catch{}})}),I.scan(d),await J(),!O())return;let p=null;try{p=S.get(D)}catch{}if(p?.values){try{S.remove?S.remove(D):S.set(D,null)}catch{}const e=p.id&&C(p.id)?`your changes to "${L(C(p.id).name)}"`:"the new token you started";await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&O()&&A(p.id&&C(p.id)?p.id:null,p.values)}}};
77
+ <div class="atx-handover">
78
+ <p class="atx-hint">Giving it to someone else, or to a bot? Send a one-time link instead of the token - it opens once, within 24 hours, and shows them how to use it. Or download the connection file a script can read.</p>
79
+ <div class="atx-actions">
80
+ <button type="button" class="btn btn-sm btn-secondary atx-link"><span data-icon="link" data-icon-size="13"></span> Make a one-time link</button>
81
+ <button type="button" class="btn btn-sm btn-ghost atx-file"><span data-icon="download" data-icon-size="13"></span> Connection file</button>
82
+ </div>
83
+ <div class="atx-link-out" hidden>
84
+ <code class="atx-link-text"></code>
85
+ <div class="atx-actions">
86
+ <small class="atx-hint atx-link-note"></small>
87
+ <span class="atx-spacer"></span>
88
+ <button type="button" class="btn btn-sm btn-primary atx-link-copy"><span data-icon="copy" data-icon-size="13"></span> Copy link</button>
89
+ </div>
90
+ </div>
91
+ </div>
92
+ <ul class="atx-report" hidden></ul>
93
+ </div>`);if(c.querySelector(".atx-token").textContent=e,u.length){const f=c.querySelector(".atx-report");for(const d of u){const p=document.createElement("li");p.textContent=d.trim(),d.startsWith(" ")&&(p.className="atx-report-warn"),f.appendChild(p)}f.hidden=!1}const z=()=>nt({origin:location.origin,token:o||{name:t},plaintext:e,authorId:w});c.querySelector(".atx-file").addEventListener("click",()=>{const f=z(),d=document.createElement("a");d.href=URL.createObjectURL(new Blob([JSON.stringify(f,null,2)+`
94
+ `],{type:"application/json"})),d.download=ot(f),document.body.appendChild(d),d.click(),setTimeout(()=>{URL.revokeObjectURL(d.href),d.remove()},1e3),h=!0});let K="";c.querySelector(".atx-link").addEventListener("click",async f=>{const d=f.currentTarget;if(!o?.id){E.toast("Make the link from a new token.",{type:"warning"});return}d.disabled=!0;try{const p=await it(z()),V=await C.apiTokens.handover(o.id,{ciphertext:p.ciphertext,iv:p.iv});K=st(location.origin,V.id,p.key),c.querySelector(".atx-link-text").textContent=K,c.querySelector(".atx-link-note").textContent=`Opens once, until ${new Date(V.expiresAt).toLocaleString("en-GB")}.`,c.querySelector(".atx-link-out").hidden=!1,h=!0}catch(p){E.toast(`No link made: ${p.message||p}`,{type:"error"}),d.disabled=!1}}),c.querySelector(".atx-link-copy").addEventListener("click",async()=>{await oe(K)?E.toast("Link copied.",{type:"success"}):E.toast("Copy failed - select the link and copy it by hand.",{type:"error"})}),c.querySelector(".atx-copy").addEventListener("click",async()=>{await oe(e)?(h=!0,c.querySelector(".copied-note").hidden=!1):E.toast("Copy failed - select the token and copy it by hand.",{type:"error"})}),c.querySelector(".atx-done").addEventListener("click",()=>s.close()),s.element.appendChild(c);const H={copied:()=>h};s.__dmSecret=!0,N=H,_.add(s),xe(s,()=>{_.delete(s),N===H&&(N=null),e=null}),de(s,()=>!h,`You have not copied the token for "${O(t)}". Once this closes it can never be shown again. Close anyway?`),I.scan(c),s.open()}function Me(e){const t=F(e);if(!t)return[];const{state:o}=ge(t);return[{header:t.name||"Token"},{label:"Edit\u2026",icon:"edit",action:()=>U(t.id)},t.enabled===!1?{label:"Switch on",icon:"play",action:()=>re(t,!0)}:{label:"Switch off\u2026",icon:"pause",disabled:o==="expired",action:()=>re(t,!1)},{type:"divider"},{label:"Copy its ending",icon:"copy",action:async()=>{E.toast(await oe(`dcms_\u2026${t.tokenHint||""}`)?"Copied the ending - the token itself is never shown again.":"Copy failed.",{type:"info"})}},{label:`Show only ${t.project}`,icon:"filter",disabled:L.peek()===t.project,action:()=>{L.value=t.project,Le()}},{type:"divider"},{label:"Revoke\u2026",icon:"trash",danger:!0,action:()=>Se(t)}]}const T=k.querySelector(".atx-list");T.innerHTML=ct;const A=k.querySelector(".atx-project"),Le=()=>{A&&(A.value=L.peek())};function $e(){if(!A)return;const e=L.peek();for(;A.options.length>1;)A.remove(1);for(const t of B.peek()){const o=document.createElement("option");o.value=t.slug,o.textContent=t.name||t.slug,A.appendChild(o)}A.value=e}const Ne=M.applyBindings({tokens:R,projects:B,loading:X,loadError:Z,filter:v,project:L,query:ie,rows:ee,counts:le,emptyText:Ce},k,{methods:{showAll:()=>{v.value="all"},showActive:()=>{v.value="active"},showExpiring:()=>{v.value="expiring"},showExpired:()=>{v.value="expired"},showDisabled:()=>{v.value="disabled"}}});b.add(()=>Ne.dispose()),b.add(ke(k,{position:"bottom"})),b.add(M.effect(()=>{ee.value,requestAnimationFrame(()=>{T.isConnected&&I.scan(T)})})),b.add(M.effect(()=>{const e=le.value,t=v.peek();t!=="all"&&!X.value&&!e[t]&&(v.value="all")}));const Ae=E.contextMenu(T,{cursor:"glyph",match:".atx-row",inherit:!1,density:"compact",items:e=>Me(e.dataset.id)});b.add(()=>Ae?.destroy?.());const pe=e=>{const t=e.target.closest(".atx-row");if(!t)return;const o=e.target.closest(".atx-kebab");if(o){we(o);return}U(t.dataset.id)},ue=e=>{const t=e.target.closest(".atx-row");t&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),we(t)):e.key==="Enter"&&e.target===t&&U(t.dataset.id))};T.addEventListener("click",pe),T.addEventListener("keydown",ue),b.add(()=>{T.removeEventListener("click",pe),T.removeEventListener("keydown",ue)}),_e(y,{id:"api-tokens-new",icon:"plus",title:"New token",onClick:()=>U()});const fe=e=>{($?.dirty()||N&&!N.copied())&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",fe),b.add(()=>window.removeEventListener("beforeunload",fe)),b.add(()=>{if($?.dirty())try{S.set(Q,{id:$.id,values:$.values(),at:new Date().toISOString()})}catch{}Te=!0,[..._].forEach(e=>{if(!(N&&e.__dmSecret&&!N.copied()))try{e.close(!0)}catch{}})}),I.scan(k),await ce(),!Y())return;let x=null;try{x=S.get(Q)}catch{}if(x?.values){try{S.remove?S.remove(Q):S.set(Q,null)}catch{}const e=x.id&&F(x.id)?`your changes to "${O(F(x.id).name)}"`:"the new token you started";await E.confirm(`You left ${e} unsaved. Pick up where you left off?`)&&Y()&&U(x.id&&F(x.id)?x.id:null,x.values)}}};