@kurtbruns/kestrel 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.dev.vars.example +24 -2
  2. package/CHANGELOG.md +73 -1
  3. package/bin/kestrel.mjs +1 -1
  4. package/cli/dev.mjs +3 -3
  5. package/cli/init.mjs +98 -4
  6. package/dist/public/dashboard/app.js +327 -327
  7. package/dist/public/dashboard/app.js.map +4 -4
  8. package/dist/public/dashboard/index.html +6 -3
  9. package/dist/public/dashboard/styles.css +133 -21
  10. package/dist/worker/index.js +5940 -4434
  11. package/docs/README.md +5 -3
  12. package/docs/get-started/02-deploy.md +25 -21
  13. package/docs/get-started/03-access.md +20 -8
  14. package/docs/get-started/04-aws-account.md +68 -0
  15. package/docs/get-started/05-ses.md +326 -0
  16. package/docs/get-started/06-production-access.md +67 -0
  17. package/docs/get-started/{05-verify.md → 07-verify.md} +16 -26
  18. package/docs/get-started/{06-go-live.md → 08-go-live.md} +4 -2
  19. package/docs/guides/01-allow-claude.md +2 -2
  20. package/docs/guides/02-automate.md +1 -1
  21. package/docs/guides/03-notifications.md +12 -12
  22. package/docs/guides/07-upgrade.md +4 -4
  23. package/docs/guides/09-as-your-list-grows.md +8 -18
  24. package/docs/publishing/02-sending-rules.md +2 -2
  25. package/docs/publishing/03-name-your-publication.md +2 -0
  26. package/docs/publishing/04-write-a-post.md +1 -1
  27. package/docs/publishing/06-troubleshooting.md +37 -9
  28. package/docs/publishing/08-connect-claude.md +1 -1
  29. package/docs/publishing/09-share-your-subscribe-link.md +3 -1
  30. package/docs/publishing/10-check-your-setup.md +15 -9
  31. package/docs/publishing/README.md +8 -3
  32. package/docs/reference/01-configuration.md +18 -16
  33. package/docs/reference/02-sending-domain-dns.md +4 -4
  34. package/migrations/0015_provider_account.sql +18 -0
  35. package/migrations/0016_held_receipts.sql +26 -0
  36. package/migrations/0017_provider_account_rejected.sql +24 -0
  37. package/migrations/0018_notify_addresses.sql +13 -0
  38. package/migrations/0019_sending.sql +67 -0
  39. package/migrations/0020_notifications_not_sending.sql +40 -0
  40. package/package.json +1 -1
  41. package/packages/kestrel/lib/api.mjs +28 -3
  42. package/packages/kestrel/lib/oauth.mjs +5 -3
  43. package/template/claude/CLAUDE.md +5 -3
  44. package/template/wrangler.jsonc +6 -6
  45. package/docs/get-started/04-ses.md +0 -310
@@ -1,277 +1,272 @@
1
1
  // GENERATED by scripts/build-client.mjs from client/ — edit the source there, never this file.
2
- "use strict";(()=>{function Fn(e){if(!e||typeof e!="object")return null;let t=e;return t.error!=="unauthorized"?null:t.reason==="access_not_configured"||t.reason==="access_unidentified"?t.reason:null}function so(e){let t=document.getElementById(e);if(!t)throw new Error(`the admin page has no #${e}`);return t}var fe=so("app"),oo=so("identity"),io=so("toasts"),Ci=document.getElementById("navToggle"),to=document.getElementById("navScrim");function an(e){document.body.classList.toggle("nav-open",e),Ci?.setAttribute("aria-expanded",e?"true":"false"),to&&(to.hidden=!e)}var rn=document.getElementById("navCollapse"),no=null;function Xl(){return window.innerWidth<540?"full":no==="collapsed"?"rail":no==="expanded"?"full":window.innerWidth<=1024?"rail":"full"}function Xs(){let e=Xl();if(document.documentElement.dataset.nav=e,!rn)return;let t=e!=="rail",n=t?"Collapse sidebar":"Expand sidebar";rn.setAttribute("aria-expanded",t?"true":"false"),rn.setAttribute("aria-label",n),rn.setAttribute("title",n)}var eo=0,Ri=0;function Ai(){Ci?.addEventListener("click",()=>an(!document.body.classList.contains("nav-open"))),to?.addEventListener("click",()=>an(!1)),document.querySelector(".sidebar")?.addEventListener("click",e=>{e.target instanceof Element&&e.target.closest("a")&&an(!1)}),rn?.addEventListener("click",()=>{no=document.documentElement.dataset.nav!=="rail"?"collapsed":"expanded",Xs()}),window.addEventListener("resize",()=>{document.body.classList.add("nav-resizing"),clearTimeout(Ri),Ri=setTimeout(()=>{document.body.classList.remove("nav-resizing")},200),!eo&&(eo=requestAnimationFrame(()=>{eo=0,Xs()}))}),Xs()}var qn=null,jn=null,Wn="Kestrel";function se(e,t){e.aborted||(document.title=t.trim()?`${t} - ${Wn}`:Wn)}function ee(e){qn?.abort(),jn=null;let t=new AbortController;qn=t,document.title=Wn;let n=document.createElement("div");n.className="view",fe.replaceChildren(n);let s;try{s=Promise.resolve(e(n,t.signal))}catch(i){s=Promise.reject(i)}return s.then(i=>{!t.signal.aborted&&i&&(jn=i)},i=>{if(!t.signal.aborted)throw i})}function Ht(){qn?.abort(),qn=null,jn=null,document.title=Wn,fe.replaceChildren()}function Vn(){return jn}function mt(e,t,n){if(n.aborted)return;let s=setInterval(t,e);n.addEventListener("abort",()=>clearInterval(s),{once:!0})}function ft(e,t,n){if(n.aborted)return;let s=()=>clearTimeout(i),i=setTimeout(()=>{n.removeEventListener("abort",s),t()},Math.max(0,e-Date.now()));n.addEventListener("abort",s,{once:!0})}function Hi(e,t,n){let s=()=>{if(n.aborted)return;let i=()=>clearTimeout(a),a=setTimeout(async()=>{n.removeEventListener("abort",i);let r=!0;try{r=await t()??!0}catch(l){ec(l)||reportError(l)}r!==!1&&s()},e);n.addEventListener("abort",i,{once:!0})};s()}function Pt(e,t){if(e.aborted){t();return}e.addEventListener("abort",t,{once:!0})}function ec(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ApiError")}function c(e,t=document){let n=t.querySelector(e);if(!n)throw new Error(`no element matches ${e}`);return n}function I(e,t=document){return[...t.querySelectorAll(e)]}var tc={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function X(e){return String(e).replace(/[&<>"']/g,t=>tc[t]??t)}var ht=class{markup;constructor(t){this.markup=t,Object.freeze(this)}toString(){return this.markup}};function Mi(e){return e instanceof ht?e.markup:e==null||e===!1?"":Array.isArray(e)?e.map(Mi).join(""):X(e)}var nc=/=\s*$/;function o(e,...t){let n=Pi(e,0);for(let s=0;s<t.length;s++){let i=t[s];if(!(i instanceof ht)&&nc.test(n))throw new Error("html: an interpolation in an unquoted attribute value cannot be made safe; quote it");n+=Mi(i)+Pi(e,s+1)}return new ht(n)}function Pi(e,t){let n=e[t];if(n===void 0)throw new Error(`html: invalid escape sequence in template text near ${JSON.stringify(e.raw[t])}`);return n}function j(e){return new ht(e)}function h(e,t){if(!(t instanceof ht))throw new Error("setHtml: expected Html; build it with html`\u2026` or vouch for it with unsafeHtml()");e.innerHTML=t.markup}var sc="https://getkestrel.dev/docs/access/",oc="/cdn-cgi/access/logout";function Kn(e){if(fe.querySelector(".access-wall"))return;Ht(),document.body.classList.add("signed-out");let t=o`<p class="hint"><a href="${sc}" target="_blank" rel="noopener">Lock the dashboard with Access <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a></p>`;e==="access_unidentified"?(h(fe,o`<div class="card auth-wall access-wall" role="alert"><h2 tabindex="-1">Access let you in, but didn’t say who you are</h2><p>Cloudflare Access sent neither an email address nor a service token, and Kestrel needs one of them to tell who is asking, so it doesn’t let this sign-in in. Some other kind of Access policy, or a login method that gives no email, let it through.</p><p>Kestrel accepts two kinds of Access policy: an Allow policy on people’s emails, and a Service Auth policy on a service token. Sign out, then sign in through one of them.</p>${t}<button id="access-signout" class="primary">Sign out</button></div>`),c("#access-signout",fe).onclick=()=>location.assign(oc)):(h(fe,o`<div class="card auth-wall access-wall"><h2 tabindex="-1">The editor is locked until you set up Access</h2><p>Until Cloudflare Access is in front of the editor, the app can’t tell who is asking, so it lets no one in. On a new deployment, that’s expected. Your public pages work as usual.</p>${t}<button id="access-reload" class="primary">Reload</button></div>`),c("#access-reload",fe).onclick=()=>location.reload()),c(".access-wall h2",fe).focus()}var Ii="Kestrel-Client",ln="editor",Gn="claude-code",zn="claude";function Yn(e){if(!e||typeof e!="object")return null;let t=e;return t.error==="schema_behind"&&typeof t.message=="string"?{message:t.message}:t.error!=="invalid_config"||typeof t.variable!="string"?null:{variable:t.variable,message:typeof t.message=="string"?t.message:`${t.variable} is refused`}}var ic="https://getkestrel.dev/docs/configuration/",rc={PROVIDER:"vars",ALLOW_FAKE_PROVIDER:"vars",APP_ORIGIN:"vars",AWS_REGION:"vars",FROM_ADDRESS:"vars",SENDING_DOMAIN:"vars",ARCHIVE_BASE_PATH:"vars",SES_MAX_SEND_RATE:"vars",SUBREQUEST_BUDGET:"vars",MIN_LEAD_SECONDS:"vars",ARCHIVE_ORIGIN:"vars",MEDIA_PUBLIC_BASE:"vars",NOTIFY_FROM:"vars",ACCESS_TEAM_DOMAIN:"secrets",ACCESS_AUD:"secrets",ACCESS_ALLOWED_EMAILS:"secrets",AWS_ACCESS_KEY_ID:"secrets",AWS_SECRET_ACCESS_KEY:"secrets",SNS_TOPIC_ARN:"secrets",SES_CONFIGURATION_SET:"secrets",SIMULATE_SENDS:"what-the-app-refuses"},ac="what-the-app-refuses";function lc(e){return`${ic}#${rc[e]??ac}`}function Zn(e){if(fe.querySelector(".config-wall"))return;Ht(),document.body.classList.add("signed-out");let{variable:t}=e,n=t?"A setting needs fixing":"The database needs updating",s=t?o`<p class="hint"><a href="${lc(t)}" target="_blank" rel="noopener">${t} in the Configuration reference <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a></p>`:"";h(fe,o`<div class="card auth-wall config-wall" role="alert"><h2 tabindex="-1">${n}</h2><p>Kestrel won’t run until it’s fixed, and nothing is sent in the meantime.</p><p class="config-wall-problem">${e.message}</p>${s}<button id="config-reload" class="primary">Reload</button></div>`),c("#config-reload",fe).onclick=()=>location.reload(),c(".config-wall h2",fe).focus()}var Jn="kestrel_token",Q={token:localStorage.getItem(Jn)||"",session:null,appConfig:null};function Oi(e){Q.token=(e||"").trim();try{Q.token?localStorage.setItem(Jn,Q.token):localStorage.removeItem(Jn)}catch{}}function ro(){return{[Ii]:ln,...Q.token?{Authorization:`Bearer ${Q.token}`}:{}}}function Di(){let e=Q.session;if(e?.auth.mode==="access"){let t=e.principal,n=t.email||(t.kind==="service"?"Service token":"Signed in");h(oo,o`<span class="who" title="${n}">${n}</span><a class="ghost" href="/cdn-cgi/access/logout" title="Sign out"><svg class="signout-icon" aria-hidden="true"><use href="#i-signout"/></svg><span class="signout-label">Sign out</span></a>`)}else h(oo,o`<span class="who dev" title="Local dev: sign-in is skipped on localhost">Local dev</span>`)}function ao(){fe.querySelector(".reauth-wall")||(Ht(),document.body.classList.add("signed-out"),h(fe,o`<div class="card auth-wall reauth-wall"><h2 tabindex="-1">Session expired</h2><p class="hint">Your access session ended. Sign in again to continue.</p><button id="reauth" class="primary">Sign in</button></div>`),c("#reauth",fe).onclick=()=>location.reload(),c(".reauth-wall h2",fe).focus())}async function Ni(){try{let e=await fetch("/api/dev/token?kind=human");if(e.ok)return Oi((await e.json()).token),!0}catch{}return!1}async function Bi(){try{return await fetch("/api/whoami",{headers:ro(),redirect:"manual"})}catch{return null}}async function Ui(){Q.token||await Ni();let e=await Bi();if(!e?.ok&&Q.token&&(Oi(""),await Ni()&&(e=await Bi())),e?.ok)return await e.json();let t=e?await e.json().catch(()=>null):null,n=Yn(t),s=Fn(t);return n?Zn(n):s?Kn(s):ao(),null}var te=class extends Error{constructor(n,s,i=null){super(n);this.status=s;this.data=i;this.name="ApiError"}status;data;get code(){let n=this.data;return typeof n?.error=="string"?n.error:null}get field(){let n=this.data;return typeof n?.field=="string"?n.field:null}},cc="Not authorized. Sign in again.",dc=e=>/^[a-z_]+$/i.test(e.trim()),uc=/^(Failed to fetch|NetworkError when attempting to fetch resource\.?|Load failed|The network connection was lost\.?|The Internet connection appears to be offline\.?)$/;function lo(e){return e instanceof TypeError&&uc.test(e.message)}function F(e){if(e instanceof te){let t=e.data?.message;return typeof t=="string"&&!dc(t)?t:e.status===401?e.message:e.status===404?"It isn\u2019t there any more. It may have been deleted elsewhere.":e.status>=500?"Something went wrong on the server. Try again in a moment.":e.status===429?"Too many requests at once. Try again in a moment.":"The server couldn\u2019t do that. Reload the page and try again."}return lo(e)?"Couldn\u2019t reach Kestrel. Check your connection and try again.":e instanceof Error?e.message:String(e)}async function co(e,t){let n={...ro(),...t.headers??{}},s=t.body;t.json!==void 0&&(n["content-type"]="application/json",s=JSON.stringify(t.json));let i=await fetch(e,{method:t.method??"GET",headers:n,body:s,signal:t.signal});if(i.status===401){let a=await i.json().catch(()=>null),r=Fn(a);throw r?Kn(r):ao(),new te(cc,401,a)}return i}function pc(e){if(e&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}}async function uo(e){let t=await e.text(),n=null;try{n=t?JSON.parse(t):null}catch{}let s=Yn(n);s&&Zn(s);let i=e.statusText||`Request failed (HTTP ${e.status})`;return new te(pc(n)??i,e.status,n)}async function R(e,t={}){let n=await co(e,t);if(!n.ok)throw await uo(n);let s=await n.text();return s?JSON.parse(s):null}async function Mt(e,t={}){let n=await co(e,t);if(!n.ok)throw await uo(n);return n.text()}async function Qn(e,t={}){let n=await co(e,t);if(!n.ok)throw await uo(n);let s=n.headers.get("content-disposition")??"",i=/filename="([^"]+)"/.exec(s)?.[1]??null;return{text:await n.text(),filename:i}}function po(e){let t=e.trim(),n=t.lastIndexOf("<");if(n<0||!t.endsWith(">"))return"";let s=t.slice(0,n).trim();return s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1).replace(/\\(.)/g,"$1").trim():s}function cn(e,t){return e||po(t)}function mo(e){let t=e?.settings.publication;return{name:cn(t?.name||"",e?.deployment.from_address??"")||"Your publication",tagline:t?.tagline||"",logoUrl:t?.logo_url||null}}function Xn(){let e=mo(Q.appConfig),t=document.getElementById("brandName"),n=document.getElementById("brandTagline"),s=document.getElementById("brandLogo");t&&(t.textContent=e.name),n&&(n.textContent=e.tagline,n.hidden=!e.tagline),s&&(e.logoUrl?(h(s,o`<img src="${e.logoUrl}" alt="">`),s.classList.remove("brand-logo-placeholder")):(s.textContent=(e.name.trim()[0]||"K").toUpperCase(),s.classList.add("brand-logo-placeholder")))}function Fi(e,t,n){return`${e}${t}/${n}`}var mc=["content","invalid_request"];function fo(e){return e!==null&&mc.includes(e)}var ho={step:"Connect Amazon SES",guide:" (the setup guide walks through it)",after:", then deploy."};var qm=1800*1e3,es=300*1e3,jm=60*1e3,Wm=1440*60*1e3;function It(e){let t=Math.round(e/1e3);if(t%60===0){let n=t/60;return`${n} minute${n===1?"":"s"}`}return`${t} seconds`}function qi(e){return`Pick a time at least ${It(e)} from now, so there\u2019s time to cancel.`}var Vm=10080*60*1e3,Km=3600*1e3;function ji(){let e=Q.appConfig?.deployment.build;if(!e?.version)return null;let t=e.tag_url?o`<a class="build-link" href="${e.tag_url}" target="_blank" rel="noopener">v${e.version}</a>`:o`v${e.version}`,n=e.commit_url?o`<a class="build-link" href="${e.commit_url}" target="_blank" rel="noopener">${e.sha}</a>`:o`${e.sha}`;return{version:t,sha:n}}function ts(){return Q.appConfig?.deployment.min_lead_ms??es}function ns(){return qi(ts())}function Wi(){let e=ts();if(e%6e4===0){let t=e/6e4;return`${t} to ${t+1} minutes`}return`${It(e)} to ${It(e+6e4)}`}function ss(e,t=Date.now()){return e<t+ts()}function os(e=Date.now()){return new Date(e+ts()+6e4)}function dn(){return Q.appConfig?.deployment.provider==="fake"}function ve(){return Q.appConfig?.deployment.provider==="none"}function fc(){return Q.appConfig?.deployment.free_plan_limits===!0}function hc(){return ve()&&Q.appConfig?.deployment.not_connected_preview===!0}var bo="#/docs/ses";function Ae(e){let t=e?o` class="${e}"`:null;return o`<a${t} href="${bo}">${ho.step}</a>`}function go(){return hc()?o`Restart <code>npm run dev</code> without <code>SIMULATE_SENDS=not-connected</code> to send.`:o`${Ae()}${ho.after}`}function is(e,t){let n=t===1;return o`No email provider connected, so nothing can be sent and ${e} ${n?"is":"are"} held, with no one marked unsent; ${n?"it goes out at its":"they go out at their"} first retry once one is connected. ${go()}`}function rs(e,t){return ve()?o`<div class="health amber ${e}" role="status"><span class="health-dot">⚠️</span><div><span>${t}</span></div></div>`:null}function as(e){if(!ve())return null;let t="Will be held: no email provider is connected.";return e==="card"?o`<div class="sched-held">${t}</div>`:o`<div class="sched-note sched-note-held"><span class="sched-note-mark" aria-hidden="true">⚠️</span><span class="sched-note-msg">${t}</span></div>`}function ls(e,t){return ve()?o`<p class="hint not-connected">No email provider connected, so ${e}. ${Ae()}${t}.</p>`:null}function cs(){return ls("a test can\u2019t be sent yet"," to send one")}function Vi(){return ls("a confirmation can\u2019t be sent yet"," to add subscribers")}function vo(){return fc()&&!ve()?o`<p class="hint daily-writes" id="schDailyWrites" role="status" hidden></p>`:null}function Ki(){return ls("this can\u2019t be scheduled yet"," to schedule it")}function Gi(){return ls("this send is held when it fires, until one is"," to send it")}function Nt(e){return dn()?`${e} (local stand-in: nothing is delivered)`:e}function zi(e){let t=Q.appConfig?.deployment;return t?Fi(t.archive_origin,t.archive_base_path,e):null}var Yi=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M280-280h280v-80H280v80Zm0-160h400v-80H280v80Zm0-160h400v-80H280v80Zm-80 480q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm0-560v560-560Z"/></svg>
3
- `;var Zi=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M272-200v-560h221q65 0 120 40t55 111q0 51-23 78.5T602-491q25 11 55.5 41t30.5 90q0 89-65 124.5T501-200H272Zm121-112h104q48 0 58.5-24.5T566-372q0-11-10.5-35.5T494-432H393v120Zm0-228h93q33 0 48-17t15-38q0-24-17-39t-44-15h-95v109Z"/></svg>
4
- `;var Ji=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"/><path d="M4 21V5"/><path d="M9 8h6"/></svg>
5
- `;var Qi=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3v8a4 4 0 0 0 4 4h8"/><path d="m14 11 4 4-4 4"/></svg>
6
- `;var Xi=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
7
- `;var er=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/></svg>
8
- `;var tr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8 12h8"/></svg>
9
- `;var nr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>
10
- `;var sr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></svg>
11
- `;var or=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8"/><path d="M12 16v4"/></svg>
12
- `;var ir=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>
13
- `;var rr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M360-280v-400h80v160h160v-160h80v400h-80v-160H440v160h-80Z"/></svg>
14
- `;var ar=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M120-120v-80h720v80H120Zm320-160v-80h400v80H440Zm0-160v-80h400v80H440Zm0-160v-80h400v80H440ZM120-760v-80h720v80H120Zm0 440v-320l160 160-160 160Z"/></svg>
15
- `;var lr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>
16
- `;var cr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M440-280h80v-240h-80v240Zm68.5-331.5Q520-623 520-640t-11.5-28.5Q497-680 480-680t-28.5 11.5Q440-657 440-640t11.5 28.5Q463-600 480-600t28.5-11.5ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>
17
- `;var dr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M200-200v-100h160l120-360H320v-100h400v100H580L460-300h140v100H200Z"/></svg>
18
- `;var ur=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 360" aria-hidden="true"><path d="M290.028 216.064C285.698 218.264 280.838 219.394 275.978 219.344C281.268 225.044 284.128 232.924 283.708 240.694C283.278 248.844 279.388 256.514 274.268 262.874C269.148 269.244 262.808 274.494 256.608 279.814C237.148 296.474 218.248 314.404 195.328 325.854C178.568 334.224 160.148 338.864 143.458 347.374C140.148 349.064 136.898 350.904 133.418 352.224C129.938 353.544 126.178 354.324 122.498 353.794C121.718 353.684 120.938 353.504 120.228 353.184C119.508 352.864 118.848 352.374 118.408 351.734C117.918 351.024 117.708 350.154 117.718 349.304C117.728 348.454 117.948 347.614 118.268 346.824C118.567 346.054 118.967 345.339 119.371 344.618L119.418 344.534C128.788 327.894 140.118 312.454 150.358 296.344C160.598 280.224 169.848 263.174 174.428 244.634C176.258 237.264 177.328 229.644 176.738 222.074C176.138 214.504 173.808 206.964 169.308 200.854C164.588 194.434 157.728 189.874 150.538 186.434C139.628 181.204 127.768 178.284 115.858 176.154C93.9183 172.224 71.6083 170.884 49.4083 168.944C45.8483 168.634 42.2483 168.294 38.8783 167.124C34.7683 165.704 31.0683 163.004 28.7383 159.334C26.4183 155.664 25.5583 151.024 26.7483 146.844C27.6583 143.624 29.7283 140.784 32.3583 138.724C34.9883 136.654 38.1683 135.324 41.4383 134.634C44.7183 133.944 48.0983 133.874 51.4383 134.154C53.2683 134.304 55.0883 134.554 56.8983 134.824C72.2383 137.094 87.3783 140.484 102.548 143.644C115.468 146.334 128.498 148.864 141.688 149.224C154.878 149.574 168.338 147.654 180.178 141.824C196.548 133.764 208.758 118.514 215.298 101.474C224.258 78.094 223.028 52.174 220.398 27.284C219.788 21.484 219.108 15.614 220.058 9.854C220.178 9.124 220.328 8.38398 220.658 7.71398C220.988 7.05398 221.528 6.45399 222.228 6.19399C222.858 5.95399 223.568 6.01399 224.218 6.22399C224.858 6.43399 225.448 6.77399 226.028 7.12399C262.588 29.154 290.508 63.614 310.198 101.484C312.188 105.314 314.108 109.204 315.408 113.314C316.708 117.434 317.358 121.814 316.768 126.084C316.348 129.114 315.268 132.104 313.318 134.454C310.668 137.634 306.688 139.354 302.778 140.744C298.878 142.124 294.808 143.324 291.488 145.804C286.998 149.174 284.328 154.834 284.598 160.444C292.098 161.904 299.448 164.114 306.508 167.014C312.788 169.594 318.998 172.854 323.418 178.014C327.088 182.294 329.288 187.614 331.438 192.844C332.158 194.584 332.878 196.344 333.328 198.184C333.778 200.014 333.958 201.944 333.578 203.794C333.138 205.934 331.948 207.914 330.248 209.294C329.898 208.024 329.258 206.834 328.408 205.834C326.958 204.154 324.928 203.054 322.798 202.454C318.258 201.174 313.328 202.114 309.018 204.044C304.708 205.974 300.898 208.834 297.068 211.584C294.808 213.204 292.508 214.804 290.028 216.064Z"/></svg>
19
- `;var pr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 6h11M9 12h11M9 18h11M4 6h1M4 12h1M4 18h1"/></svg>
20
- `;var mr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M440-280H280q-83 0-141.5-58.5T80-480q0-83 58.5-141.5T280-680h160v80H280q-50 0-85 35t-35 85q0 50 35 85t85 35h160v80ZM320-440v-80h320v80H320Zm200 160v-80h160q50 0 85-35t35-85q0-50-35-85t-85-35H520v-80h160q83 0 141.5 58.5T880-480q0 83-58.5 141.5T680-280H520Z"/></svg>
21
- `;var fr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
22
- `;var hr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M120-80v-60h100v-30h-60v-60h60v-30H120v-60h120q17 0 28.5 11.5T280-280v40q0 17-11.5 28.5T240-200q17 0 28.5 11.5T280-160v40q0 17-11.5 28.5T240-80H120Zm0-280v-110q0-17 11.5-28.5T160-510h60v-30H120v-60h120q17 0 28.5 11.5T280-560v70q0 17-11.5 28.5T240-450h-60v30h100v60H120Zm60-280v-180h-60v-60h120v240h-60Zm180 440v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360Z"/></svg>
23
- `;var br=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M720-330q0 104-73 177T470-80q-104 0-177-73t-73-177v-370q0-75 52.5-127.5T400-880q75 0 127.5 52.5T580-700v350q0 46-32 78t-78 32q-46 0-78-32t-32-78v-370h80v370q0 13 8.5 21.5T470-320q13 0 21.5-8.5T500-350v-350q-1-42-29.5-71T400-800q-42 0-71 29t-29 71v370q-1 71 49 120.5T470-160q70 0 119-49.5T640-330v-390h80v390Z"/></svg>
24
- `;var gr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2" width="10" height="20" rx="2"/><path d="M11 18h2"/></svg>
25
- `;var vr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
26
- `;var yr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
27
- `;var wr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="m228-240 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T458-480L320-240h-92Zm360 0 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T818-480L680-240h-92ZM362.5-517.5Q380-535 380-560t-17.5-42.5Q345-620 320-620t-42.5 17.5Q260-585 260-560t17.5 42.5Q295-500 320-500t42.5-17.5Zm360 0Q740-535 740-560t-17.5-42.5Q705-620 680-620t-42.5 17.5Q620-585 620-560t17.5 42.5Q655-500 680-500t42.5-17.5ZM680-560Zm-360 0Z"/></svg>
28
- `;var Sr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
29
- `;var $r=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2"/></svg>
30
- `;var Er=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 3 11 14M22 3l-7 18-4-7-7-4 18-7z"/></svg>
31
- `;var xr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="m370-80-16-128q-13-5-24.5-12T307-235l-119 50L78-375l103-78q-1-7-1-13.5v-27q0-6.5 1-13.5L78-585l110-190 119 50q11-8 23-15t24-12l16-128h220l16 128q13 5 24.5 12t22.5 15l119-50 110 190-103 78q1 7 1 13.5v27q0 6.5-2 13.5l103 78-110 190-118-50q-11 8-23 15t-24 12L590-80H370Zm70-80h79l14-106q31-8 57.5-23.5T639-327l99 41 39-68-86-65q5-14 7-29.5t2-31.5q0-16-2-31.5t-7-29.5l86-65-39-68-99 42q-22-23-48.5-38.5T533-694l-13-106h-79l-14 106q-31 8-57.5 23.5T321-633l-99-41-39 68 86 64q-5 15-7 30t-2 32q0 16 2 31t7 30l-86 65 39 68 99-42q22 23 48.5 38.5T427-266l13 106Zm42-180q58 0 99-41t41-99q0-58-41-99t-99-41q-59 0-99.5 41T342-480q0 58 40.5 99t99.5 41Zm-2-140Z"/></svg>
32
- `;var kr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M360-200v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360ZM200-160q-33 0-56.5-23.5T120-240q0-33 23.5-56.5T200-320q33 0 56.5 23.5T280-240q0 33-23.5 56.5T200-160Zm0-240q-33 0-56.5-23.5T120-480q0-33 23.5-56.5T200-560q33 0 56.5 23.5T280-480q0 33-23.5 56.5T200-400Zm-56.5-263.5Q120-687 120-720t23.5-56.5Q167-800 200-800t56.5 23.5Q280-753 280-720t-23.5 56.5Q233-640 200-640t-56.5-23.5Z"/></svg>
33
- `;var _r=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4M8 8l4-4 4 4"/><path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/></svg>
34
- `;var Tr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>
35
- `;var Yc={article:j(Yi),bold:j(Zi),check:j(Xi),code:j(nr),copyout:j(sr),editable:j(ir),heading:j(rr),indent:j(ar),info:j(lr),"info-filled":j(cr),italic:j(dr),kestrel:j(ur),lines:j(pr),link:j(mr),ol:j(hr),paperclip:j(br),plus:j(vr),preview:j(yr),quote:j(wr),readonly:j(Sr),search:j($r),send:j(Er),settings:j(xr),ul:j(kr),upload:j(_r),book:j(Ji),branch:j(Qi),"circle-check":j(er),"circle-minus":j(tr),desktop:j(or),mail:j(fr),phone:j(gr),x:j(Tr)};function N(e){return Yc[e]}function Bt(e,t,n){let s=(S,b)=>e===S?o`<a href="#/${S}" data-room="${S}" data-text="${b}" aria-current="page">${b}</a>`:o`<a href="#/${S}" data-room="${S}" data-text="${b}">${b}</a>`,i=ji(),a=Q.appConfig?.deployment.build.build_time,r=a?`Built ${new Date(a).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}`:null,l=i?o`${i.version} <span aria-hidden="true">·</span> ${i.sha}`:null,d=l?r?o`<div class="rail-foot" title="${r}">${l}</div>`:o`<div class="rail-foot">${l}</div>`:null,u=l?r?o`<footer class="room-foot" title="${r}">${l}</footer>`:o`<footer class="room-foot">${l}</footer>`:null,f=t==null?o`<div class="room-body norail"><div class="room-main">${n}</div></div>`:o`<div class="room-body"><nav class="room-rail" aria-label="Contents"><div class="rail-inner">${t}${d}</div></nav><div class="room-main">${n}</div></div>`;return o`<div class="room">
2
+ "use strict";(()=>{function Zn(e){if(!e||typeof e!="object")return null;let t=e;return t.error!=="unauthorized"?null:t.reason==="access_not_configured"||t.reason==="access_unidentified"?t.reason:null}function vo(e){let t=document.getElementById(e);if(!t)throw new Error(`the admin page has no #${e}`);return t}var pe=vo("app"),yo=vo("identity"),wo=vo("toasts"),Yi=document.getElementById("navToggle"),bo=document.getElementById("navScrim");function dn(e){document.body.classList.toggle("nav-open",e),Yi?.setAttribute("aria-expanded",e?"true":"false"),bo&&(bo.hidden=!e)}var cn=document.getElementById("navCollapse"),go=null;function Dc(){return window.innerWidth<540?"full":go==="collapsed"?"rail":go==="expanded"?"full":window.innerWidth<=1024?"rail":"full"}function fo(){let e=Dc();if(document.documentElement.dataset.nav=e,!cn)return;let t=e!=="rail",n=t?"Collapse sidebar":"Expand sidebar";cn.setAttribute("aria-expanded",t?"true":"false"),cn.setAttribute("aria-label",n),cn.setAttribute("title",n)}var ho=0,zi=0;function Zi(){Yi?.addEventListener("click",()=>dn(!document.body.classList.contains("nav-open"))),bo?.addEventListener("click",()=>dn(!1)),document.querySelector(".sidebar")?.addEventListener("click",e=>{e.target instanceof Element&&e.target.closest("a")&&dn(!1)}),cn?.addEventListener("click",()=>{go=document.documentElement.dataset.nav!=="rail"?"collapsed":"expanded",fo()}),window.addEventListener("resize",()=>{document.body.classList.add("nav-resizing"),clearTimeout(zi),zi=setTimeout(()=>{document.body.classList.remove("nav-resizing")},200),!ho&&(ho=requestAnimationFrame(()=>{ho=0,fo()}))}),fo()}var Jn=null,Qn=null,Xn="Kestrel";function ie(e,t){e.aborted||(document.title=t.trim()?`${t} - ${Xn}`:Xn)}function ee(e){Jn?.abort(),Qn=null;let t=new AbortController;Jn=t,document.title=Xn;let n=document.createElement("div");n.className="view",pe.replaceChildren(n);let s;try{s=Promise.resolve(e(n,t.signal))}catch(i){s=Promise.reject(i)}return s.then(i=>{!t.signal.aborted&&i&&(Qn=i)},i=>{if(!t.signal.aborted)throw i})}function It(){Jn?.abort(),Jn=null,Qn=null,document.title=Xn,pe.replaceChildren()}function es(){return Qn}function bt(e,t,n){if(n.aborted)return;let s=setInterval(t,e);n.addEventListener("abort",()=>clearInterval(s),{once:!0})}function gt(e,t,n){if(n.aborted)return;let s=()=>clearTimeout(i),i=setTimeout(()=>{n.removeEventListener("abort",s),t()},Math.max(0,e-Date.now()));n.addEventListener("abort",s,{once:!0})}function Ji(e,t,n){let s=()=>{if(n.aborted)return;let i=()=>clearTimeout(r),r=setTimeout(async()=>{n.removeEventListener("abort",i);let a=!0;try{a=await t()??!0}catch(l){Bc(l)||reportError(l)}a!==!1&&s()},e);n.addEventListener("abort",i,{once:!0})};s()}function Nt(e,t){if(e.aborted){t();return}e.addEventListener("abort",t,{once:!0})}function Bc(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ApiError")}function c(e,t=document){let n=t.querySelector(e);if(!n)throw new Error(`no element matches ${e}`);return n}function N(e,t=document){return[...t.querySelectorAll(e)]}var Uc={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function X(e){return String(e).replace(/[&<>"']/g,t=>Uc[t]??t)}var vt=class{markup;constructor(t){this.markup=t,Object.freeze(this)}toString(){return this.markup}};function Xi(e){return e instanceof vt?e.markup:e==null||e===!1?"":Array.isArray(e)?e.map(Xi).join(""):X(e)}var Fc=/=\s*$/;function o(e,...t){let n=Qi(e,0);for(let s=0;s<t.length;s++){let i=t[s];if(!(i instanceof vt)&&Fc.test(n))throw new Error("html: an interpolation in an unquoted attribute value cannot be made safe; quote it");n+=Xi(i)+Qi(e,s+1)}return new vt(n)}function Qi(e,t){let n=e[t];if(n===void 0)throw new Error(`html: invalid escape sequence in template text near ${JSON.stringify(e.raw[t])}`);return n}function z(e){return new vt(e)}function h(e,t){if(!(t instanceof vt))throw new Error("setHtml: expected Html; build it with html`\u2026` or vouch for it with unsafeHtml()");e.innerHTML=t.markup}var qc="https://getkestrel.dev/docs/access/",jc="/cdn-cgi/access/logout";function ts(e){if(pe.querySelector(".access-wall"))return;It(),document.body.classList.add("signed-out");let t=o`<p class="hint"><a href="${qc}" target="_blank" rel="noopener">Lock the dashboard with Access <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a></p>`;e==="access_unidentified"?(h(pe,o`<div class="card auth-wall access-wall" role="alert"><h2 tabindex="-1">Access let you in, but didn’t say who you are</h2><p>Cloudflare Access sent neither an email address nor a service token, and Kestrel needs one of them to tell who is asking, so it doesn’t let this sign-in in. Some other kind of Access policy, or a login method that gives no email, let it through.</p><p>Kestrel accepts two kinds of Access policy: an Allow policy on people’s emails, and a Service Auth policy on a service token. Sign out, then sign in through one of them.</p>${t}<button id="access-signout" class="primary">Sign out</button></div>`),c("#access-signout",pe).onclick=()=>location.assign(jc)):(h(pe,o`<div class="card auth-wall access-wall"><h2 tabindex="-1">The editor is locked until you set up Access</h2><p>Until Cloudflare Access is in front of the editor, the app can’t tell who is asking, so it lets no one in. On a new deployment, that’s expected. Your public pages work as usual.</p>${t}<button id="access-reload" class="primary">Reload</button></div>`),c("#access-reload",pe).onclick=()=>location.reload()),c(".access-wall h2",pe).focus()}var er="Kestrel-Client",un="editor",ns="claude-code",ss="claude";function os(e){if(!e||typeof e!="object")return null;let t=e;return t.error==="schema_behind"&&typeof t.message=="string"?{message:t.message}:t.error!=="invalid_config"||typeof t.variable!="string"?null:{variable:t.variable,message:typeof t.message=="string"?t.message:`${t.variable} is refused`}}var Wc="https://getkestrel.dev/docs/configuration/",Vc={PROVIDER:"vars",ALLOW_FAKE_PROVIDER:"vars",APP_ORIGIN:"vars",AWS_REGION:"vars",FROM_ADDRESS:"vars",SENDING_DOMAIN:"vars",ARCHIVE_BASE_PATH:"vars",SES_MAX_SEND_RATE:"vars",SUBREQUEST_BUDGET:"vars",MIN_LEAD_SECONDS:"vars",ARCHIVE_ORIGIN:"vars",MEDIA_PUBLIC_BASE:"vars",NOTIFY_FROM:"vars",ACCESS_TEAM_DOMAIN:"secrets",ACCESS_AUD:"secrets",ACCESS_ALLOWED_EMAILS:"secrets",AWS_ACCESS_KEY_ID:"secrets",AWS_SECRET_ACCESS_KEY:"secrets",SNS_TOPIC_ARN:"secrets",SES_CONFIGURATION_SET:"secrets",SIMULATE_SENDS:"what-the-app-refuses"},Kc="what-the-app-refuses";function Gc(e){return`${Wc}#${Vc[e]??Kc}`}function is(e){if(pe.querySelector(".config-wall"))return;It(),document.body.classList.add("signed-out");let{variable:t}=e,n=t?"A setting needs fixing":"The database needs updating",s=t?o`<p class="hint"><a href="${Gc(t)}" target="_blank" rel="noopener">${t} in the Configuration reference <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a></p>`:"";h(pe,o`<div class="card auth-wall config-wall" role="alert"><h2 tabindex="-1">${n}</h2><p>Kestrel won’t run until it’s fixed, and nothing is sent in the meantime.</p><p class="config-wall-problem">${e.message}</p>${s}<button id="config-reload" class="primary">Reload</button></div>`),c("#config-reload",pe).onclick=()=>location.reload(),c(".config-wall h2",pe).focus()}var rs="kestrel_token",Y={token:localStorage.getItem(rs)||"",session:null,appConfig:null};function sr(e){Y.token=(e||"").trim();try{Y.token?localStorage.setItem(rs,Y.token):localStorage.removeItem(rs)}catch{}}function So(){return{[er]:un,...Y.token?{Authorization:`Bearer ${Y.token}`}:{}}}function or(){let e=Y.session;if(e?.auth.mode==="access"){let t=e.principal,n=t.email||(t.kind==="service"?"Service token":"Signed in");h(yo,o`<span class="who" title="${n}">${n}</span><a class="ghost" href="/cdn-cgi/access/logout" title="Sign out"><svg class="signout-icon" aria-hidden="true"><use href="#i-signout"/></svg><span class="signout-label">Sign out</span></a>`)}else h(yo,o`<span class="who dev" title="Local dev: sign-in is skipped on localhost">Local dev</span>`)}function pn(){pe.querySelector(".reauth-wall")||(It(),document.body.classList.add("signed-out"),h(pe,o`<div class="card auth-wall reauth-wall"><h2 tabindex="-1">Session expired</h2><p class="hint">Your access session ended. Sign in again to continue.</p><button id="reauth" class="primary">Sign in</button></div>`),c("#reauth",pe).onclick=()=>location.reload(),c(".reauth-wall h2",pe).focus())}async function tr(){try{let e=await fetch("/api/dev/token?kind=human");if(e.ok)return sr((await e.json()).token),!0}catch{}return!1}async function nr(){try{return await fetch("/api/whoami",{headers:So(),redirect:"manual"})}catch{return null}}function zc(e){let t=e;return typeof t?.principal=="object"&&t.principal!==null&&typeof t.auth=="object"}async function ir(){Y.token||await tr();let e=await nr();!e?.ok&&Y.token&&(sr(""),await tr()&&(e=await nr()));let t=e?await e.json().catch(()=>null):null;if(e?.ok&&zc(t))return t;let n=os(t),s=Zn(t);return n?is(n):s?ts(s):pn(),null}var te=class extends Error{constructor(n,s,i=null){super(n);this.status=s;this.data=i;this.name="ApiError"}status;data;get code(){let n=this.data;return typeof n?.error=="string"?n.error:null}get field(){let n=this.data;return typeof n?.field=="string"?n.field:null}},Yc="Not authorized. Sign in again.",Zc=e=>/^[a-z_]+$/i.test(e.trim()),Jc=/^(Failed to fetch|NetworkError when attempting to fetch resource\.?|Load failed|The network connection was lost\.?|The Internet connection appears to be offline\.?)$/;function $o(e){return e instanceof TypeError&&Jc.test(e.message)}function V(e){if(e instanceof te){let t=e.data?.message;return typeof t=="string"&&!Zc(t)?t:e.status===401?e.message:e.status===404?"It isn\u2019t there any more. It may have been deleted elsewhere.":e.status>=500?"Something went wrong on the server. Try again in a moment.":e.status===429?"Too many requests at once. Try again in a moment.":"The server couldn\u2019t do that. Reload the page and try again."}return $o(e)?"Couldn\u2019t reach Kestrel. Check your connection and try again.":e instanceof Error?e.message:String(e)}async function xo(e,t){let n={...So(),...t.headers??{}},s=t.body;t.json!==void 0&&(n["content-type"]="application/json",s=JSON.stringify(t.json));let i=await fetch(e,{method:t.method??"GET",headers:n,body:s,signal:t.signal});if(i.status===401){let r=await i.json().catch(()=>null),a=Zn(r);throw a?ts(a):pn(),new te(Yc,401,r)}return i}function Qc(e){if(e&&typeof e=="object"){let t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error}}async function Eo(e){let t=await e.text(),n=null;try{n=t?JSON.parse(t):null}catch{}let s=os(n);s&&is(s);let i=e.statusText||`Request failed (HTTP ${e.status})`;return new te(Qc(n)??i,e.status,n)}async function L(e,t={}){let n=await xo(e,t);if(!n.ok)throw await Eo(n);let s=await n.text();return s?JSON.parse(s):null}async function Ot(e,t={}){let n=await xo(e,t);if(!n.ok)throw await Eo(n);return n.text()}async function as(e,t={}){let n=await xo(e,t);if(!n.ok)throw await Eo(n);let s=n.headers.get("content-disposition")??"",i=/filename="([^"]+)"/.exec(s)?.[1]??null;return{text:await n.text(),filename:i}}function ko(e){let t=e.trim(),n=t.lastIndexOf("<");if(n<0||!t.endsWith(">"))return"";let s=t.slice(0,n).trim();return s.length>=2&&s.startsWith('"')&&s.endsWith('"')?s.slice(1,-1).replace(/\\(.)/g,"$1").trim():s}function mn(e,t){return e||ko(t)}function _o(e){let t=e?.settings.publication;return{name:mn(t?.name||"",e?.deployment.from_address??"")||"Your publication",tagline:t?.tagline||"",logoUrl:t?.logo_url||null}}function ls(){let e=_o(Y.appConfig),t=document.getElementById("brandName"),n=document.getElementById("brandTagline"),s=document.getElementById("brandLogo");t&&(t.textContent=e.name),n&&(n.textContent=e.tagline,n.hidden=!e.tagline),s&&(e.logoUrl?(h(s,o`<img src="${e.logoUrl}" alt="">`),s.classList.remove("brand-logo-placeholder")):(s.textContent=(e.name.trim()[0]||"K").toUpperCase(),s.classList.add("brand-logo-placeholder")))}function rr(e,t,n){return`${e}${t}/${n}`}var Xc=["content","invalid_request"];function To(e){return e!==null&&Xc.includes(e)}var Lo={step:"Connect Amazon SES",guide:" (the setup guide walks through it)",after:", then deploy."};var ar="Amazon SES is still in the sandbox, so when this send fires it reaches only addresses verified in SES. It waits for the rest, and other sends wait behind it, until AWS grants production access, then finishes on its own.";var Nf=1800*1e3,cs=300*1e3,Of=60*1e3,Df=1440*60*1e3;function Dt(e){let t=Math.round(e/1e3);if(t%60===0){let n=t/60;return`${n} minute${n===1?"":"s"}`}return`${t} seconds`}function lr(e){return`Pick a time at least ${Dt(e)} from now, so there\u2019s time to cancel.`}var Bf=10080*60*1e3,Uf=3600*1e3;function cr(){let e=Y.appConfig?.deployment.build;if(!e?.version)return null;let t=e.tag_url?o`<a class="build-link" href="${e.tag_url}" target="_blank" rel="noopener">v${e.version}</a>`:o`v${e.version}`,n=e.commit_url?o`<a class="build-link" href="${e.commit_url}" target="_blank" rel="noopener">${e.sha}</a>`:o`${e.sha}`;return{version:t,sha:n}}function ds(){return Y.appConfig?.deployment.min_lead_ms??cs}function us(){return lr(ds())}function dr(){let e=ds();if(e%6e4===0){let t=e/6e4;return`${t} to ${t+1} minutes`}return`${Dt(e)} to ${Dt(e+6e4)}`}function ps(e,t=Date.now()){return e<t+ds()}function ms(e=Date.now()){return new Date(e+ds()+6e4)}function fn(){return Y.appConfig?.deployment.provider==="fake"}function ge(){return Y.appConfig?.deployment.provider==="none"}function ed(){return Y.appConfig?.deployment.free_plan_limits===!0}function td(){return ge()&&Y.appConfig?.deployment.not_connected_preview===!0}var Ro="#/docs/ses";function Ae(e){let t=e?o` class="${e}"`:null;return o`<a${t} href="${Ro}">${Lo.step}</a>`}function Co(){return td()?o`Restart <code>npm run dev</code> without <code>SIMULATE_SENDS=not-connected</code> to send.`:o`${Ae()}${Lo.after}`}function fs(e,t){let n=t===1;return o`No email provider connected, so nothing can be sent and ${e} ${n?"is":"are"} held, with no one marked unsent; ${n?"it goes out at its":"they go out at their"} first retry once one is connected. ${Co()}`}function hs(e,t){return ge()?o`<div class="health amber ${e}" role="status"><span class="health-dot">⚠️</span><div><span>${t}</span></div></div>`:null}function bs(e){if(!ge())return null;let t="Will be held: no email provider is connected.";return e==="card"?o`<div class="sched-held">${t}</div>`:o`<div class="sched-note sched-note-held"><span class="sched-note-mark" aria-hidden="true">⚠️</span><span class="sched-note-msg">${t}</span></div>`}function gs(e,t){return ge()?o`<p class="hint not-connected">No email provider connected, so ${e}. ${Ae()}${t}.</p>`:null}function vs(){return gs("a test can\u2019t be sent yet"," to send one")}function ur(){return gs("a confirmation can\u2019t be sent yet"," to add subscribers")}function Ao(){return ed()&&!ge()?o`<p class="hint daily-writes" id="schDailyWrites" role="status" hidden></p>`:null}function Ho(){return ge()?null:o`<p class="hint daily-writes" id="schSandbox" role="status" hidden></p>`}function pr(){return gs("this can\u2019t be scheduled yet"," to schedule it")}function mr(){return gs("this send is held when it fires, until one is"," to send it")}function Bt(e){return fn()?`${e} (local stand-in: nothing is delivered)`:e}function fr(e){let t=Y.appConfig?.deployment;return t?rr(t.archive_origin,t.archive_base_path,e):null}var hr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M280-280h280v-80H280v80Zm0-160h400v-80H280v80Zm0-160h400v-80H280v80Zm-80 480q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm0-560v560-560Z"/></svg>
3
+ `;var br=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M272-200v-560h221q65 0 120 40t55 111q0 51-23 78.5T602-491q25 11 55.5 41t30.5 90q0 89-65 124.5T501-200H272Zm121-112h104q48 0 58.5-24.5T566-372q0-11-10.5-35.5T494-432H393v120Zm0-228h93q33 0 48-17t15-38q0-24-17-39t-44-15h-95v109Z"/></svg>
4
+ `;var gr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"/><path d="M4 21V5"/><path d="M9 8h6"/></svg>
5
+ `;var vr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3v8a4 4 0 0 0 4 4h8"/><path d="m14 11 4 4-4 4"/></svg>
6
+ `;var yr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
7
+ `;var wr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/></svg>
8
+ `;var Sr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M8 12h8"/></svg>
9
+ `;var $r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>
10
+ `;var xr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/></svg>
11
+ `;var Er=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8"/><path d="M12 16v4"/></svg>
12
+ `;var kr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>
13
+ `;var _r=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M360-280v-400h80v160h160v-160h80v400h-80v-160H440v160h-80Z"/></svg>
14
+ `;var Tr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M120-120v-80h720v80H120Zm320-160v-80h400v80H440Zm0-160v-80h400v80H440Zm0-160v-80h400v80H440ZM120-760v-80h720v80H120Zm0 440v-320l160 160-160 160Z"/></svg>
15
+ `;var Lr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 16v-4M12 8h.01"/></svg>
16
+ `;var Rr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M440-280h80v-240h-80v240Zm68.5-331.5Q520-623 520-640t-11.5-28.5Q497-680 480-680t-28.5 11.5Q440-657 440-640t11.5 28.5Q463-600 480-600t28.5-11.5ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>
17
+ `;var Cr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M200-200v-100h160l120-360H320v-100h400v100H580L460-300h140v100H200Z"/></svg>
18
+ `;var Ar=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 360" aria-hidden="true"><path d="M290.028 216.064C285.698 218.264 280.838 219.394 275.978 219.344C281.268 225.044 284.128 232.924 283.708 240.694C283.278 248.844 279.388 256.514 274.268 262.874C269.148 269.244 262.808 274.494 256.608 279.814C237.148 296.474 218.248 314.404 195.328 325.854C178.568 334.224 160.148 338.864 143.458 347.374C140.148 349.064 136.898 350.904 133.418 352.224C129.938 353.544 126.178 354.324 122.498 353.794C121.718 353.684 120.938 353.504 120.228 353.184C119.508 352.864 118.848 352.374 118.408 351.734C117.918 351.024 117.708 350.154 117.718 349.304C117.728 348.454 117.948 347.614 118.268 346.824C118.567 346.054 118.967 345.339 119.371 344.618L119.418 344.534C128.788 327.894 140.118 312.454 150.358 296.344C160.598 280.224 169.848 263.174 174.428 244.634C176.258 237.264 177.328 229.644 176.738 222.074C176.138 214.504 173.808 206.964 169.308 200.854C164.588 194.434 157.728 189.874 150.538 186.434C139.628 181.204 127.768 178.284 115.858 176.154C93.9183 172.224 71.6083 170.884 49.4083 168.944C45.8483 168.634 42.2483 168.294 38.8783 167.124C34.7683 165.704 31.0683 163.004 28.7383 159.334C26.4183 155.664 25.5583 151.024 26.7483 146.844C27.6583 143.624 29.7283 140.784 32.3583 138.724C34.9883 136.654 38.1683 135.324 41.4383 134.634C44.7183 133.944 48.0983 133.874 51.4383 134.154C53.2683 134.304 55.0883 134.554 56.8983 134.824C72.2383 137.094 87.3783 140.484 102.548 143.644C115.468 146.334 128.498 148.864 141.688 149.224C154.878 149.574 168.338 147.654 180.178 141.824C196.548 133.764 208.758 118.514 215.298 101.474C224.258 78.094 223.028 52.174 220.398 27.284C219.788 21.484 219.108 15.614 220.058 9.854C220.178 9.124 220.328 8.38398 220.658 7.71398C220.988 7.05398 221.528 6.45399 222.228 6.19399C222.858 5.95399 223.568 6.01399 224.218 6.22399C224.858 6.43399 225.448 6.77399 226.028 7.12399C262.588 29.154 290.508 63.614 310.198 101.484C312.188 105.314 314.108 109.204 315.408 113.314C316.708 117.434 317.358 121.814 316.768 126.084C316.348 129.114 315.268 132.104 313.318 134.454C310.668 137.634 306.688 139.354 302.778 140.744C298.878 142.124 294.808 143.324 291.488 145.804C286.998 149.174 284.328 154.834 284.598 160.444C292.098 161.904 299.448 164.114 306.508 167.014C312.788 169.594 318.998 172.854 323.418 178.014C327.088 182.294 329.288 187.614 331.438 192.844C332.158 194.584 332.878 196.344 333.328 198.184C333.778 200.014 333.958 201.944 333.578 203.794C333.138 205.934 331.948 207.914 330.248 209.294C329.898 208.024 329.258 206.834 328.408 205.834C326.958 204.154 324.928 203.054 322.798 202.454C318.258 201.174 313.328 202.114 309.018 204.044C304.708 205.974 300.898 208.834 297.068 211.584C294.808 213.204 292.508 214.804 290.028 216.064Z"/></svg>
19
+ `;var Hr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 6h11M9 12h11M9 18h11M4 6h1M4 12h1M4 18h1"/></svg>
20
+ `;var Pr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M440-280H280q-83 0-141.5-58.5T80-480q0-83 58.5-141.5T280-680h160v80H280q-50 0-85 35t-35 85q0 50 35 85t85 35h160v80ZM320-440v-80h320v80H320Zm200 160v-80h160q50 0 85-35t35-85q0-50-35-85t-85-35H520v-80h160q83 0 141.5 58.5T880-480q0 83-58.5 141.5T680-280H520Z"/></svg>
21
+ `;var Mr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
22
+ `;var Ir=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M120-80v-60h100v-30h-60v-60h60v-30H120v-60h120q17 0 28.5 11.5T280-280v40q0 17-11.5 28.5T240-200q17 0 28.5 11.5T280-160v40q0 17-11.5 28.5T240-80H120Zm0-280v-110q0-17 11.5-28.5T160-510h60v-30H120v-60h120q17 0 28.5 11.5T280-560v70q0 17-11.5 28.5T240-450h-60v30h100v60H120Zm60-280v-180h-60v-60h120v240h-60Zm180 440v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360Z"/></svg>
23
+ `;var Nr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M720-330q0 104-73 177T470-80q-104 0-177-73t-73-177v-370q0-75 52.5-127.5T400-880q75 0 127.5 52.5T580-700v350q0 46-32 78t-78 32q-46 0-78-32t-32-78v-370h80v370q0 13 8.5 21.5T470-320q13 0 21.5-8.5T500-350v-350q-1-42-29.5-71T400-800q-42 0-71 29t-29 71v370q-1 71 49 120.5T470-160q70 0 119-49.5T640-330v-390h80v390Z"/></svg>
24
+ `;var Or=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2" width="10" height="20" rx="2"/><path d="M11 18h2"/></svg>
25
+ `;var Dr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
26
+ `;var Br=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>
27
+ `;var Ur=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="m228-240 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T458-480L320-240h-92Zm360 0 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T818-480L680-240h-92ZM362.5-517.5Q380-535 380-560t-17.5-42.5Q345-620 320-620t-42.5 17.5Q260-585 260-560t17.5 42.5Q295-500 320-500t42.5-17.5Zm360 0Q740-535 740-560t-17.5-42.5Q705-620 680-620t-42.5 17.5Q620-585 620-560t17.5 42.5Q655-500 680-500t42.5-17.5ZM680-560Zm-360 0Z"/></svg>
28
+ `;var Fr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
29
+ `;var qr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2"/></svg>
30
+ `;var jr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 3 11 14M22 3l-7 18-4-7-7-4 18-7z"/></svg>
31
+ `;var Wr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="m370-80-16-128q-13-5-24.5-12T307-235l-119 50L78-375l103-78q-1-7-1-13.5v-27q0-6.5 1-13.5L78-585l110-190 119 50q11-8 23-15t24-12l16-128h220l16 128q13 5 24.5 12t22.5 15l119-50 110 190-103 78q1 7 1 13.5v27q0 6.5-2 13.5l103 78-110 190-118-50q-11 8-23 15t-24 12L590-80H370Zm70-80h79l14-106q31-8 57.5-23.5T639-327l99 41 39-68-86-65q5-14 7-29.5t2-31.5q0-16-2-31.5t-7-29.5l86-65-39-68-99 42q-22-23-48.5-38.5T533-694l-13-106h-79l-14 106q-31 8-57.5 23.5T321-633l-99-41-39 68 86 64q-5 15-7 30t-2 32q0 16 2 31t7 30l-86 65 39 68 99-42q22 23 48.5 38.5T427-266l13 106Zm42-180q58 0 99-41t41-99q0-58-41-99t-99-41q-59 0-99.5 41T342-480q0 58 40.5 99t99.5 41Zm-2-140Z"/></svg>
32
+ `;var Vr=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M360-200v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360ZM200-160q-33 0-56.5-23.5T120-240q0-33 23.5-56.5T200-320q33 0 56.5 23.5T280-240q0 33-23.5 56.5T200-160Zm0-240q-33 0-56.5-23.5T120-480q0-33 23.5-56.5T200-560q33 0 56.5 23.5T280-480q0 33-23.5 56.5T200-400Zm-56.5-263.5Q120-687 120-720t23.5-56.5Q167-800 200-800t56.5 23.5Q280-753 280-720t-23.5 56.5Q233-640 200-640t-56.5-23.5Z"/></svg>
33
+ `;var Kr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 16V4M8 8l4-4 4 4"/><path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/></svg>
34
+ `;var Gr=`<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>
35
+ `;var Id={article:z(hr),bold:z(br),check:z(yr),code:z($r),copyout:z(xr),editable:z(kr),heading:z(_r),indent:z(Tr),info:z(Lr),"info-filled":z(Rr),italic:z(Cr),kestrel:z(Ar),lines:z(Hr),link:z(Pr),ol:z(Ir),paperclip:z(Nr),plus:z(Dr),preview:z(Br),quote:z(Ur),readonly:z(Fr),search:z(qr),send:z(jr),settings:z(Wr),ul:z(Vr),upload:z(Kr),book:z(gr),branch:z(vr),"circle-check":z(wr),"circle-minus":z(Sr),desktop:z(Er),mail:z(Mr),phone:z(Or),x:z(Gr)};function O(e){return Id[e]}function Ut(e,t,n){let s=(v,f)=>e===v?o`<a href="#/${v}" data-room="${v}" data-text="${f}" aria-current="page">${f}</a>`:o`<a href="#/${v}" data-room="${v}" data-text="${f}">${f}</a>`,i=cr(),r=Y.appConfig?.deployment.build.build_time,a=r?`Built ${new Date(r).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}`:null,l=i?o`${i.version} <span aria-hidden="true">·</span> ${i.sha}`:null,d=l?a?o`<div class="rail-foot" title="${a}">${l}</div>`:o`<div class="rail-foot">${l}</div>`:null,u=l?a?o`<footer class="room-foot" title="${a}">${l}</footer>`:o`<footer class="room-foot">${l}</footer>`:null,m=t==null?o`<div class="room-body norail"><div class="room-main">${n}</div></div>`:o`<div class="room-body"><nav class="room-rail" aria-label="Contents"><div class="rail-inner">${t}${d}</div></nav><div class="room-main">${n}</div></div>`;return o`<div class="room">
36
36
  <header class="room-bar">
37
37
  <a class="room-back" href="#/dashboard" aria-label="Back to dashboard"><span aria-hidden="true">←</span><span class="room-back-label">Dashboard</span></a>
38
38
  <div class="room-nav">
39
- <a class="room-brand" href="#/docs">${N("kestrel")}<span>Kestrel</span></a>
39
+ <a class="room-brand" href="#/docs">${O("kestrel")}<span>Kestrel</span></a>
40
40
  <nav class="room-switch" aria-label="Reference">${s("docs","Docs")}${s("api-reference","API")}</nav>
41
41
  <a class="room-close" href="#/dashboard" title="Back to publication" aria-label="Back to publication"><span aria-hidden="true">✕</span></a>
42
42
  </div>
43
43
  </header>
44
- ${f}
44
+ ${m}
45
45
  ${u}
46
- </div>`}function Lr(){fe.addEventListener("click",e=>{let t=e.target instanceof Element?e.target.closest(".room-bar a[href^='#/']"):null;!t||t.getAttribute("href")!==location.hash||(e.preventDefault(),window.scrollTo(0,0))})}var Zc=/^(\/[A-Za-z0-9._~%-]+)+$/,Jc=/\/(?:\.|%2e){1,2}(?=\/|$)/i;function yo(e){return Zc.test(e)&&!Jc.test(e)}function Rr(e){let t=new URLSearchParams(e).get("to");return t&&yo(t)?`#${t}`:null}var Qc=/^(\d+)\.(\d+)$/;function Xc(e){return`${e.seq}.${e.at}`}function Cr(e){let t=Qc.exec(e);if(!t?.[1]||!t[2])return null;let n=Number(t[1]),s=Number(t[2]);return Number.isSafeInteger(n)&&Number.isSafeInteger(s)?{seq:n,at:s}:null}function ds(e,t){let n=Cr(e),s=Cr(t);return!n||!s?n?e:t:Xc({seq:Math.min(n.seq,s.seq),at:Math.min(n.at,s.at)})}function nt(e){switch(e.status){case"scheduled":return e.phase==="due"?"due":"scheduled";case"sending":return"sending";case"sent":return e.phase==="complete"?"complete":"sent";default:return"canceled"}}var ed=3e3,td=6e4,nd=3e4,Ue=new Set,us=null,bt=null,Ye,tt=null,un=!1,wo=!1,ps=0;function ms(e){try{e()}catch(t){reportError(t)}}function So(e,t){return e&&t?ds(e,t):e??t}function Ar(e){clearTimeout(Ye),Ye=void 0,!(!Ue.size||document.hidden)&&(Ye=setTimeout(pn,e))}function pn(){if(clearTimeout(Ye),Ye=void 0,!Ue.size)return;if(tt){un=!0;return}let e=So(us,bt);bt=null;let t=[...Ue],n=new AbortController;tt=n;let s=setTimeout(()=>n.abort(),nd),i=e?`?since=${encodeURIComponent(e)}`:"";R(`/api/sends/feed${i}`,{signal:n.signal}).then(a=>{if(clearTimeout(s),tt===n){tt=null,ps=0,us=a.cursor;for(let r of t)Ue.has(r)&&r.take(a);if(un){un=!1,pn();return}Ar(Math.max(0,a.read_again_at-a.now))}},a=>{if(clearTimeout(s),tt===n){if(tt=null,un=!1,a instanceof te&&a.code==="cursor_ahead"){let r=[...Ue];for(let l of r)Mr(l);for(let l of r)ms(()=>l.stale());return}a instanceof te&&a.status===400?us=null:bt=So(bt,e),ps+=1,Ar(Math.min(ed*2**(ps-1),td))}})}function sd(){wo||(wo=!0,queueMicrotask(()=>{wo=!1,pn()}))}function Hr(){document.hidden?(clearTimeout(Ye),Ye=void 0):pn()}function Pr(e,t,n){n.aborted||(Ue.add(e),bt=So(bt,t),Ue.size===1&&document.addEventListener("visibilitychange",Hr),n.addEventListener("abort",()=>Mr(e),{once:!0}),sd())}function Mr(e){Ue.delete(e),!Ue.size&&(clearTimeout(Ye),Ye=void 0,tt?.abort(),tt=null,un=!1,ps=0,us=null,bt=null,document.removeEventListener("visibilitychange",Hr))}function Ot(e,t,n){let s=new Map(e.sends.map(i=>[i.id,nt(i)]));Pr({take(i){if(!i.sends.length&&!i.removed.length)return;let a=[];for(let l of i.sends){let d=nt(l),u=s.get(l.id)??null;u!==d&&a.push({send:l,from:u,to:d}),s.set(l.id,d)}let r=i.removed.map(l=>l.id);for(let l of r)s.delete(l);ms(()=>t.update({sends:i.sends,changes:a,removed:r}))},stale:()=>t.stale()},e.cursor,n)}function mn(e,t,n){let s=e.send.id,i=nt(e.send);Pr({take(a){if(a.removed.some(u=>u.id===s)){ms(()=>t.removed());return}let r=a.sends.find(u=>u.id===s);if(!r)return;let l=nt(r),d=l!==i?{send:r,from:i,to:l}:null;i=l,ms(()=>t.update(r,d))},stale:()=>t.stale()},e.cursor,n)}function Fe(){Ue.size&&pn()}function gt(e){return e.trim().toLowerCase()}function vt(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function W(e){if(!e)return"\u2014";let t=new Date(e);return t.toLocaleString(void 0,{year:t.getFullYear()===new Date().getFullYear()?void 0:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function fs(e){let t=new Set,n=[];for(let s of String(e||"").split(/[\n,]+/)){let i=gt(s);vt(i)?t.add(i):i&&n.push(s.trim())}return{valid:[...t],invalid:n}}function hs(e){return e.length?`Not ${e.length===1?"an email address":"email addresses"}: ${e.join(", ")}`:null}function bs(e,t,n){let s=new Map,i=[];for(let r of n)r.message?s.set(r.message,[...s.get(r.message)??[],r.email]):i.push(r.email);if(!s.size)return e?`Sent to ${e} of ${t}. Not sent to ${i.join(", ")}. Send again to try those.`:"Not sent. Send again to try.";let a=[...s].map(([r,l])=>t>1?`${l.join(", ")}: ${r}`:r);return i.length&&a.push(`Not sent to ${i.join(", ")}.`),e?`Sent to ${e} of ${t}. ${a.join(" ")} Send again goes only to those.`:a.join(" ")}function yt(e){let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}function fn(e,t=!1){let n=e-Date.now();if(t||n<=0)return"Preparing to send\u2026";let s=Math.floor(n/1e3),i=Math.floor(s/60),a=Math.floor(i/60);if(s<300)return i>0?`Sends in ${i}m ${String(s%60).padStart(2,"0")}s`:`Sends in ${s}s`;if(i<60)return`Sends in ${i}m`;if(a<24){let l=i%60;return l>0?`Sends in ${a}h ${l}m`:`Sends in ${a}h`}let r=Math.round(a/24);return`Sends in ${r} day${r===1?"":"s"}`}function gs(e){return`Missed its fire time \xB7 ${Math.max(0,Math.floor((Date.now()-e)/6e4))} min late`}var hn=e=>Math.max(0,Math.min(100,Math.round(e||0)));function vs(e){if(e==null||!Number.isFinite(e)||e<=0)return"\u2014";let t=Math.round(e/1e3);if(t<90)return`${t}s`;let n=Math.round(t/60);return n<90?`${n} min`:`${Math.round(n/60)} hr`}function wt(e,t){return t.email_only?o`<span class="title-with-label"><span class="title-text">${e}</span><span class="email-only-mark">${N("mail")}Email only</span></span>`:e}function ys(e){return e.email_only?o` · <span class="sched-email-only">Email only</span>`:null}function ws(e){return o`<span class="countdown" data-fire="${e.fire_at}"${e.phase==="due"&&o` data-due`}${Le(e,"missed")&&o` data-missed`}></span>`}function Ss(e,t){let n=0,s=()=>{let i=Date.now(),a=Number.POSITIVE_INFINITY,r=l=>{l>i&&l<a&&(a=l)};for(let l of I("[data-closes]",e)){let d=Number(l.dataset.closes);l.hidden=i>=d,r(d)}for(let l of I("[data-fire]",e)){let d=Number(l.dataset.fire),u=l.dataset.missed!==void 0;l.textContent=u?gs(d):fn(d,l.dataset.due!==void 0),l.classList.toggle("countdown-missed",u),r(d)}a-i<=1e3&&a!==n&&(n=a,ft(a,s,t))};return mt(1e3,s,t),s}var Le=(e,t)=>e.conditions.some(n=>n.kind===t);function he(e,t){return e.conditions.find(n=>n.kind===t)}var Ze=(e,t)=>e.actions.some(n=>n.name===t);function Dt(e,t){let n=new Set(e.map(s=>s.id));return[...e.map(s=>t.get(s.id)??s),...[...t.values()].filter(s=>!n.has(s.id))]}function bn(e){return Le(e,"wedged")||Le(e,"refused")}function Ut(e){let t=e.delivered||0,n=[];e.complained&&n.push(`${e.complained.toLocaleString()} complained`),e.bounced&&n.push(`${e.bounced.toLocaleString()} bounced`),e.unsent&&n.push(`${e.unsent.toLocaleString()} unsent`);let s=n.length?o`<span class="muted delivered-note">${n.map((i,a)=>o`${a?", ":""}<span class="delivered-kind">${i}</span>`)}</span>`:null;return o`<span class="n">${t.toLocaleString()}</span>${s}`}function Ft(e){if(e===null)return"it is retried on its own";let t=e-Date.now();return t>0?`next retry in ${vs(t)}`:"next retry due now"}function $s(e,{stuckNote:t=!0}={}){let n=e.counts,s=n.accepted+n.delivered+n.bounced+n.complained,i=n.delivered+n.bounced+n.complained,a=e.audience.count,r=a>0?100*s/a:0,l=e.dispatch.eta_ms?` \xB7 ~${vs(e.dispatch.eta_ms)} left`:"",d=t?he(e,"stuck"):void 0,u=e.provider.halt,f=e.phase==="backing_off"&&u?.reason==="unavailable",S=f?"Backing off":"Sending",b=f?` \xB7 provider unavailable, ${Ft(u.retry_at)}`:"";return o`<div class="card spread clickable active-card" data-watch="${e.id}">
46
+ </div>`}function zr(){pe.addEventListener("click",e=>{let t=e.target instanceof Element?e.target.closest(".room-bar a[href^='#/']"):null;!t||t.getAttribute("href")!==location.hash||(e.preventDefault(),window.scrollTo(0,0))})}var Nd=/^(\/[A-Za-z0-9._~%-]+)+$/,Od=/\/(?:\.|%2e){1,2}(?=\/|$)/i;function Po(e){return Nd.test(e)&&!Od.test(e)}function Yr(e){let t=new URLSearchParams(e).get("to");return t&&Po(t)?`#${t}`:null}var Dd=/^(\d+)\.(\d+)$/;function Bd(e){return`${e.seq}.${e.at}`}function Zr(e){let t=Dd.exec(e);if(!t?.[1]||!t[2])return null;let n=Number(t[1]),s=Number(t[2]);return Number.isSafeInteger(n)&&Number.isSafeInteger(s)?{seq:n,at:s}:null}function ys(e,t){let n=Zr(e),s=Zr(t);return!n||!s?n?e:t:Bd({seq:Math.min(n.seq,s.seq),at:Math.min(n.at,s.at)})}function ot(e){switch(e.status){case"scheduled":return e.phase==="due"?"due":"scheduled";case"sending":return"sending";case"sent":return e.phase==="complete"?"complete":"sent";default:return"canceled"}}var Ud=3e3,Fd=6e4,qd=3e4,Ue=new Set,ws=null,yt=null,Je,st=null,hn=!1,Mo=!1,Ss=0;function $s(e){try{e()}catch(t){reportError(t)}}function Io(e,t){return e&&t?ys(e,t):e??t}function Jr(e){clearTimeout(Je),Je=void 0,!(!Ue.size||document.hidden)&&(Je=setTimeout(bn,e))}function bn(){if(clearTimeout(Je),Je=void 0,!Ue.size)return;if(st){hn=!0;return}let e=Io(ws,yt);yt=null;let t=[...Ue],n=new AbortController;st=n;let s=setTimeout(()=>n.abort(),qd),i=e?`?since=${encodeURIComponent(e)}`:"";L(`/api/sends/feed${i}`,{signal:n.signal}).then(r=>{if(clearTimeout(s),st===n){st=null,Ss=0,ws=r.cursor;for(let a of t)Ue.has(a)&&a.take(r);if(hn){hn=!1,bn();return}Jr(Math.max(0,r.read_again_at-r.now))}},r=>{if(clearTimeout(s),st===n){if(st=null,hn=!1,r instanceof te&&r.code==="cursor_ahead"){let a=[...Ue];for(let l of a)ea(l);for(let l of a)$s(()=>l.stale());return}r instanceof te&&r.status===400?ws=null:yt=Io(yt,e),Ss+=1,Jr(Math.min(Ud*2**(Ss-1),Fd))}})}function jd(){Mo||(Mo=!0,queueMicrotask(()=>{Mo=!1,bn()}))}function Qr(){document.hidden?(clearTimeout(Je),Je=void 0):bn()}function Xr(e,t,n){n.aborted||(Ue.add(e),yt=Io(yt,t),Ue.size===1&&document.addEventListener("visibilitychange",Qr),n.addEventListener("abort",()=>ea(e),{once:!0}),jd())}function ea(e){Ue.delete(e),!Ue.size&&(clearTimeout(Je),Je=void 0,st?.abort(),st=null,hn=!1,Ss=0,ws=null,yt=null,document.removeEventListener("visibilitychange",Qr))}function Ft(e,t,n){let s=new Map(e.sends.map(i=>[i.id,ot(i)]));Xr({take(i){if(!i.sends.length&&!i.removed.length)return;let r=[];for(let l of i.sends){let d=ot(l),u=s.get(l.id)??null;u!==d&&r.push({send:l,from:u,to:d}),s.set(l.id,d)}let a=i.removed.map(l=>l.id);for(let l of a)s.delete(l);$s(()=>t.update({sends:i.sends,changes:r,removed:a}))},stale:()=>t.stale()},e.cursor,n)}function gn(e,t,n){let s=e.send.id,i=ot(e.send);Xr({take(r){if(r.removed.some(u=>u.id===s)){$s(()=>t.removed());return}let a=r.sends.find(u=>u.id===s);if(!a)return;let l=ot(a),d=l!==i?{send:a,from:i,to:l}:null;i=l,$s(()=>t.update(a,d))},stale:()=>t.stale()},e.cursor,n)}function Fe(){Ue.size&&bn()}function wt(e){return e.trim().toLowerCase()}function St(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function j(e){if(!e)return"\u2014";let t=new Date(e);return t.toLocaleString(void 0,{year:t.getFullYear()===new Date().getFullYear()?void 0:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function xs(e){let t=new Set,n=[];for(let s of String(e||"").split(/[\n,]+/)){let i=wt(s);St(i)?t.add(i):i&&n.push(s.trim())}return{valid:[...t],invalid:n}}function Es(e){return e.length?`Not ${e.length===1?"an email address":"email addresses"}: ${e.join(", ")}`:null}function ks(e,t,n){let s=new Map,i=[];for(let a of n)a.message?s.set(a.message,[...s.get(a.message)??[],a.email]):i.push(a.email);if(!s.size)return e?`Sent to ${e} of ${t}. Not sent to ${i.join(", ")}. Send again to try those.`:"Not sent. Send again to try.";let r=[...s].map(([a,l])=>t>1?`${l.join(", ")}: ${a}`:a);return i.length&&r.push(`Not sent to ${i.join(", ")}.`),e?`Sent to ${e} of ${t}. ${r.join(" ")} Send again goes only to those.`:r.join(" ")}function $t(e){let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}function vn(e,t=!1){let n=e-Date.now();if(t||n<=0)return"Preparing to send\u2026";let s=Math.floor(n/1e3),i=Math.floor(s/60),r=Math.floor(i/60);if(s<300)return i>0?`Sends in ${i}m ${String(s%60).padStart(2,"0")}s`:`Sends in ${s}s`;if(i<60)return`Sends in ${i}m`;if(r<24){let l=i%60;return l>0?`Sends in ${r}h ${l}m`:`Sends in ${r}h`}let a=Math.round(r/24);return`Sends in ${a} day${a===1?"":"s"}`}function _s(e){return`Missed its fire time \xB7 ${Math.max(0,Math.floor((Date.now()-e)/6e4))} min late`}var yn=e=>Math.max(0,Math.min(100,Math.round(e||0)));function Ts(e){if(e==null||!Number.isFinite(e)||e<=0)return"\u2014";let t=Math.round(e/1e3);if(t<90)return`${t}s`;let n=Math.round(t/60);return n<90?`${n} min`:`${Math.round(n/60)} hr`}function xt(e,t){return t.email_only?o`<span class="title-with-label"><span class="title-text">${e}</span><span class="email-only-mark">${O("mail")}Email only</span></span>`:e}function Ls(e){return e.email_only?o` · <span class="sched-email-only">Email only</span>`:null}function Rs(e){return o`<span class="countdown" data-fire="${e.fire_at}"${e.phase==="due"&&o` data-due`}${Re(e,"missed")&&o` data-missed`}></span>`}function Cs(e,t){let n=0,s=()=>{let i=Date.now(),r=Number.POSITIVE_INFINITY,a=l=>{l>i&&l<r&&(r=l)};for(let l of N("[data-closes]",e)){let d=Number(l.dataset.closes);l.hidden=i>=d,a(d)}for(let l of N("[data-fire]",e)){let d=Number(l.dataset.fire),u=l.dataset.missed!==void 0;l.textContent=u?_s(d):vn(d,l.dataset.due!==void 0),l.classList.toggle("countdown-missed",u),a(d)}r-i<=1e3&&r!==n&&(n=r,gt(r,s,t))};return bt(1e3,s,t),s}var Re=(e,t)=>e.conditions.some(n=>n.kind===t);function he(e,t){return e.conditions.find(n=>n.kind===t)}var Qe=(e,t)=>e.actions.some(n=>n.name===t);function qt(e,t){let n=new Set(e.map(s=>s.id));return[...e.map(s=>t.get(s.id)??s),...[...t.values()].filter(s=>!n.has(s.id))]}function wn(e){return Re(e,"wedged")||Re(e,"refused")}function jt(e){let t=e.delivered||0,n=[];e.complained&&n.push(`${e.complained.toLocaleString()} complained`),e.bounced&&n.push(`${e.bounced.toLocaleString()} bounced`),e.unsent&&n.push(`${e.unsent.toLocaleString()} unsent`);let s=n.length?o`<span class="muted delivered-note">${n.map((i,r)=>o`${r?", ":""}<span class="delivered-kind">${i}</span>`)}</span>`:null;return o`<span class="n">${t.toLocaleString()}</span>${s}`}function Wt(e){if(e===null)return"it is retried on its own";let t=e-Date.now();return t>0?`next retry in ${Ts(t)}`:"next retry due now"}function As(e,{stuckNote:t=!0}={}){let n=e.counts,s=n.accepted+n.delivered+n.bounced+n.complained,i=n.delivered+n.bounced+n.complained,r=e.audience.count,a=r>0?100*s/r:0,l=e.dispatch.eta_ms?` \xB7 ~${Ts(e.dispatch.eta_ms)} left`:"",d=t?he(e,"stuck"):void 0,u=e.provider.halt,m=e.phase==="backing_off"&&u?.reason==="unavailable",v=m?"Backing off":"Sending",f=m?` \xB7 provider unavailable, ${Wt(u.retry_at)}`:"";return o`<div class="card spread clickable active-card" data-watch="${e.id}">
47
47
  <div class="active-main">
48
48
  <a class="card-link active-subj" href="#/sent/${e.id}">${e.subject||o`<em>untitled</em>`}</a>
49
- <div class="active-bar"><div class="active-fill" style="width:${hn(r)}%"></div></div>
50
- <div class="muted active-stat">${S}: ${s.toLocaleString()} of ${a.toLocaleString()} accepted${i?` \xB7 ${i.toLocaleString()} confirmed`:""}${l}${b}</div>
49
+ <div class="active-bar"><div class="active-fill" style="width:${yn(a)}%"></div></div>
50
+ <div class="muted active-stat">${v}: ${s.toLocaleString()} of ${r.toLocaleString()} accepted${i?` \xB7 ${i.toLocaleString()} confirmed`:""}${l}${f}</div>
51
51
  ${d?o`<div class="active-stuck">${d.message}</div>`:null}
52
52
  </div>
53
53
  <a class="ghost-link" href="#/sent/${e.id}">Watch&nbsp;→</a>
54
- </div>`}function qt(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.suppressed&&t.set("suppressed",e.suppressed),e.failures&&t.set("failures",e.failures);let n=(e.search||"").trim();return n&&t.set("search",n),e.sort&&(t.set("sort",e.sort),t.set("dir",e.dir??"desc")),t.set("limit",String(e.limit)),t.set("offset",String(e.offset)),t.toString()}function jt(e){let t=e.statuses?.length?o`<select class="lt-status" aria-label="Filter by status"><option value="${e.allValue||""}">All statuses</option>${e.statuses.map(i=>o`<option value="${i.value}">${i.label}</option>`)}</select>`:null,n=e.suppressible?o`<label class="lt-toggle"><input type="checkbox" class="lt-suppressed"><span>Suppressed</span></label>`:null,s=e.failures?o`<label class="lt-toggle"><input type="checkbox" class="lt-failures"><span>With delivery failures</span></label>`:null;return o`<div class="list-toolbar">
54
+ </div>`}function Vt(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.suppressed&&t.set("suppressed",e.suppressed),e.failures&&t.set("failures",e.failures);let n=(e.search||"").trim();return n&&t.set("search",n),e.sort&&(t.set("sort",e.sort),t.set("dir",e.dir??"desc")),t.set("limit",String(e.limit)),t.set("offset",String(e.offset)),t.toString()}function Kt(e){let t=e.statuses?.length?o`<select class="lt-status" aria-label="Filter by status"><option value="${e.allValue||""}">All statuses</option>${e.statuses.map(i=>o`<option value="${i.value}">${i.label}</option>`)}</select>`:null,n=e.suppressible?o`<label class="lt-toggle"><input type="checkbox" class="lt-suppressed"><span>Suppressed</span></label>`:null,s=e.failures?o`<label class="lt-toggle"><input type="checkbox" class="lt-failures"><span>With delivery failures</span></label>`:null;return o`<div class="list-toolbar">
55
55
  <input class="lt-search" type="search" placeholder="${e.searchPlaceholder||"Search\u2026"}" aria-label="Search" autocomplete="off">
56
56
  <div class="lt-filters">${t}${n}${s}</div>
57
- </div>`}function Wt(e,t,n){let s=e.querySelector(".lt-search"),i=e.querySelector(".lt-status"),a=e.querySelector(".lt-suppressed"),r=e.querySelector(".lt-failures");if(s){s.value=t.search||"";let l;s.oninput=()=>{clearTimeout(l),l=setTimeout(()=>{t.search=s.value,t.offset=0,n()},250)}}i&&(i.value=t.status||"",i.onchange=()=>{t.status=i.value,t.offset=0,n()}),a&&(a.checked=t.suppressed==="only",a.onchange=()=>{t.suppressed=a.checked?"only":"",t.offset=0,n()}),r&&(r.checked=t.failures==="only",r.onchange=()=>{t.failures=r.checked?"only":"",t.offset=0,n()})}function $e(e,t,n,s){if(!t)return s?o`<th class="${s}">${e}</th>`:o`<th>${e}</th>`;let i=n.sort===t,a=i?n.dir==="asc"?"\u2191":"\u2193":"",r=`${s?`${s} `:""}sortable${i?" sorted":""}`;return o`<th class="${r}"><button type="button" class="th-sort" data-sort="${t}">${e}<span class="th-arrow" aria-hidden="true">${a}</span></button></th>`}function st(e,t,n){for(let s of e.querySelectorAll(".th-sort"))s.onclick=()=>{let i=s.dataset.sort;t.sort===i?t.dir=t.dir==="asc"?"desc":"asc":(t.sort=i,t.dir="desc"),t.offset=0,n()}}function ot(e,t,n,s){let i=n?.limit??t.limit;if(!n||n.total<=i){h(e,o``);return}let a=n.offset+1,r=Math.min(n.offset+i,n.total),l=n.offset>0,d=n.offset+i<n.total;if(h(e,o`<div class="pager"><button type="button" class="pager-prev"${l?null:Ir}>← Prev</button><span class="pager-range muted">${a}–${r} of ${n.total}</span><button type="button" class="pager-next"${d?null:Ir}>Next →</button></div>`),l){let u=e.querySelector(".pager-prev");u&&(u.onclick=()=>{t.offset=Math.max(0,n.offset-i),s()})}if(d){let u=e.querySelector(".pager-next");u&&(u.onclick=()=>{t.offset=n.offset+i,s()})}}var Ir=o` disabled`;var od=3600,id=300,rd=3,Eo=new WeakMap;function O(e){let t=[...io.querySelectorAll(".toast:not(.leaving)")],n=t.find(i=>i.textContent===e);if(n){Nr(n);return}let s=document.createElement("div");s.className="toast",s.textContent=e,io.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),Nr(s);for(let i of t.slice(0,t.length+1-rd))Or(i)}function Nr(e){clearTimeout(Eo.get(e)),Eo.set(e,window.setTimeout(()=>Or(e),od))}function Or(e){clearTimeout(Eo.get(e)),e.style.height=`${e.offsetHeight}px`,e.offsetHeight,e.classList.add("leaving"),e.style.height="0",setTimeout(()=>e.remove(),id)}var Je=e=>o`<span class="badge ${e}">${e}</span>`,ad=0,$o=new WeakMap;function Dr(e){let t=document.createElement("div");t.className="field-error",t.id=`field-error-${++ad}`,t.setAttribute("role","alert");let n=document.createElement("span");n.className="field-error-ico",n.setAttribute("aria-hidden","true"),n.textContent="!";let s=document.createElement("span");return s.textContent=e,t.append(n,s),t}function Ne(e,t,{after:n}={}){$o.get(e)?.();let s=Dr(t),i=e.getAttribute("aria-describedby");(n??e).after(s),e.setAttribute("aria-describedby",i?`${i} ${s.id}`:s.id),e.classList.add("is-invalid");let a=!1,r=()=>{a||(a=!0,s.remove(),e.classList.remove("is-invalid"),i===null?e.removeAttribute("aria-describedby"):e.setAttribute("aria-describedby",i),e.removeEventListener("input",r),e.removeEventListener("change",r),$o.delete(e))};return e.addEventListener("input",r),e.addEventListener("change",r),$o.set(e,r),r}function pe(e,t){let n=document.createElement("div");n.className="modal-backdrop",h(n,o`<div class="modal" role="dialog" aria-modal="true">${e}</div>`);let s=n.firstElementChild,i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=f=>{n===[...document.querySelectorAll(".modal-backdrop")].pop()&&(f.key==="Escape"?u():f.key==="Tab"&&cd(s,f))},r=null,l=()=>{r?.(),r=null},d=(f,S)=>{if(l(),S){r=Ne(S,f),S.focus();return}let b=Dr(f);b.classList.add("dialog-error");let p=s.querySelector(".actions");p?p.before(b):s.append(b),r=()=>b.remove()},u=()=>{let f=document.activeElement,S=n.contains(f)||!f||f===document.body;n.remove(),document.removeEventListener("keydown",a),t.removeEventListener("abort",u),S&&i?.isConnected&&i.focus()};return t.aborted?{el:n,close:u,error:d,clearError:l}:(document.body.appendChild(n),n.addEventListener("click",f=>{f.target===n&&u()}),document.addEventListener("keydown",a),t.addEventListener("abort",u,{once:!0}),queueMicrotask(()=>{n.isConnected&&!s.contains(document.activeElement)&&Ur(s)[0]?.focus()}),{el:n,close:u,error:d,clearError:l})}var ld='a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Ur(e){return[...e.querySelectorAll(ld)].filter(t=>!t.closest("[hidden]"))}function cd(e,t){let n=Ur(e),s=n[0],i=n[n.length-1];if(!s||!i){t.preventDefault();return}let a=document.activeElement;e.contains(a)?t.shiftKey&&a===s?(t.preventDefault(),i.focus()):!t.shiftKey&&a===i&&(t.preventDefault(),s.focus()):(t.preventDefault(),s.focus())}var Br=8;function dd(e){let t=getComputedStyle(e,"::after"),n=parseFloat(t.width)+parseFloat(t.paddingLeft)+parseFloat(t.paddingRight);if(!Number.isFinite(n))return;let s=e.getBoundingClientRect().left,i=document.documentElement.clientWidth,a=Math.min(0,Math.max(i-Br-n-s,Br-s));e.style.setProperty("--tip-x",`${Math.round(a)}px`)}function Fr(){for(let e of["pointerover","focusin"])document.addEventListener(e,t=>{let n=t.target instanceof Element?t.target.closest(".info"):null;n&&dd(n)});document.addEventListener("keydown",e=>{let t=document.activeElement;e.key==="Escape"&&t instanceof HTMLElement&&t.classList.contains("info")&&t.blur()})}var Es=[],xo=null,Vt=null;function St(){let e=Es.some(t=>t.contains(document.activeElement));for(let t of Es)t.remove();Es=[],xo?.removeEventListener("abort",St),xo=null,Vt?.setAttribute("aria-expanded","false"),e&&Vt?.isConnected&&Vt.focus(),Vt=null}function Kt(e,t,n,{align:s="end"}={}){if(St(),n.aborted)return;let i=document.createElement("div");i.className="menu-overlay",i.onclick=St;let a=document.createElement("div");a.className="menu",a.setAttribute("role","menu");for(let l of t){let d=document.createElement("button");if(d.type="button",d.setAttribute("role","menuitem"),d.tabIndex=-1,d.className=`menu-item${l.danger?" danger-item":""}`,l.description){let u=document.createElement("span");u.className="menu-item-name",u.textContent=l.label;let f=document.createElement("span");f.className="menu-item-desc",f.textContent=l.description,d.append(u,f),a.classList.add("menu-described")}else d.textContent=l.label;d.onclick=()=>{St(),l.onClick()},a.appendChild(d)}a.addEventListener("keydown",l=>ud(a,l)),document.body.appendChild(i),document.body.appendChild(a),Es=[i,a],xo=n,Vt=e instanceof HTMLElement?e:null,Vt?.setAttribute("aria-expanded","true"),n.addEventListener("abort",St,{once:!0});let r=e.getBoundingClientRect();a.style.top=`${r.bottom+window.scrollY+4}px`,a.style.left=`${(s==="start"?r.left:r.right-a.offsetWidth)+window.scrollX}px`,a.querySelector(".menu-item")?.focus()}function ud(e,t){let n=[...e.querySelectorAll(".menu-item")],s=n.indexOf(document.activeElement),i=a=>{t.preventDefault(),n[(a+n.length)%n.length]?.focus()};t.key==="ArrowDown"?i(s+1):t.key==="ArrowUp"?i(s-1):t.key==="Home"?i(0):t.key==="End"?i(n.length-1):t.key==="Escape"?(t.preventDefault(),t.stopPropagation(),St()):t.key==="Tab"&&St()}async function G(e,t,n){let s=e.textContent;e.disabled=!0,t&&(e.textContent=t);try{return await n()}finally{e.isConnected&&(e.disabled=!1,e.textContent=s)}}function oe(e,t,n){h(e,o`<div class="error"><span>${t}</span><button class="ghost" data-retry>Retry</button></div>`);let s=e.querySelector("[data-retry]");s&&(s.onclick=n)}function Gt(e,t){return e.actions.find(n=>n.name===t)}function gn(e){let t=e.send;return t&&(t.status==="scheduled"||t.status==="sending")?t:null}var pd=[{value:"draft",label:"Draft"},{value:"scheduled",label:"Scheduled"}],ko="draft,scheduled";function _o(e){return G(e,"Creating\u2026",async()=>{try{let{post:t}=await R("/api/posts",{method:"POST",json:{}});location.hash=`#/edit/${t.id}`}catch(t){O(F(t))}})}async function To(e,t){se(t,"Drafts");let n={status:ko,search:"",sort:"",dir:"desc",offset:0,limit:50};h(e,o`<div class="spread page-head"><h1>Drafts</h1><button class="primary" id="newPost">New post</button></div>
58
- ${jt({statuses:pd,allValue:ko,searchPlaceholder:"Search subject\u2026"})}
57
+ </div>`}function Gt(e,t,n){let s=e.querySelector(".lt-search"),i=e.querySelector(".lt-status"),r=e.querySelector(".lt-suppressed"),a=e.querySelector(".lt-failures");if(s){s.value=t.search||"";let l;s.oninput=()=>{clearTimeout(l),l=setTimeout(()=>{t.search=s.value,t.offset=0,n()},250)}}i&&(i.value=t.status||"",i.onchange=()=>{t.status=i.value,t.offset=0,n()}),r&&(r.checked=t.suppressed==="only",r.onchange=()=>{t.suppressed=r.checked?"only":"",t.offset=0,n()}),a&&(a.checked=t.failures==="only",a.onchange=()=>{t.failures=a.checked?"only":"",t.offset=0,n()})}function Ee(e,t,n,s){if(!t)return s?o`<th class="${s}">${e}</th>`:o`<th>${e}</th>`;let i=n.sort===t,r=i?n.dir==="asc"?"\u2191":"\u2193":"",a=`${s?`${s} `:""}sortable${i?" sorted":""}`;return o`<th class="${a}"><button type="button" class="th-sort" data-sort="${t}">${e}<span class="th-arrow" aria-hidden="true">${r}</span></button></th>`}function it(e,t,n){for(let s of e.querySelectorAll(".th-sort"))s.onclick=()=>{let i=s.dataset.sort;t.sort===i?t.dir=t.dir==="asc"?"desc":"asc":(t.sort=i,t.dir="desc"),t.offset=0,n()}}function rt(e,t,n,s){let i=n?.limit??t.limit;if(!n||n.total<=i){h(e,o``);return}let r=n.offset+1,a=Math.min(n.offset+i,n.total),l=n.offset>0,d=n.offset+i<n.total;if(h(e,o`<div class="pager"><button type="button" class="pager-prev"${l?null:ta}>← Prev</button><span class="pager-range muted">${r}–${a} of ${n.total}</span><button type="button" class="pager-next"${d?null:ta}>Next →</button></div>`),l){let u=e.querySelector(".pager-prev");u&&(u.onclick=()=>{t.offset=Math.max(0,n.offset-i),s()})}if(d){let u=e.querySelector(".pager-next");u&&(u.onclick=()=>{t.offset=n.offset+i,s()})}}var ta=o` disabled`;var Wd=3600,Vd=300,Kd=3,Oo=new WeakMap;function U(e){let t=[...wo.querySelectorAll(".toast:not(.leaving)")],n=t.find(i=>i.textContent===e);if(n){na(n);return}let s=document.createElement("div");s.className="toast",s.textContent=e,wo.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),na(s);for(let i of t.slice(0,t.length+1-Kd))oa(i)}function na(e){clearTimeout(Oo.get(e)),Oo.set(e,window.setTimeout(()=>oa(e),Wd))}function oa(e){clearTimeout(Oo.get(e)),e.style.height=`${e.offsetHeight}px`,e.offsetHeight,e.classList.add("leaving"),e.style.height="0",setTimeout(()=>e.remove(),Vd)}var Xe=e=>o`<span class="badge ${e}">${e}</span>`,Gd=0,No=new WeakMap;function ia(e){let t=document.createElement("div");t.className="field-error",t.id=`field-error-${++Gd}`,t.setAttribute("role","alert");let n=document.createElement("span");n.className="field-error-ico",n.setAttribute("aria-hidden","true"),n.textContent="!";let s=document.createElement("span");return s.textContent=e,t.append(n,s),t}function qe(e,t,{after:n}={}){No.get(e)?.();let s=ia(t),i=e.getAttribute("aria-describedby");(n??e).after(s),e.setAttribute("aria-describedby",i?`${i} ${s.id}`:s.id),e.classList.add("is-invalid");let r=!1,a=()=>{r||(r=!0,s.remove(),e.classList.remove("is-invalid"),i===null?e.removeAttribute("aria-describedby"):e.setAttribute("aria-describedby",i),e.removeEventListener("input",a),e.removeEventListener("change",a),No.delete(e))};return e.addEventListener("input",a),e.addEventListener("change",a),No.set(e,a),a}function fe(e,t){let n=document.createElement("div");n.className="modal-backdrop",h(n,o`<div class="modal" role="dialog" aria-modal="true">${e}</div>`);let s=n.firstElementChild,i=document.activeElement instanceof HTMLElement?document.activeElement:null,r=m=>{n===[...document.querySelectorAll(".modal-backdrop")].pop()&&(m.key==="Escape"?u():m.key==="Tab"&&Yd(s,m))},a=null,l=()=>{a?.(),a=null},d=(m,v)=>{if(l(),v){a=qe(v,m),v.focus();return}let f=ia(m);f.classList.add("dialog-error");let p=s.querySelector(".actions");p?p.before(f):s.append(f),a=()=>f.remove()},u=()=>{let m=document.activeElement,v=n.contains(m)||!m||m===document.body;n.remove(),document.removeEventListener("keydown",r),t.removeEventListener("abort",u),v&&i?.isConnected&&i.focus()};return t.aborted?{el:n,close:u,error:d,clearError:l}:(document.body.appendChild(n),n.addEventListener("click",m=>{m.target===n&&u()}),document.addEventListener("keydown",r),t.addEventListener("abort",u,{once:!0}),queueMicrotask(()=>{n.isConnected&&!s.contains(document.activeElement)&&ra(s)[0]?.focus()}),{el:n,close:u,error:d,clearError:l})}var zd='a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function ra(e){return[...e.querySelectorAll(zd)].filter(t=>!t.closest("[hidden]"))}function Yd(e,t){let n=ra(e),s=n[0],i=n[n.length-1];if(!s||!i){t.preventDefault();return}let r=document.activeElement;e.contains(r)?t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus()):(t.preventDefault(),s.focus())}var sa=8;function Zd(e){let t=getComputedStyle(e,"::after"),n=parseFloat(t.width)+parseFloat(t.paddingLeft)+parseFloat(t.paddingRight);if(!Number.isFinite(n))return;let s=e.getBoundingClientRect().left,i=document.documentElement.clientWidth,r=Math.min(0,Math.max(i-sa-n-s,sa-s));e.style.setProperty("--tip-x",`${Math.round(r)}px`)}function aa(){for(let e of["pointerover","focusin"])document.addEventListener(e,t=>{let n=t.target instanceof Element?t.target.closest(".info"):null;n&&Zd(n)});document.addEventListener("keydown",e=>{let t=document.activeElement;e.key==="Escape"&&t instanceof HTMLElement&&t.classList.contains("info")&&t.blur()})}var Hs=[],Do=null,zt=null;function Et(){let e=Hs.some(t=>t.contains(document.activeElement));for(let t of Hs)t.remove();Hs=[],Do?.removeEventListener("abort",Et),Do=null,zt?.setAttribute("aria-expanded","false"),e&&zt?.isConnected&&zt.focus(),zt=null}function Yt(e,t,n,{align:s="end"}={}){if(Et(),n.aborted)return;let i=document.createElement("div");i.className="menu-overlay",i.onclick=Et;let r=document.createElement("div");r.className="menu",r.setAttribute("role","menu");for(let l of t){let d=document.createElement("button");if(d.type="button",d.setAttribute("role","menuitem"),d.tabIndex=-1,d.className=`menu-item${l.danger?" danger-item":""}`,l.description){let u=document.createElement("span");u.className="menu-item-name",u.textContent=l.label;let m=document.createElement("span");m.className="menu-item-desc",m.textContent=l.description,d.append(u,m),r.classList.add("menu-described")}else d.textContent=l.label;d.onclick=()=>{Et(),l.onClick()},r.appendChild(d)}r.addEventListener("keydown",l=>Jd(r,l)),document.body.appendChild(i),document.body.appendChild(r),Hs=[i,r],Do=n,zt=e instanceof HTMLElement?e:null,zt?.setAttribute("aria-expanded","true"),n.addEventListener("abort",Et,{once:!0});let a=e.getBoundingClientRect();r.style.top=`${a.bottom+window.scrollY+4}px`,r.style.left=`${(s==="start"?a.left:a.right-r.offsetWidth)+window.scrollX}px`,r.querySelector(".menu-item")?.focus()}function Jd(e,t){let n=[...e.querySelectorAll(".menu-item")],s=n.indexOf(document.activeElement),i=r=>{t.preventDefault(),n[(r+n.length)%n.length]?.focus()};t.key==="ArrowDown"?i(s+1):t.key==="ArrowUp"?i(s-1):t.key==="Home"?i(0):t.key==="End"?i(n.length-1):t.key==="Escape"?(t.preventDefault(),t.stopPropagation(),Et()):t.key==="Tab"&&Et()}async function Z(e,t,n){let s=e.textContent;e.disabled=!0,t&&(e.textContent=t);try{return await n()}finally{e.isConnected&&(e.disabled=!1,e.textContent=s)}}function re(e,t,n){h(e,o`<div class="error"><span>${t}</span><button class="ghost" data-retry>Retry</button></div>`);let s=e.querySelector("[data-retry]");s&&(s.onclick=n)}function Zt(e,t){return e.actions.find(n=>n.name===t)}function Sn(e){let t=e.send;return t&&(t.status==="scheduled"||t.status==="sending")?t:null}var Qd=[{value:"draft",label:"Draft"},{value:"scheduled",label:"Scheduled"}],Bo="draft,scheduled";function Uo(e){return Z(e,"Creating\u2026",async()=>{try{let{post:t}=await L("/api/posts",{method:"POST",json:{}});location.hash=`#/edit/${t.id}`}catch(t){U(V(t))}})}async function Fo(e,t){ie(t,"Drafts");let n={status:Bo,search:"",sort:"",dir:"desc",offset:0,limit:50};h(e,o`<div class="spread page-head"><h1>Drafts</h1><button class="primary" id="newPost">New post</button></div>
58
+ ${Kt({statuses:Qd,allValue:Bo,searchPlaceholder:"Search subject\u2026"})}
59
59
  <div id="list"><p class="muted">Loading…</p></div>
60
- <div id="postsPager"></div>`);let s=c("#newPost",e);s.onclick=()=>_o(s);let i=c("#list",e),a=c("#postsPager",e),r=new Map,l=0,d=()=>u(!1);async function u(p){let v=++l;try{let x=await R(`/api/posts?${qt(n)}`,{signal:t});if(v!==l)return null;let M=x.posts;if(r=new Map(M.map(A=>[A.id,gn(A)])),!M.length){let A=n.search||n.status&&n.status!==ko;return h(i,o`<p class="muted">${A?"No drafts match.":"No drafts yet. Create your first draft."}</p>`),h(a,o``),x}h(i,o`<div class="table-wrap"><table class="list-table posts-table stacks has-actions"><colgroup><col><col class="c-status"><col class="c-date"><col class="c-date"><col class="c-act"></colgroup><thead><tr>${$e("Title","subject",n)}${$e("Status",null,n)}${$e("Scheduled","send.fire_at",n)}${$e("Updated","updated_at",n)}<th></th></tr></thead><tbody>${M.map(A=>{let H=gn(A),T=H?.status==="sending",m=H&&T?`#/sent/${H.id}`:`#/edit/${A.id}`,y=H?.fire_at??null,C=Gt(A,"delete")?"1":"";return o`<tr class="clickable" data-id="${A.id}" data-target="${m}"><td>${wt(o`<a href="${m}">${A.subject||o`<em>untitled</em>`}</a>`,A)}</td><td>${T?Je("sending"):Je(A.status)}</td><td class="muted when${y?"":" empty"}">${y?W(y):"\u2014"}</td><td class="muted updated">${W(A.updated_at)}</td><td class="act"><button class="icon" data-menu="${A.id}" data-status="${T?"sending":A.status}" data-delete="${C}" data-target="${m}" aria-label="Post actions" aria-haspopup="menu">⋯</button></td></tr>`})}</tbody></table></div>`),st(i,n,d);for(let A of I("tr[data-id]",i))A.onclick=H=>{let T=H.target;T instanceof Element&&T.tagName!=="A"&&!T.closest("[data-menu]")&&A.dataset.target&&(location.hash=A.dataset.target)};for(let A of I("[data-menu]",i))A.onclick=H=>{H.stopPropagation();let T=A.dataset.status,m=A.dataset.target??"",y=[{label:T==="sending"?"Watch send":"Open",onClick:()=>{location.hash=m}}];if(A.dataset.delete&&A.dataset.menu){let C=A.dataset.menu;y.push({label:"Delete draft",danger:!0,onClick:()=>fd(C,d,t)})}Kt(A,y,t)};return ot(a,n,x.page,d),x}catch(x){return!p&&v===l&&oe(i,F(x),()=>f?d():void b()),null}}let f=!1,S=p=>{f=!0,Ot({cursor:p.cursor,sends:[]},{update({sends:v,removed:x}){let M=new Set([...r.values()].flatMap(H=>H?.id??[]));(v.some(H=>r.has(H.post_id)&&md(r.get(H.post_id)??null,H))||x.some(H=>M.has(H)))&&u(!0)},stale:()=>ee(To)},t)},b=async()=>{let p=await u(!1);p&&!f&&S(p)};Wt(e,n,d),await b()}function md(e,t){return e?.id===t.id?t.status!==e.status||t.fire_at!==e.fire_at:t.status==="scheduled"||t.status==="sending"}function fd(e,t,n){let s=pe(o`<h3>Delete draft?</h3><p class="hint">This permanently deletes the draft and its revisions. This can’t be undone.</p><div class="actions"><button type="button" id="dCancel">Cancel</button><button type="button" class="danger" id="dGo">Delete</button></div>`,n),i=c("#dGo",s.el);c("#dCancel",s.el).onclick=s.close,i.onclick=()=>G(i,"Deleting\u2026",async()=>{s.clearError();try{await R(`/api/posts/${e}`,{method:"DELETE"}),s.close(),O("Draft deleted"),t()}catch(a){s.error(F(a))}})}var Lo={pending:"Subscribed but hasn\u2019t clicked the confirmation email.",confirmed:"Receives your posts. They confirmed here, or opted in at the service you imported them from.",unsubscribed:"Left the list. They\u2019re sent nothing until they sign up again, or, unless they left by a complaint or an erasure, you add them back and they confirm."},qr={reader:"They unsubscribed themselves, from the link or the button in your email.",publisher:"You unsubscribed them, when they asked you to.",complaint:"They reported your email as spam. Only their own sign-up brings them back, so you can\u2019t add them: ask them to subscribe through your subscribe page.",erased:"You erased them at their request. Only the address is kept, so it isn\u2019t mailed again, and only their own sign-up brings them back.",import:"The list you imported says they left, without saying why."},jr="The address isn\u2019t sent your posts, whatever its status. The status stays as it was, greyed while the suppression keeps it from taking effect.",qe={bounce:"bounced",import_bounce:"bounced",manual:"blocked"},vn={bounced:"Mail to the address failed, here or at the service it was imported from. You can clear it.",blocked:"Stopped by hand, by you or at the service it was imported from. You can unblock it."},it={unsubscribe:{label:"Unsubscribe",when:"When they ask you to take them off the list. They can rejoin by subscribing again."},block:{label:"Block",when:"When you decide yourself to stop mailing an address. Their status stays as it was, and you can unblock it."},unblock:{label:"Unblock",when:"When you decide to mail an address you blocked again. They receive your posts only if they\u2019re confirmed."},clear:{label:"Clear",when:"When you know a bounce\u2019s cause is gone, such as a reader who tells you their mailbox is fixed. Mail goes again to an address that failed."},erase:{label:"Erase",when:"When they ask you to delete their data. They\u2019re unsubscribed and only their address is kept. It can\u2019t be undone, and they come back only by subscribing themselves."}};function xs(e,t){let n=ve(),s=pe(o`<h3>Add subscriber</h3><p class="hint">Starts the normal double opt-in: they get a confirmation email and won’t receive posts until they confirm.</p>${Vi()}${n?null:o`<label for="addEmail">Email address</label><input type="email" id="addEmail" placeholder="person@example.com">`}<div class="actions"><button type="button" id="aCancel">Cancel</button><button type="button" class="primary" id="aGo">Send confirmation</button></div>`,t),i=c("#aGo",s.el);if(c("#aCancel",s.el).onclick=s.close,i.disabled=n,n){c("#aCancel",s.el).focus();return}let a=c("#addEmail",s.el);a.focus(),i.onclick=()=>G(i,"Adding\u2026",async()=>{s.clearError();let r=gt(a.value);if(!vt(r)){s.error("Enter a valid email address",a);return}try{let l=await R("/api/subscribers",{method:"POST",json:{email:r}});s.close(),O(hd(r,l.action)),e()}catch(l){s.error(F(l),l instanceof te&&l.field==="email"?a:void 0)}})}function hd(e,t){switch(t){case"already_confirmed":return`${e} is already confirmed`;case"suppressed":return`${e} is suppressed, so no confirmation was sent`;case"recently_sent":return`A confirmation went to ${e} a few minutes ago; try again later`;default:return`Confirmation sent to ${e}`}}function Wr(e,t,n){let s=pe(o`<h3>Unsubscribe this subscriber?</h3><p class="hint">Use this when <strong>${e.email}</strong> asks you to take them off the list. They stop receiving posts immediately, and can rejoin by subscribing again. To stop mailing them on your own judgment, block the address instead.</p><div class="actions"><button type="button" id="uCancel">Cancel</button><button type="button" class="danger" id="uGo">Unsubscribe</button></div>`,n),i=c("#uGo",s.el);c("#uCancel",s.el).onclick=s.close,i.onclick=()=>G(i,"Unsubscribing\u2026",async()=>{s.clearError();try{await R(`/api/subscribers/${e.id}/unsubscribe`,{method:"POST"}),s.close(),O(`Unsubscribed ${e.email}`),t()}catch(a){s.error(F(a))}})}function Vr(e,t,n){let s=pe(o`<h3>Block this address?</h3><p class="hint">Stops all mail to <strong>${e.email}</strong>, whatever their status, which stays as it is. Use this when you decide yourself to stop mailing them; if they asked to leave, unsubscribe them instead. You can unblock it later.</p><div class="actions"><button type="button" id="bCancel">Cancel</button><button type="button" class="danger" id="bGo">Block</button></div>`,n),i=c("#bGo",s.el);c("#bCancel",s.el).onclick=s.close,i.onclick=()=>G(i,"Blocking\u2026",async()=>{s.clearError();try{let a=await R("/api/suppressions",{method:"POST",json:{email:e.email}});s.close(),O(a.added?`Blocked ${e.email}`:`${e.email} was already suppressed (${qe[a.suppression.reason]})`),t()}catch(a){s.error(F(a))}})}function Kr(e,t,n){let s=e.status==="confirmed"?"They\u2019re confirmed, so they\u2019ll receive your posts again.":"They\u2019ll receive posts again only once they\u2019re confirmed.",i=pe(o`<h3>Unblock this address?</h3><p class="hint">Undoes the block on <strong>${e.email}</strong>. ${s}</p><div class="actions"><button type="button" id="ubCancel">Cancel</button><button type="button" class="primary" id="ubGo">Unblock</button></div>`,n),a=c("#ubGo",i.el);c("#ubCancel",i.el).onclick=i.close,a.onclick=()=>G(a,"Unblocking\u2026",async()=>{i.clearError();try{await Gr(e),i.close(),O(`Unblocked ${e.email}`),t()}catch(r){i.error(F(r))}})}function Gr(e){return R("/api/suppressions/lift",{method:"POST",json:{email:e.email,reason:e.suppression?.reason}})}function zr(e,t,n){let s=e.status==="confirmed"?"They\u2019re confirmed, so they\u2019ll receive your posts again.":"They\u2019ll receive posts again only once they\u2019re confirmed.",i=pe(o`<h3>Clear this bounce?</h3><p class="hint">Lets mail go again to <strong>${e.email}</strong>, an address where mail failed. Clear it only when you know the reason is gone, such as a reader who tells you their mailbox is fixed. ${s}</p><div class="actions"><button type="button" id="cCancel">Cancel</button><button type="button" class="danger" id="cGo">Clear</button></div>`,n),a=c("#cGo",i.el);c("#cCancel",i.el).onclick=i.close,a.onclick=()=>G(a,"Clearing\u2026",async()=>{i.clearError();try{await Gr(e),i.close(),O(`Cleared the bounce on ${e.email}`),t()}catch(r){i.error(F(r))}})}function Yr(e,t,n){let s=pe(o`<h3>Erase this subscriber?</h3><p class="hint">Unsubscribes <strong>${e.email}</strong> and deletes how they joined and the evidence for it, and past sends show an erased recipient in its place. Only the address is kept, so it’s never mailed again. This can’t be undone. They can still rejoin by subscribing and confirming themselves, but you can’t add them back.</p><div class="actions"><button type="button" id="eCancel">Cancel</button><button type="button" class="danger" id="eGo">Erase</button></div>`,n),i=c("#eGo",s.el);c("#eCancel",s.el).onclick=s.close,i.onclick=()=>G(i,"Erasing\u2026",async()=>{s.clearError();try{let a=await R(`/api/subscribers/${e.id}/erase`,{method:"POST"});s.close(),O(gd(a)),t()}catch(a){s.error(F(a))}})}var bd={bounce:"bounce",import_bounce:"bounce",manual:"block"};function gd({subscriber:e}){let t=e.suppression;return t?`Erased ${e.email}. Its ${bd[t.reason]??"suppression"} still stands`:`Erased ${e.email}`}var vd=1500;function Te(e=!1,t="Copy"){return o`<span>${t}</span>${N(e?"check":"copyout")}`}function yn(e,t){return o`<button type="button" class="copy-btn" data-copy="${e}" aria-label="${t}">${Te()}</button>`}function zt(e,t,n){return o`<div class="block code-block"><div class="block-head"><span class="block-label">${e}</span>${yn(n,`Copy ${e}`)}</div><pre><code>${t}</code></pre></div>`}function Zr(e,t){return o`<div class="code-bare"><pre><code>${e}</code></pre><button type="button" class="copy-btn" data-copy="${t}" data-copy-word="" aria-label="Copy" title="Copy">${Te(!1,"")}</button></div>`}var Ro=new WeakMap;async function wn(e,t){try{await navigator.clipboard.writeText(t)}catch{O("Couldn\u2019t copy to clipboard");return}let n=Ro.get(e),s=n?.label??e.getAttribute("aria-label")??"Copy",i=e.dataset.copyWord;window.clearTimeout(n?.timer),h(e,Te(!0,i)),e.setAttribute("aria-label","Copied"),e.classList.add("copied");let a=window.setTimeout(()=>{h(e,Te(!1,i)),e.setAttribute("aria-label",s),e.classList.remove("copied"),Ro.delete(e)},vd);Ro.set(e,{label:s,timer:a})}function je(e){e.addEventListener("click",t=>{let n=t.target instanceof Element?t.target.closest("[data-copy]"):null;n&&e.contains(n)&&wn(n,n.dataset.copy??"")})}function yd(e,t=!1){let n=[],s=e.filter(m=>Le(m,"missed"));s.length&&n.push({level:"red",text:`${s.length} scheduled send${s.length===1?"":"s"} passed the fire time without going out.`});let i=e.flatMap(m=>{let y=he(m,"wedged");return y?[{s:m,count:y.count}]:[]}),[a]=i;if(a){let m=i.reduce((C,U)=>C+U.count,0),y=m===1?"delivery":"deliveries";n.push({level:"red",text:i.length===1?o`<a href="#/sent/${a.s.id}">${a.s.subject}</a> has ${m} ambiguous ${y} awaiting a decision; resolve ${m===1?"it":"them"} on its page.`:o`${m} ambiguous ${y} across <a href="#/sent">${i.length} sends</a> await a decision; resolve them on the Sent page.`})}let r=ve(),l=e.flatMap(m=>{let y=he(m,"refused");return y?[{s:m,c:y}]:[]}),d=r?l.filter(m=>m.c.cause==="not_connected"):[],u=l.filter(m=>!d.includes(m)),f=m=>m.length===1&&m[0]?o`<a href="#/sent/${m[0].s.id}">${m[0].s.subject}</a>`:o`<a href="#/sent">${m.length} sends</a>`;d.length&&n.push({level:"red",text:o`<span class="dash-not-connected">${is(f(d),d.length)}</span>`});let[S]=u;S&&n.push({level:"red",text:o`${f(u)}: ${S.c.message}`});let b=e.filter(m=>Le(m,"stuck")&&!bn(m)),[p]=b;p&&n.push({level:"amber",text:b.length===1?o`<a href="#/sent/${p.id}">${p.subject}</a>: ${he(p,"stuck")?.message}`:o`<a href="#/sent">${b.length} sends</a> have handed off no one for a while, with no retry or provider problem to explain it.`});let v=e.flatMap(m=>{let y=he(m,"provider_unavailable");return y?.severity==="warn"?[{s:m,c:y}]:[]}),[x]=v;x&&n.push({level:"amber",text:o`<a href="#/sent/${x.s.id}">${x.s.subject}</a>: ${x.c.message}`});let M=e.flatMap(m=>{let y=he(m,"bounce_spike");return y?[{s:m,c:y}]:[]}),[A]=M;A&&n.push({level:"amber",text:o`<a href="#/sent/${A.s.id}">${A.s.subject}</a>: ${A.c.message}`});let H=e.flatMap(m=>{let y=he(m,"no_receipts");return y?[{s:m,c:y}]:[]}),[T]=H;return T&&n.push({level:"amber",text:H.length===1?o`<a href="#/sent/${T.s.id}">${T.s.subject}</a>: ${T.c.message}`:o`<a href="#/sent">${H.length} sends</a> have had no delivery receipt long after they went out. The provider's events may not be reaching this app, so its bounces suppress no one and its complaints unsubscribe no one.`}),r&&!d.length&&!t&&n.push({level:"amber",text:o`<span class="dash-not-connected">No email provider connected, so nothing can be sent yet. ${Ae()} to start sending.</span>`}),n}function wd(e){if(!e.length)return o``;let t=e.some(n=>n.level==="red")?"red":"amber";return o`<div class="health ${t}"><span class="health-dot">⚠️</span><div>${e.map(n=>o`<div>${n.text}</div>`)}</div></div>`}var Jr=e=>e.filter(t=>t.status==="sending"&&!bn(t));async function Co(e,t){se(t,"Dashboard");let n=()=>{t.aborted||ee(Co)};h(e,o`<div class="dash" id="dash"><p class="muted">Loading…</p></div>`);let s=c("#dash",e),i,a,r,l;try{let[_,K,D]=await Promise.all([R("/api/posts?limit=200",{signal:t}),R("/api/sends?limit=200",{signal:t}),R("/api/subscribers",{signal:t})]);i=_.posts,a=K,r=D.counts,l=D.workers_plan_advice}catch(_){oe(s,F(_),n);return}let d=a.sends,u=new Map,f=mo(Q.appConfig),S=Q.appConfig?.deployment??null,b=()=>d.some(_=>(_.status==="sending"||_.status==="sent")&&!_.email_only),p=()=>({named:!!Q.appConfig?.settings.publication?.name?.trim(),onList:r.confirmed+r.pending,archived:b()});if(!i.length){h(s,o`<div class="dash-head"><div><h1>${f.name}</h1>${f.tagline?o`<p class="muted dash-tagline">${f.tagline}</p>`:null}<p class="muted">Let’s get your first post out the door.</p></div></div>${aa(f,S,p(),"checklist")}<section class="dash-section"><h2>API access</h2>${ra(!1)}</section>`),ia(s,n,t);return}let v=()=>!b(),x=()=>v()?aa(f,S,p(),"card"):o``,M=()=>wd(yd(Dt(d,u),v()&&ve())),A=[{label:"Confirmed",emph:!0,v:r.confirmed,filter:"confirmed"},{label:"Pending",v:r.pending,filter:"pending"},{label:"Unsubscribed",v:r.unsubscribed,filter:"unsubscribed"},{label:"Suppressed",v:r.suppressed,filter:"suppressed"}],H=o`<div class="tiles">${A.map(_=>o`<a class="tile${_.emph?" tile-emph":""}" href="#/subscribers/${_.filter}"><span class="tile-n">${_.v}</span><span class="tile-label">${_.label}${_.sub?o`<span class="tile-sub">${_.sub}</span>`:null}</span></a>`)}</div>`,T=i.filter(_=>_.status==="draft").slice(0,5),m=T.length?o`<div class="table-wrap"><table class="dash-drafts"><tbody>${T.map(_=>o`<tr class="clickable" data-id="${_.id}"><td>${wt(o`<a href="#/edit/${_.id}">${_.subject||o`<em>untitled</em>`}</a>`,_)}</td><td class="muted edited">edited ${W(_.updated_at)}</td></tr>`)}</tbody></table></div>`:o`<p class="muted">No drafts in progress.</p>`,y=S?.app_origin||location.origin,C=o`<div class="card pub-card">
61
- <div class="pub-row"><code class="pub-val">${y}</code>${yn(y,"Copy the publication\u2019s address")}</div>
60
+ <div id="postsPager"></div>`);let s=c("#newPost",e);s.onclick=()=>Uo(s);let i=c("#list",e),r=c("#postsPager",e),a=new Map,l=0,d=()=>u(!1);async function u(p){let S=++l;try{let $=await L(`/api/posts?${Vt(n)}`,{signal:t});if(S!==l)return null;let M=$.posts;if(a=new Map(M.map(P=>[P.id,Sn(P)])),!M.length){let P=n.search||n.status&&n.status!==Bo;return h(i,o`<p class="muted">${P?"No drafts match.":"No drafts yet. Create your first draft."}</p>`),h(r,o``),$}h(i,o`<div class="table-wrap"><table class="list-table posts-table stacks has-actions"><colgroup><col><col class="c-status"><col class="c-date"><col class="c-date"><col class="c-act"></colgroup><thead><tr>${Ee("Title","subject",n)}${Ee("Status",null,n)}${Ee("Scheduled","send.fire_at",n)}${Ee("Updated","updated_at",n)}<th></th></tr></thead><tbody>${M.map(P=>{let A=Sn(P),H=A?.status==="sending",y=A&&H?`#/sent/${A.id}`:`#/edit/${P.id}`,w=A?.fire_at??null,T=Zt(P,"delete")?"1":"";return o`<tr class="clickable" data-id="${P.id}" data-target="${y}"><td>${xt(o`<a href="${y}">${P.subject||o`<em>untitled</em>`}</a>`,P)}</td><td>${H?Xe("sending"):Xe(P.status)}</td><td class="muted when${w?"":" empty"}">${w?j(w):"\u2014"}</td><td class="muted updated">${j(P.updated_at)}</td><td class="act"><button class="icon" data-menu="${P.id}" data-status="${H?"sending":P.status}" data-delete="${T}" data-target="${y}" aria-label="Post actions" aria-haspopup="menu">⋯</button></td></tr>`})}</tbody></table></div>`),it(i,n,d);for(let P of N("tr[data-id]",i))P.onclick=A=>{let H=A.target;H instanceof Element&&H.tagName!=="A"&&!H.closest("[data-menu]")&&P.dataset.target&&(location.hash=P.dataset.target)};for(let P of N("[data-menu]",i))P.onclick=A=>{A.stopPropagation();let H=P.dataset.status,y=P.dataset.target??"",w=[{label:H==="sending"?"Watch send":"Open",onClick:()=>{location.hash=y}}];if(P.dataset.delete&&P.dataset.menu){let T=P.dataset.menu;w.push({label:"Delete draft",danger:!0,onClick:()=>eu(T,d,t)})}Yt(P,w,t)};return rt(r,n,$.page,d),$}catch($){return!p&&S===l&&re(i,V($),()=>m?d():void f()),null}}let m=!1,v=p=>{m=!0,Ft({cursor:p.cursor,sends:[]},{update({sends:S,removed:$}){let M=new Set([...a.values()].flatMap(A=>A?.id??[]));(S.some(A=>a.has(A.post_id)&&Xd(a.get(A.post_id)??null,A))||$.some(A=>M.has(A)))&&u(!0)},stale:()=>ee(Fo)},t)},f=async()=>{let p=await u(!1);p&&!m&&v(p)};Gt(e,n,d),await f()}function Xd(e,t){return e?.id===t.id?t.status!==e.status||t.fire_at!==e.fire_at:t.status==="scheduled"||t.status==="sending"}function eu(e,t,n){let s=fe(o`<h3>Delete draft?</h3><p class="hint">This permanently deletes the draft and its revisions. This can’t be undone.</p><div class="actions"><button type="button" id="dCancel">Cancel</button><button type="button" class="danger" id="dGo">Delete</button></div>`,n),i=c("#dGo",s.el);c("#dCancel",s.el).onclick=s.close,i.onclick=()=>Z(i,"Deleting\u2026",async()=>{s.clearError();try{await L(`/api/posts/${e}`,{method:"DELETE"}),s.close(),U("Draft deleted"),t()}catch(r){s.error(V(r))}})}var kt="#/docs/production-access",tu="#/docs/production-access/3-answer-awss-questions",nu="#/docs/ses/5-create-the-apps-aws-key",$n="#/template";function jo(e){return e?.provider==="ses"||!!e?.simulation}async function at(e,t){if(!jo(e))return null;try{return await L("/api/provider",{signal:t})}catch{return null}}var lt=e=>e?.state==="sandbox";function qo(e){let t=e.account?.max_24_hour_send;return typeof t=="number"?`, up to ${t.toLocaleString()} a day`:""}function la(e,t=null){if(e.state==="production")return o`<span>Amazon SES <span class="set-pill ok" id="providerState">Production</span>${t}</span>`;if(e.state!=="sandbox")return e.unknown_reason==="permission"?o`<span>Amazon SES${t}</span><span class="muted" id="providerUnread">To show whether SES is in the sandbox, Kestrel’s AWS key needs permission to read your account. <a class="set-link" href="${nu}">Add the permission</a></span>`:o`Amazon SES${t}`;let n=o`<span class="set-pill warn" id="providerState">Sandbox</span>`,s=e.review==="pending"?o`AWS is reviewing your request for production access. Until then, it mails only addresses verified in SES${qo(e)}.`:e.review==="denied"?o`<span class="set-warn">AWS hasn’t granted production access yet. ${ca(e)}: read its reply and answer there.</span> <a class="set-link" href="${tu}">What AWS asks for</a>`:e.review==="failed"?o`<span class="set-warn">AWS didn’t receive your request for production access.</span> <a class="set-link" href="${kt}">Request it again</a>`:o`<span class="set-warn">It mails only addresses verified in SES${qo(e)}.</span> <a class="set-link" href="${kt}">Request production access</a>`;return o`<span>Amazon SES ${n}${t}</span><span class="muted" id="providerReview">${s}</span>`}function ca(e){return e.review_case?`It has replied in AWS Support, case ${e.review_case}`:"It has replied in AWS Support"}var su={account:"from your SES account",setting:"set by SES_MAX_SEND_RATE",default:"Kestrel\u2019s default"};function da(e){if(!e.send_rate)return null;let{value:t,source:n}=e.send_rate;return o`<span>${t} ${t===1?"email":"emails"} a second${qo(e)} <span class="muted">(${su[n]})</span></span>`}var ou={configuration_set_missing:"Send bounces and complaints to the app",configuration_set_paused:"Send bounces and complaints to the app",key_rejected:"Create the app\u2019s AWS key",sending_disabled:"A problem with Amazon SES",sender_unverified:"Verify your sending hostname",account_probation:"A problem with Amazon SES",bounces_not_routed:"Send bounces and complaints to the app"};function Ps(e){return o`${e.message} <a href="#/docs/${e.docs.slug}/${e.docs.anchor}">${ou[e.code]}</a>`}var xn=e=>e.severity==="error";function ua(){return o`Amazon SES is still in the sandbox, so it mails only addresses verified in SES. <a href="${kt}">Request production access</a>`}function pa(e,t){return e?.state==="production"?null:e?.state==="sandbox"&&e.review==="pending"?"Waiting for AWS to grant production access.":e?.state==="sandbox"&&e.review==="denied"?`AWS hasn\u2019t granted it yet. ${ca(e)}: answer there.`:e?.state==="sandbox"&&e.review==="failed"?"AWS didn\u2019t receive your request. Ask again.":t?e?.state==="unknown"&&e.unknown_reason==="permission"?"Kestrel can\u2019t read your SES account, so the SES console\u2019s account dashboard says whether AWS granted it.":null:"Name your publication first: AWS\u2019s reviewer looks at it."}function En(e){return e?.sending?.state==="refusing"?e.sending.refusal:null}function ma(e){return e.found_by==="account_check"?`${e.error} ${e.advice}`:`SES says: ${e.error.replace(/[.!?]?$/,".")} ${e.advice}`}function fa(e){return o`<span class="dash-not-going-out"><strong>Email isn’t going out, and signups are paused.</strong> ${ma(e)} Then <a href="${$n}">send a test email</a>: once SES takes one, signups reopen.</span>`}function ha(){return o`Signups are paused: Amazon SES is refusing email, including confirmations. <a href="#/">See what to fix</a>`}function ba(e,t){let n=e.sending;if(!n)return null;let s=n.last_accepted?o`<span class="muted" id="providerLastAccepted">SES accepted an email ${t(n.last_accepted.at)}.</span>`:null;return n.state==="refusing"&&n.refusal?{pill:o`<span class="set-pill danger" id="providerSending">Refusing</span>`,line:o`<span class="set-error">${ma(n.refusal)} Then <a class="set-link" href="${$n}">send a test email</a>.</span>${s}`}:n.state==="unproven"?{pill:o`<span class="set-pill" id="providerSending">Not proven yet</span>`,line:o`<span>SES hasn’t sent anything yet, so signups are closed. <a class="set-link" href="${$n}">Send a test email</a></span>`}:{pill:null,line:s??o``}}var Wo={pending:"Subscribed but hasn\u2019t clicked the confirmation email.",confirmed:"Receives your posts. They confirmed here, or opted in at the service you imported them from.",unsubscribed:"Left the list. They\u2019re sent nothing until they sign up again, or, unless they left by a complaint or an erasure, you add them back and they confirm."},ga={reader:"They unsubscribed themselves, from the link or the button in your email.",publisher:"You unsubscribed them, when they asked you to.",complaint:"They reported your email as spam. Only their own sign-up brings them back, so you can\u2019t add them: ask them to subscribe through your subscribe page.",erased:"You erased them at their request. Only the address is kept, so it isn\u2019t mailed again, and only their own sign-up brings them back.",import:"The list you imported says they left, without saying why."},va="The address isn\u2019t sent your posts, whatever its status. The status stays as it was, greyed while the suppression keeps it from taking effect.",je={bounce:"bounced",import_bounce:"bounced",manual:"blocked"},kn={bounced:"Mail to the address failed, here or at the service it was imported from. You can clear it.",blocked:"Stopped by hand, by you or at the service it was imported from. You can unblock it."},ct={unsubscribe:{label:"Unsubscribe",when:"When they ask you to take them off the list. They can rejoin by subscribing again."},block:{label:"Block",when:"When you decide yourself to stop mailing an address. Their status stays as it was, and you can unblock it."},unblock:{label:"Unblock",when:"When you decide to mail an address you blocked again. They receive your posts only if they\u2019re confirmed."},clear:{label:"Clear",when:"When you know a bounce\u2019s cause is gone, such as a reader who tells you their mailbox is fixed. Mail goes again to an address that failed."},erase:{label:"Erase",when:"When they ask you to delete their data. They\u2019re unsubscribed and only their address is kept. It can\u2019t be undone, and they come back only by subscribing themselves."}};function Ms(e,t){let n=ge(),s=fe(o`<h3>Add subscriber</h3><p class="hint">Starts the normal double opt-in: they get a confirmation email and won’t receive posts until they confirm.</p>${ur()}${n?null:o`<label for="addEmail">Email address</label><input type="email" id="addEmail" placeholder="person@example.com">`}<div class="actions"><button type="button" id="aCancel">Cancel</button><button type="button" class="primary" id="aGo">Send confirmation</button></div>`,t),i=c("#aGo",s.el);if(c("#aCancel",s.el).onclick=s.close,i.disabled=n,n){c("#aCancel",s.el).focus();return}let r=c("#addEmail",s.el);r.focus(),i.onclick=()=>Z(i,"Adding\u2026",async()=>{s.clearError();let a=wt(r.value);if(!St(a)){s.error("Enter a valid email address",r);return}try{let l=await L("/api/subscribers",{method:"POST",json:{email:a}});s.close(),U(iu(a,l.action)),e()}catch(l){s.error(V(l),l instanceof te&&l.field==="email"?r:void 0)}})}function iu(e,t){switch(t){case"already_confirmed":return`${e} is already confirmed`;case"suppressed":return`${e} is suppressed, so no confirmation was sent`;case"recently_sent":return`A confirmation went to ${e} a few minutes ago; try again later`;default:return`Confirmation sent to ${e}`}}function ya(e,t,n){let s=fe(o`<h3>Unsubscribe this subscriber?</h3><p class="hint">Use this when <strong>${e.email}</strong> asks you to take them off the list. They stop receiving posts immediately, and can rejoin by subscribing again. To stop mailing them on your own judgment, block the address instead.</p><div class="actions"><button type="button" id="uCancel">Cancel</button><button type="button" class="danger" id="uGo">Unsubscribe</button></div>`,n),i=c("#uGo",s.el);c("#uCancel",s.el).onclick=s.close,i.onclick=()=>Z(i,"Unsubscribing\u2026",async()=>{s.clearError();try{await L(`/api/subscribers/${e.id}/unsubscribe`,{method:"POST"}),s.close(),U(`Unsubscribed ${e.email}`),t()}catch(r){s.error(V(r))}})}function wa(e,t,n){let s=fe(o`<h3>Block this address?</h3><p class="hint">Stops all mail to <strong>${e.email}</strong>, whatever their status, which stays as it is. Use this when you decide yourself to stop mailing them; if they asked to leave, unsubscribe them instead. You can unblock it later.</p><div class="actions"><button type="button" id="bCancel">Cancel</button><button type="button" class="danger" id="bGo">Block</button></div>`,n),i=c("#bGo",s.el);c("#bCancel",s.el).onclick=s.close,i.onclick=()=>Z(i,"Blocking\u2026",async()=>{s.clearError();try{let r=await L("/api/suppressions",{method:"POST",json:{email:e.email}});s.close(),U(r.added?`Blocked ${e.email}`:`${e.email} was already suppressed (${je[r.suppression.reason]})`),t()}catch(r){s.error(V(r))}})}function Sa(e,t,n){let s=e.status==="confirmed"?"They\u2019re confirmed, so they\u2019ll receive your posts again.":"They\u2019ll receive posts again only once they\u2019re confirmed.",i=fe(o`<h3>Unblock this address?</h3><p class="hint">Undoes the block on <strong>${e.email}</strong>. ${s}</p><div class="actions"><button type="button" id="ubCancel">Cancel</button><button type="button" class="primary" id="ubGo">Unblock</button></div>`,n),r=c("#ubGo",i.el);c("#ubCancel",i.el).onclick=i.close,r.onclick=()=>Z(r,"Unblocking\u2026",async()=>{i.clearError();try{await $a(e),i.close(),U(`Unblocked ${e.email}`),t()}catch(a){i.error(V(a))}})}function $a(e){return L("/api/suppressions/lift",{method:"POST",json:{email:e.email,reason:e.suppression?.reason}})}function xa(e,t,n){let s=e.status==="confirmed"?"They\u2019re confirmed, so they\u2019ll receive your posts again.":"They\u2019ll receive posts again only once they\u2019re confirmed.",i=fe(o`<h3>Clear this bounce?</h3><p class="hint">Lets mail go again to <strong>${e.email}</strong>, an address where mail failed. Clear it only when you know the reason is gone, such as a reader who tells you their mailbox is fixed. ${s}</p><div class="actions"><button type="button" id="cCancel">Cancel</button><button type="button" class="danger" id="cGo">Clear</button></div>`,n),r=c("#cGo",i.el);c("#cCancel",i.el).onclick=i.close,r.onclick=()=>Z(r,"Clearing\u2026",async()=>{i.clearError();try{await $a(e),i.close(),U(`Cleared the bounce on ${e.email}`),t()}catch(a){i.error(V(a))}})}function Ea(e,t,n){let s=fe(o`<h3>Erase this subscriber?</h3><p class="hint">Unsubscribes <strong>${e.email}</strong> and deletes how they joined and the evidence for it, and past sends show an erased recipient in its place. Only the address is kept, so it’s never mailed again. This can’t be undone. They can still rejoin by subscribing and confirming themselves, but you can’t add them back.</p><div class="actions"><button type="button" id="eCancel">Cancel</button><button type="button" class="danger" id="eGo">Erase</button></div>`,n),i=c("#eGo",s.el);c("#eCancel",s.el).onclick=s.close,i.onclick=()=>Z(i,"Erasing\u2026",async()=>{s.clearError();try{let r=await L(`/api/subscribers/${e.id}/erase`,{method:"POST"});s.close(),U(au(r)),t()}catch(r){s.error(V(r))}})}var ru={bounce:"bounce",import_bounce:"bounce",manual:"block"};function au({subscriber:e}){let t=e.suppression;return t?`Erased ${e.email}. Its ${ru[t.reason]??"suppression"} still stands`:`Erased ${e.email}`}var lu=1500;function Te(e=!1,t="Copy"){return o`<span>${t}</span>${O(e?"check":"copyout")}`}function _n(e,t){return o`<button type="button" class="copy-btn" data-copy="${e}" aria-label="${t}">${Te()}</button>`}function Jt(e,t,n){return o`<div class="block code-block"><div class="block-head"><span class="block-label">${e}</span>${_n(n,`Copy ${e}`)}</div><pre><code>${t}</code></pre></div>`}function ka(e,t){return o`<div class="code-bare"><pre><code>${e}</code></pre><button type="button" class="copy-btn" data-copy="${t}" data-copy-word="" aria-label="Copy" title="Copy">${Te(!1,"")}</button></div>`}var Vo=new WeakMap;async function Tn(e,t){try{await navigator.clipboard.writeText(t)}catch{U("Couldn\u2019t copy to clipboard");return}let n=Vo.get(e),s=n?.label??e.getAttribute("aria-label")??"Copy",i=e.dataset.copyWord;window.clearTimeout(n?.timer),h(e,Te(!0,i)),e.setAttribute("aria-label","Copied"),e.classList.add("copied");let r=window.setTimeout(()=>{h(e,Te(!1,i)),e.setAttribute("aria-label",s),e.classList.remove("copied"),Vo.delete(e)},lu);Vo.set(e,{label:s,timer:r})}function We(e){e.addEventListener("click",t=>{let n=t.target instanceof Element?t.target.closest("[data-copy]"):null;n&&e.contains(n)&&Tn(n,n.dataset.copy??"")})}var Ko="Connect Amazon SES",Ln="Send a test email",_a="Schedule your first post",Is=e=>`After ${e}`,cu="SES is refusing. See why above.",du="The last notification didn\u2019t arrive. See why above.",Ta=(e,t,n)=>`${e.toLocaleString()} ${e===1?t:n}`;function uu(e){let t=e.provider,n=t?.sending??null,s=lt(t),i=[];i.push({key:"connect",title:Ko,state:e.notConnected?"todo":"done",hint:e.notConnected?"Nothing can be sent, and signups stay closed, until SES is connected.":e.connectedTo}),i.push(e.notConnected?{key:"test",title:Ln,state:"blocked",hint:Is(Ko)}:n?.state==="working"?{key:"test",title:Ln,state:"done",hint:n.last_accepted?`SES accepted an email ${j(n.last_accepted.at)}.`:"SES is accepting email."}:n?.state==="refusing"?{key:"test",title:Ln,state:"attention",hint:cu}:{key:"test",title:Ln,state:"todo",hint:n?`SES is connected but hasn\u2019t sent anything yet. Send one to ${s?"an address verified in SES":"yourself"}.`:"Send one to yourself, and check it arrives."}),i.push({key:"name",title:"Name your publication",state:e.named?"done":"todo",hint:e.named?`Named \u201C${e.name}\u201D.`:`Currently \u201C${e.name}\u201D.`}),i.push({key:"notify",title:"Get notified",state:e.notifyTo?e.notifyFailed?"attention":"done":"todo",hint:e.notifyTo?e.notifyFailed?du:`Notifications go to ${Ta(e.notifyTo,"address","addresses")}.`:null}),(e.notConnected||e.sesAccount)&&i.push({key:"access",title:"Request production access",state:t?.state==="production"?"done":s&&t?.review==="pending"?"waiting":"todo",hint:t?.state==="production"?"AWS granted it.":pa(t,e.named)}),i.push({key:"list",title:"Bring your existing list",state:e.onList?"done":"todo",hint:e.onList?`${Ta(e.onList,"subscriber","subscribers")} on your list.`:"Optional."}),i.push({key:"write",title:"Write your first post",state:e.firstPost!==null?"done":"todo",hint:e.firstPost!==null?`\u201C${e.firstPost||"Untitled"}\u201D.`:null}),i.push({key:"schedule",title:_a,state:e.notConnected?"blocked":e.firstSend?"done":"todo",hint:e.notConnected?Is(Ko):e.firstSend?`Goes out ${j(e.firstSend.fire_at)}.`:s&&n?.state==="working"?"Best after AWS grants access: until then it reaches only verified addresses.":null});let r=e.firstSend,a=r?r.tested_at!==null&&(r.remade_at??0)<=r.tested_at:!1;i.push({key:"post_test",title:"Send a test email for your first post",state:r?a?"done":"todo":"blocked",hint:r?a?"The email that goes out has been tested.":`\u201C${r.subject}\u201D goes out ${j(r.fire_at)}. Send yourself a test of it first.`:Is(_a)});let l=e.notConnected||t!==null&&t.signups!=="open";return i.push({key:"share",title:"Share your subscribe link",state:l?"blocked":"todo",hint:l?Is(Ln):Go(e)?null:"Share it once AWS grants production access."}),i}function pu(e,t,n){if(e.state==="blocked")return null;if(e.state==="done")switch(e.key){case"connect":case"access":case"write":case"schedule":return null;case"list":return o`<button data-nav="#/subscribers">Subscribers</button>`}let s=n?"primary":"";switch(e.key){case"connect":return o`<button class="${s}" data-nav="${Ro}">Connect</button>`;case"test":return o`<button class="${s}" data-nav="${$n}">Send test email</button>`;case"name":case"notify":return o`<button class="${s}" data-nav="#/settings">Settings</button>`;case"access":return o`<button class="${s}" data-nav="${kt}">Docs</button>`;case"list":return o`<button class="${s}" data-nav="#/subscribers/import">Import</button>`;case"write":return o`<button class="${s}" data-act="new-post">New post</button>`;case"schedule":return null;case"post_test":return t.firstSend?o`<button class="${s}" data-nav="#/edit/${t.firstSend.post_id}">Send test</button>`:null;case"share":return Go(t)?o`<button class="${s}" type="button" data-copy="${t.subscribeUrl}" aria-label="Copy the subscribe link">${Te()}</button>`:null}}function La(e,t,n=!1){let s=uu(e),i=s.filter(d=>d.state==="done"),r=n?s:s.filter(d=>d.state!=="done"),a=s.find(d=>(d.state==="todo"||d.state==="attention")&&d.key!=="list"),l=d=>o`<li class="setup-${d.key.replace("_","-")} setup-${d.state}"><div class="setup-step-main"><strong>${d.title}</strong>${d.hint?o`<span class="muted setup-hint">${d.hint}</span>`:null}${d.key==="share"&&d.state!=="blocked"&&Go(e)?o`<code class="setup-url">${e.subscribeUrl}</code>`:null}</div>${pu(d,e,t==="checklist"&&d===a)}</li>`;return o`<div class="card setup${t==="card"?" setup-card":""}">
61
+ <h2 class="setup-title">${t==="card"?"Finish setting up":"Set up your publication"}</h2>
62
+ ${i.length?o`<button type="button" class="setup-fold" data-act="toggle-done" aria-controls="setupSteps" aria-expanded="${n?"true":"false"}" aria-label="${n?"Hide":"Show"} ${i.length} done ${i.length===1?"step":"steps"}"><span class="setup-fold-mark" aria-hidden="true">✓</span><span>${i.length} done</span></button>`:null}
63
+ <ol class="setup-steps" id="setupSteps">${r.map(l)}</ol>
64
+ </div>`}var Go=e=>!e.sesAccount||e.provider?.state==="production";function Ra(e){return e?.provider==="ses"?e.aws_region?`Sends through Amazon SES in ${e.aws_region}.`:"Sends through Amazon SES.":"Sends through local development\u2019s stand-in, which delivers nothing."}function Ca(e){return e.filter(t=>t.status==="scheduled"&&!t.email_only).sort((t,n)=>t.fire_at-n.fire_at)[0]??null}function mu(e,t=!1,n=null,s=!1,i=null){let r=[],a=e.filter(R=>Re(R,"missed"));a.length&&r.push({level:"red",text:`${a.length} scheduled send${a.length===1?"":"s"} passed the fire time without going out.`});let l=e.flatMap(R=>{let F=he(R,"wedged");return F?[{s:R,count:F.count}]:[]}),[d]=l;if(d){let R=l.reduce((K,b)=>K+b.count,0),F=R===1?"delivery":"deliveries";r.push({level:"red",text:l.length===1?o`<a href="#/sent/${d.s.id}">${d.s.subject}</a> has ${R} ambiguous ${F} awaiting a decision; resolve ${R===1?"it":"them"} on its page.`:o`${R} ambiguous ${F} across <a href="#/sent">${l.length} sends</a> await a decision; resolve them on the Sent page.`})}let u=ge(),m=e.flatMap(R=>{let F=he(R,"refused");return F?[{s:R,c:F}]:[]}),v=u?m.filter(R=>R.c.cause==="not_connected"):[],f=m.filter(R=>!v.includes(R)),p=R=>R.length===1&&R[0]?o`<a href="#/sent/${R[0].s.id}">${R[0].s.subject}</a>`:o`<a href="#/sent">${R.length} sends</a>`;v.length&&r.push({level:"red",text:o`<span class="dash-not-connected">${fs(p(v),v.length)}</span>`});let[S]=f;S&&r.push({level:"red",text:o`${p(f)}: ${S.c.message}`});let $=e.filter(R=>Re(R,"stuck")&&!wn(R)),[M]=$;M&&r.push({level:"amber",text:$.length===1?o`<a href="#/sent/${M.id}">${M.subject}</a>: ${he(M,"stuck")?.message}`:o`<a href="#/sent">${$.length} sends</a> have handed off no one for a while, with no retry or provider problem to explain it.`});let P=e.flatMap(R=>{let F=he(R,"provider_unavailable");return F?.severity==="warn"?[{s:R,c:F}]:[]}),[A]=P;A&&r.push({level:"amber",text:o`<a href="#/sent/${A.s.id}">${A.s.subject}</a>: ${A.c.message}`});let H=e.flatMap(R=>{let F=he(R,"bounce_spike");return F?[{s:R,c:F}]:[]}),[y]=H;y&&r.push({level:"amber",text:o`<a href="#/sent/${y.s.id}">${y.s.subject}</a>: ${y.c.message}`});let w=e.flatMap(R=>{let F=he(R,"no_receipts");return F?[{s:R,c:F}]:[]}),[T]=w;T&&r.push({level:"amber",text:w.length===1?o`<a href="#/sent/${T.s.id}">${T.s.subject}</a>: ${T.c.message}`:o`<a href="#/sent">${w.length} sends</a> have had no delivery receipt long after they went out. The provider's events may not be reaching this app, so its bounces suppress no one and its complaints unsubscribe no one.`}),u&&!v.length&&!t&&r.push({level:"amber",text:o`<span class="dash-not-connected">No email provider connected, so nothing can be sent yet. ${Ae()} to start sending.</span>`});let D=En(n);D&&r.push({level:"red",text:fa(D)});for(let R of n?.warnings??[])D&&xn(R)||r.push({level:xn(R)?"red":"amber",text:o`<span class="dash-provider-warning">${Ps(R)}</span>`});return lt(n)&&!s&&r.push({level:"amber",text:o`<span class="dash-sandbox">${ua()}</span>`}),i&&r.push({level:"amber",text:o`<span class="dash-notify-failed">Kestrel’s last notification didn’t arrive: ${i.error.replace(/[.!?]?$/,".")} Check <a href="#/settings">Settings → Notifications</a>.</span>`}),r}function fu(e){if(!e.length)return o``;let t=e.some(n=>n.level==="red")?"red":"amber";return o`<div class="health ${t}"><span class="health-dot">⚠️</span><div>${e.map(n=>o`<div>${n.text}</div>`)}</div></div>`}var Aa=e=>e.filter(t=>t.status==="sending"&&!wn(t));async function zo(e,t){ie(t,"Dashboard");let n=()=>{t.aborted||ee(zo)};h(e,o`<div class="dash" id="dash"><p class="muted">Loading…</p></div>`);let s=c("#dash",e),i,r,a,l,d;try{let[k,G,q,ne]=await Promise.all([L("/api/posts?limit=200",{signal:t}),L("/api/sends?limit=200",{signal:t}),L("/api/subscribers",{signal:t}),at(Y.appConfig?.deployment,t)]);d=ne,i=k.posts,r=G,a=q.counts,l=q.workers_plan_advice}catch(k){re(s,V(k),n);return}let u=r.sends,m=new Map,v=_o(Y.appConfig),f=Y.appConfig?.deployment??null,p=()=>u.some(k=>(k.status==="sending"||k.status==="sent")&&!k.email_only),S=()=>{let k=Y.appConfig,G=k?.notification_status.last_failure??null;return{notConnected:ge(),sesAccount:!ge()&&jo(f),provider:d,name:v.name,named:!!k?.settings.publication?.name?.trim(),notifyTo:k?.settings.notifications.to.length??0,notifyFailed:G!==null,onList:a.confirmed+a.pending,connectedTo:Ra(f),firstPost:i.filter(q=>!q.email_only).sort((q,ne)=>q.created_at-ne.created_at)[0]?.subject??null,firstSend:Ca(u),subscribeUrl:`${f?.app_origin||location.origin}/subscribe`}},$=()=>!p(),M=()=>fu(mu(qt(u,m),$()&&ge(),d,$(),Y.appConfig?.notification_status.last_failure??null)),P=!1,A=(k=!1)=>{let G=c("#dashSetup",s),q=k||document.activeElement?.closest("#dashSetup [data-act='toggle-done']")!=null,ne=i.length?"card":"checklist";h(G,ne==="checklist"||$()?La(S(),ne,P):o``),Fa(G,n,t);let He=G.querySelector("[data-act='toggle-done']");He&&(He.onclick=()=>{P=!P,A(!0)},q&&He.focus())};if(!i.length){h(s,o`<div class="dash-head"><div><h1>${v.name}</h1>${v.tagline?o`<p class="muted dash-tagline">${v.tagline}</p>`:null}<p class="muted">Let’s get your first post out the door.</p></div></div><div id="dashHealth">${M()}</div><div id="dashSetup"></div><section class="dash-section"><h2>API access</h2>${Ua(!1)}</section>`),A(),Ba(s,n,t);return}let H=[{label:"Confirmed",emph:!0,v:a.confirmed,filter:"confirmed"},{label:"Pending",v:a.pending,filter:"pending"},{label:"Unsubscribed",v:a.unsubscribed,filter:"unsubscribed"},{label:"Suppressed",v:a.suppressed,filter:"suppressed"}],y=o`<div class="tiles">${H.map(k=>o`<a class="tile${k.emph?" tile-emph":""}" href="#/subscribers/${k.filter}"><span class="tile-n">${k.v}</span><span class="tile-label">${k.label}${k.sub?o`<span class="tile-sub">${k.sub}</span>`:null}</span></a>`)}</div>`,w=i.filter(k=>k.status==="draft").slice(0,5),T=w.length?o`<div class="table-wrap"><table class="dash-drafts"><tbody>${w.map(k=>o`<tr class="clickable" data-id="${k.id}"><td>${xt(o`<a href="#/edit/${k.id}">${k.subject||o`<em>untitled</em>`}</a>`,k)}</td><td class="muted edited">edited ${j(k.updated_at)}</td></tr>`)}</tbody></table></div>`:o`<p class="muted">No drafts in progress.</p>`,D=f?.app_origin||location.origin,R=o`<div class="card pub-card">
65
+ <div class="pub-row"><code class="pub-val">${D}</code>${_n(D,"Copy the publication\u2019s address")}</div>
62
66
  <div class="pub-foot"><a href="/" target="_blank" rel="noopener">View publication&nbsp;↗</a></div>
63
- </div>`,U=i.some(_=>_.author_client===Gn||_.author_client===zn),J=ra(U),z=o`<div class="row quick-actions"><button data-act="new-post">New post</button><button data-act="add-sub">Add subscriber</button><button data-nav="#/settings">Edit publication</button></div>`;h(s,o`
67
+ </div>`,F=i.some(k=>k.author_client===ns||k.author_client===ss),K=Ua(F),b=o`<div class="row quick-actions"><button data-act="new-post">New post</button><button data-act="add-sub">Add subscriber</button><button data-nav="#/settings">Edit publication</button></div>`;h(s,o`
64
68
  <div class="dash-head">
65
- <div><h1>${f.name}</h1>${f.tagline?o`<p class="muted dash-tagline">${f.tagline}</p>`:null}</div>
69
+ <div><h1>${v.name}</h1>${v.tagline?o`<p class="muted dash-tagline">${v.tagline}</p>`:null}</div>
66
70
  <button class="primary" data-act="new-post">New post</button>
67
71
  </div>
68
72
  <div id="dashHealth">${M()}</div>
69
- <div id="dashSetup">${x()}</div>
70
- <div id="dashActive">${sa(Jr(Dt(d,u)))}</div>
71
- <section class="dash-section"><h2>Subscribers</h2>${H}${l?o`<p class="workers-plan" id="dashWorkersPlan" role="status">${l}</p>`:null}</section>
73
+ <div id="dashSetup"></div>
74
+ <div id="dashActive">${Oa(Aa(qt(u,m)))}</div>
75
+ <section class="dash-section"><h2>Subscribers</h2>${y}${l?o`<p class="workers-plan" id="dashWorkersPlan" role="status">${l}</p>`:null}</section>
72
76
  <div class="dash-cols">
73
- <section class="dash-section"><h2>Scheduled</h2><div id="dashScheduled">${ta(Qr(d))}</div></section>
74
- <section class="dash-section"><h2>Drafts</h2>${m}</section>
77
+ <section class="dash-section"><h2>Scheduled</h2><div id="dashScheduled">${Ia(Ha(u))}</div></section>
78
+ <section class="dash-section"><h2>Drafts</h2>${T}</section>
75
79
  </div>
76
- <section class="dash-section"><h2>Sent</h2><div id="dashSent">${Xr(d)}</div></section>
77
- <section class="dash-section"><h2>Quick actions</h2>${z}</section>
80
+ <section class="dash-section"><h2>Sent</h2><div id="dashSent">${Pa(u)}</div></section>
81
+ <section class="dash-section"><h2>Quick actions</h2>${b}</section>
78
82
  <div class="dash-cols">
79
- <section class="dash-section"><h2>Publication</h2>${C}</section>
80
- <section class="dash-section"><h2>API access</h2>${J}</section>
81
- </div>`),ia(s,n,t);for(let _ of I("tr[data-id]",s))_.onclick=K=>{let D=K.target;D instanceof Element&&D.tagName!=="A"&&!D.closest("button")&&(location.hash=`#/edit/${_.dataset.id}`)};ea(s),oa(s),na(s);let q=Ss(s,t);q();let g=0,E=async()=>{let _=++g;try{let K=await R("/api/sends?limit=200",{signal:t});if(_!==g)return;d=K.sends,h(c("#dashScheduled",s),ta(Qr(d))),na(s),q(),h(c("#dashSent",s),Xr(d)),ea(s),h(c("#dashSetup",s),x()),la(c("#dashSetup",s),n,t),L()}catch{}},L=()=>{let _=Dt(d,u);h(c("#dashHealth",s),M()),h(c("#dashActive",s),sa(Jr(_))),oa(s),Sd(s,[...u.values()])},$=_=>_==="scheduled"||_==="due";Ot(a,{update:_=>{for(let K of _.sends)u.set(K.id,K);for(let K of _.removed)u.delete(K);L(),(_.changes.length||_.removed.length||_.sends.some(K=>$(nt(K))))&&E()},stale:n},t)}var Qr=e=>e.filter(t=>t.status==="scheduled").sort((t,n)=>t.fire_at-n.fire_at);function Xr(e){let t=e.filter(n=>n.status==="sent"||n.status==="sending").slice(0,5);return t.length?o`<div class="table-wrap"><table class="dash-sent"><thead><tr><th>Subject</th><th>Status</th><th class="num">Recipients</th><th class="num">Delivered</th><th></th></tr></thead><tbody>${t.map(n=>{let s=n.email_only?n.links.unlisted:n.links.archive;return o`<tr class="clickable" data-send="${n.id}"><td>${wt(o`<a href="#/sent/${n.id}">${n.subject}</a>`,n)}</td><td>${Je(n.status)}</td><td class="num">${n.audience.count.toLocaleString()}</td><td class="num delivered">${Ut(n.counts)}</td><td class="act">${s?o`<a class="ghost-link" href="${s}" target="_blank" rel="noopener">${n.email_only?o`Web version&nbsp;↗`:o`Archive&nbsp;↗`}</a>`:null}</td></tr>`})}</tbody></table></div>`:o`<p class="muted">No sends yet.</p>`}function ea(e){for(let t of I("tr[data-send]",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/sent/${t.dataset.send}`)}}function Sd(e,t){for(let n of t){let s=I("#dashSent tr[data-send]",e).find(i=>i.dataset.send===n.id)?.querySelector("td.delivered");s&&h(s,Ut(n.counts))}}function ta(e){if(!e.length)return o`<p class="muted">Nothing scheduled.</p>`;let t=as("card");return o`${e.map(n=>o`<div class="card spread clickable nextup sched-card" data-post="${n.post_id}"><div><a class="card-link sched-subj" href="#/edit/${n.post_id}">${n.subject}</a><div class="muted">${ws(n)} · ${W(n.fire_at)} · ${n.audience.count} recipients${ys(n)}</div>${t}${Le(n,"remade")?o`<div class="sched-remade-mark">Look changed since your last test</div>`:null}</div></div>`)}`}function na(e){for(let t of I("#dashScheduled .nextup",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/edit/${t.dataset.post}`)}}function sa(e){return e.length?o`<section class="dash-section"><h2>Active send${e.length===1?"":"s"}</h2>${e.map(t=>$s(t,{stuckNote:!1}))}</section>`:o``}function oa(e){for(let t of I("#dashActive .active-card[data-watch]",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/sent/${t.dataset.watch}`)}}function ia(e,t,n){la(e,t,n),je(e)}function la(e,t,n){for(let s of I("[data-nav]",e))s.onclick=()=>{location.hash=s.dataset.nav??""};for(let s of I("[data-act='new-post']",e))s.onclick=()=>_o(s);for(let s of I("[data-act='add-sub']",e))s.onclick=()=>xs(t,n)}function ra(e){return e?o`<div class="card pub-card">
83
+ <section class="dash-section"><h2>Publication</h2>${R}</section>
84
+ <section class="dash-section"><h2>API access</h2>${K}</section>
85
+ </div>`),A(),Ba(s,n,t);for(let k of N("tr[data-id]",s))k.onclick=G=>{let q=G.target;q instanceof Element&&q.tagName!=="A"&&!q.closest("button")&&(location.hash=`#/edit/${k.dataset.id}`)};Ma(s),Da(s),Na(s);let E=Cs(s,t);E();let C=0,x=async()=>{let k=++C;try{let G=await L("/api/sends?limit=200",{signal:t});if(k!==C)return;u=G.sends,h(c("#dashScheduled",s),Ia(Ha(u))),Na(s),E(),h(c("#dashSent",s),Pa(u)),Ma(s),A(),W()}catch{}},W=()=>{let k=qt(u,m);h(c("#dashHealth",s),M()),h(c("#dashActive",s),Oa(Aa(k))),Da(s),hu(s,[...m.values()])},oe=k=>k==="scheduled"||k==="due";Ft(r,{update:k=>{for(let G of k.sends)m.set(G.id,G);for(let G of k.removed)m.delete(G);W(),(k.changes.length||k.removed.length||k.sends.some(G=>oe(ot(G))))&&x()},stale:n},t)}var Ha=e=>e.filter(t=>t.status==="scheduled").sort((t,n)=>t.fire_at-n.fire_at);function Pa(e){let t=e.filter(n=>n.status==="sent"||n.status==="sending").slice(0,5);return t.length?o`<div class="table-wrap"><table class="dash-sent"><thead><tr><th>Subject</th><th>Status</th><th class="num">Recipients</th><th class="num">Delivered</th><th></th></tr></thead><tbody>${t.map(n=>{let s=n.email_only?n.links.unlisted:n.links.archive;return o`<tr class="clickable" data-send="${n.id}"><td>${xt(o`<a href="#/sent/${n.id}">${n.subject}</a>`,n)}</td><td>${Xe(n.status)}</td><td class="num">${n.audience.count.toLocaleString()}</td><td class="num delivered">${jt(n.counts)}</td><td class="act">${s?o`<a class="ghost-link" href="${s}" target="_blank" rel="noopener">${n.email_only?o`Web version&nbsp;↗`:o`Archive&nbsp;↗`}</a>`:null}</td></tr>`})}</tbody></table></div>`:o`<p class="muted">No sends yet.</p>`}function Ma(e){for(let t of N("tr[data-send]",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/sent/${t.dataset.send}`)}}function hu(e,t){for(let n of t){let s=N("#dashSent tr[data-send]",e).find(i=>i.dataset.send===n.id)?.querySelector("td.delivered");s&&h(s,jt(n.counts))}}function Ia(e){if(!e.length)return o`<p class="muted">Nothing scheduled.</p>`;let t=bs("card");return o`${e.map(n=>o`<div class="card spread clickable nextup sched-card" data-post="${n.post_id}"><div><a class="card-link sched-subj" href="#/edit/${n.post_id}">${n.subject}</a><div class="muted">${Rs(n)} · ${j(n.fire_at)} · ${n.audience.count} recipients${Ls(n)}</div>${t}${Re(n,"remade")?o`<div class="sched-remade-mark">Look changed since your last test</div>`:null}</div></div>`)}`}function Na(e){for(let t of N("#dashScheduled .nextup",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/edit/${t.dataset.post}`)}}function Oa(e){return e.length?o`<section class="dash-section"><h2>Active send${e.length===1?"":"s"}</h2>${e.map(t=>As(t,{stuckNote:!1}))}</section>`:o``}function Da(e){for(let t of N("#dashActive .active-card[data-watch]",e))t.onclick=n=>{let s=n.target;s instanceof Element&&s.tagName!=="A"&&(location.hash=`#/sent/${t.dataset.watch}`)}}function Ba(e,t,n){Fa(e,t,n),We(e)}function Fa(e,t,n){for(let s of N("[data-nav]",e))s.onclick=()=>{location.hash=s.dataset.nav??""};for(let s of N("[data-act='new-post']",e))s.onclick=()=>Uo(s);for(let s of N("[data-act='add-sub']",e))s.onclick=()=>Ms(t,n)}function Ua(e){return e?o`<div class="card pub-card">
82
86
  <p class="conn-status"><span class="conn-dot" aria-hidden="true"></span>Claude is connected.</p>
83
- <div class="pub-foot pub-links"><a href="#/api-reference">${N("code")}API reference →</a><a href="#/docs/connect-claude/working-with-claude">${N("article")}Working with Claude →</a></div>
87
+ <div class="pub-foot pub-links"><a href="#/api-reference">${O("code")}API reference →</a><a href="#/docs/connect-claude/working-with-claude">${O("article")}Working with Claude →</a></div>
84
88
  </div>`:o`<div class="card pub-card">
85
89
  <p class="pub-note">Let Claude draft, proofread, and schedule your posts.</p>
86
- <div class="pub-foot pub-links"><a href="#/docs/connect-claude">${N("article")}Connect Claude →</a><a href="#/api-reference">${N("code")}API reference →</a></div>
87
- </div>`}function aa(e,t,n,s){let i=`${t?.app_origin||location.origin}/subscribe`,a=ve(),{onList:r}=n,l=d=>d?" setup-done":"";return o`<div class="card setup${s==="card"?" setup-card":""}">
88
- <h2 class="setup-title">${s==="card"?"Finish setting up":"Set up your publication"}</h2>
89
- <ol class="setup-steps">
90
- <li class="setup-name${l(n.named)}"><div class="setup-step-main"><strong>Name your publication</strong><span class="muted">Currently “${e.name}”. Set the name, tagline, and brand in Settings.</span></div><button data-nav="#/settings">Settings</button></li>
91
- ${a?o`<li class="setup-connect"><div class="setup-step-main"><strong>Connect Amazon SES</strong><span class="muted">Nothing can be sent, and signups stay closed, until SES is connected.</span></div><button data-nav="${bo}">Connect Amazon SES</button></li>`:o`<li class="setup-check"><div class="setup-step-main"><strong>Check your setup</strong><span class="muted">Send yourself a test, and see how Kestrel tells you when something needs attention.</span></div><button data-nav="#/docs/check-your-setup">Docs</button></li>`}
92
- ${r?o`<li class="setup-done setup-list"><div class="setup-step-main"><strong>Bring your existing list</strong><span class="muted">${r.toLocaleString()} ${r===1?"subscriber":"subscribers"} on your list.</span></div><button data-nav="#/subscribers">Subscribers</button></li>`:o`<li class="setup-list"><div class="setup-step-main"><strong>Bring your existing list</strong><span class="muted">Import the subscribers you have on another service, with the consent they gave there. Skip this if you’re starting fresh.</span></div><button data-nav="#/subscribers/import">Import</button></li>`}
93
- <li class="setup-write${l(n.archived)}"><div class="setup-step-main"><strong>Publish your first post</strong><span class="muted">Write a post, test it, and send it. It goes to your subscribers and onto your site.</span></div>${s==="card"?o`<button data-act="new-post">New post</button>`:o`<button class="primary" data-act="new-post">New post</button>`}</li>
94
- ${a?o`<li class="setup-subscribe"><div class="setup-step-main"><strong>Share your subscribe link</strong><span class="muted">Signups open once an email provider is connected; until then the page says they aren’t open yet.</span></div></li>`:o`<li class="setup-subscribe"><div class="setup-step-main"><strong>Share your subscribe link</strong><code class="setup-url">${i}</code></div><button type="button" data-copy="${i}" aria-label="Copy the subscribe link">${Te()}</button></li>`}
95
- </ol>
96
- </div>`}var Ao=Math.floor(5e3);var Lb=`Workers Free suits a list of up to about ${1e3.toLocaleString("en-US")} subscribers. Past about ${Ao.toLocaleString("en-US")}, one send can use up the day\u2019s database writes and stop this newsletter until midnight UTC.`,$d="Move to Workers Paid, or, if the account is on it already, set SUBREQUEST_BUDGET to 10000.";function ca(e){return`On the Workers Free plan\u2019s limits, a send to ${e.toLocaleString("en-US")} recipients may use up the day\u2019s database writes and stop this newsletter until midnight UTC, the send included. Workers Free suits a list of up to about ${1e3.toLocaleString("en-US")} subscribers. ${$d}`}function ks(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80).replace(/-+$/g,"")}function Sn(e){return e.replace(/^https?:\/\//,"")}function da(){let e=zi("");return e?Sn(e):"/archive/"}function Qe(e,t){return{emailOnly:e.email_only,slug:e.slug,slugAuto:e.slug_auto,subject:e.subject,slugTaken:t,fixed:e.published_at!==null}}function Ho(e){return e.emailOnly?o`Sends by email only`:o`Sends by email and publishes at <code>${da()}${e.slug}</code>`}function Po(e){return N(e.emailOnly?"mail":"link")}var Ed="Listed on your home page and in your public archive. Unchecked, it\u2019s sent as email only: anyone with the email can still open its web version.",ua="Fixed once the post is sent, since people may have its link.";function pa(e,t){return e.fixed?o`<p class="pub-note">${t}</p>`:e.slugAuto&&e.slugTaken?o`<p class="pub-taken">${N("info")}<span>Another post has <code>${e.slugTaken}</code>, so a number was added. You can change it above.</span></p>`:e.slugAuto?o`<p class="pub-note">Follows the subject until you type your own.</p>`:null}function xd(e,t,{include:n=!0,fixedNote:s=ua}){let i=n?o`<label class="listing-check"><input type="checkbox" id="${t}Include"${e.emailOnly?null:o` checked`}><span><strong>Include in archive</strong><span class="listing-help">${Ed}</span></span></label>`:null;return e.emailOnly?o`${i}`:o`${i}<div class="pub-address"><label class="pub-label" for="${t}Slug">Archive address</label><label class="url-field${e.fixed?" readonly":""}" id="${t}Field"><span class="url-base">${da()}</span><input type="text" id="${t}Slug" value="${e.slug}" spellcheck="false" autocomplete="off" autocapitalize="off"${e.fixed?o` readonly`:null}></label><div id="${t}Note">${pa(e,s)}</div></div>`}function kd(e,t,n,s,{fixedNote:i=ua,onChange:a}){let r=e.querySelector(`#${n}Include`);r&&(r.onchange=()=>{t.emailOnly=!r.checked,s(),a?.()});let l=e.querySelector(`#${n}Slug`),d=e.querySelector(`#${n}Note`);!l||!d||t.fixed||(l.onfocus=()=>l.select(),l.oninput=()=>{t.slug=l.value,t.slugAuto=!1,e.querySelector(`#${n}Field`)?.classList.remove("is-invalid"),h(d,pa(t,i)??o``)},l.onblur=()=>{l.value.trim()===""&&(t.slugAuto=!0,t.slug=ks(t.subject)||t.slug,s())})}function $n(e,t){let n={};return t.emailOnly!==e.emailOnly&&(n.email_only=t.emailOnly),!e.fixed&&!t.emailOnly&&(t.slugAuto&&!e.slugAuto?n.slug_auto=!0:!t.slugAuto&&t.slug!==e.slug&&(n.slug=t.slug)),Object.keys(n).length?n:null}function $t(e,t,n,s={}){let i=()=>{h(e,xd(t,n,s)),kd(e,t,n,i,s)};i()}function En(e,t,n){if(!(n instanceof te)||n.field!=="slug"&&n.field!=="slug_auto")return!1;let s=e.querySelector(`#${t}Note`),i=e.querySelector(`#${t}Slug`);return!s||!i?!1:(e.querySelector(`#${t}Field`)?.classList.add("is-invalid"),h(s,o`<p class="pub-error" role="alert">${n.message}</p>`),i.focus(),!0)}var Et=F;function _s(e,t,n){let s=e.c_in_flight||0,a=pe(o`<h3>Resolve ${s} ambiguous ${s===1?"delivery":"deliveries"}</h3>
90
+ <div class="pub-foot pub-links"><a href="#/docs/connect-claude">${O("article")}Connect Claude →</a><a href="#/api-reference">${O("code")}API reference →</a></div>
91
+ </div>`}var Yo=Math.floor(5e3);var Hg=`Workers Free suits a list of up to about ${1e3.toLocaleString("en-US")} subscribers. Past about ${Yo.toLocaleString("en-US")}, one send can use up the day\u2019s database writes and stop this newsletter until midnight UTC.`,bu="Move to Workers Paid, or, if the account is on it already, set SUBREQUEST_BUDGET to 10000.";function qa(e){return`On the Workers Free plan\u2019s limits, a send to ${e.toLocaleString("en-US")} recipients may use up the day\u2019s database writes and stop this newsletter until midnight UTC, the send included. Workers Free suits a list of up to about ${1e3.toLocaleString("en-US")} subscribers. ${bu}`}function Ns(e){return e.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80).replace(/-+$/g,"")}function Rn(e){return e.replace(/^https?:\/\//,"")}function ja(){let e=fr("");return e?Rn(e):"/archive/"}function et(e,t){return{emailOnly:e.email_only,slug:e.slug,slugAuto:e.slug_auto,subject:e.subject,slugTaken:t,fixed:e.published_at!==null}}function Zo(e){return e.emailOnly?o`Sends by email only`:o`Sends by email and publishes at <code>${ja()}${e.slug}</code>`}function Jo(e){return O(e.emailOnly?"mail":"link")}var gu="Listed on your home page and in your public archive. Unchecked, it\u2019s sent as email only: anyone with the email can still open its web version.",Wa="Fixed once the post is sent, since people may have its link.";function Va(e,t){return e.fixed?o`<p class="pub-note">${t}</p>`:e.slugAuto&&e.slugTaken?o`<p class="pub-taken">${O("info")}<span>Another post has <code>${e.slugTaken}</code>, so a number was added. You can change it above.</span></p>`:e.slugAuto?o`<p class="pub-note">Follows the subject until you type your own.</p>`:null}function vu(e,t,{include:n=!0,fixedNote:s=Wa}){let i=n?o`<label class="listing-check"><input type="checkbox" id="${t}Include"${e.emailOnly?null:o` checked`}><span><strong>Include in archive</strong><span class="listing-help">${gu}</span></span></label>`:null;return e.emailOnly?o`${i}`:o`${i}<div class="pub-address"><label class="pub-label" for="${t}Slug">Archive address</label><label class="url-field${e.fixed?" readonly":""}" id="${t}Field"><span class="url-base">${ja()}</span><input type="text" id="${t}Slug" value="${e.slug}" spellcheck="false" autocomplete="off" autocapitalize="off"${e.fixed?o` readonly`:null}></label><div id="${t}Note">${Va(e,s)}</div></div>`}function yu(e,t,n,s,{fixedNote:i=Wa,onChange:r}){let a=e.querySelector(`#${n}Include`);a&&(a.onchange=()=>{t.emailOnly=!a.checked,s(),r?.()});let l=e.querySelector(`#${n}Slug`),d=e.querySelector(`#${n}Note`);!l||!d||t.fixed||(l.onfocus=()=>l.select(),l.oninput=()=>{t.slug=l.value,t.slugAuto=!1,e.querySelector(`#${n}Field`)?.classList.remove("is-invalid"),h(d,Va(t,i)??o``)},l.onblur=()=>{l.value.trim()===""&&(t.slugAuto=!0,t.slug=Ns(t.subject)||t.slug,s())})}function Cn(e,t){let n={};return t.emailOnly!==e.emailOnly&&(n.email_only=t.emailOnly),!e.fixed&&!t.emailOnly&&(t.slugAuto&&!e.slugAuto?n.slug_auto=!0:!t.slugAuto&&t.slug!==e.slug&&(n.slug=t.slug)),Object.keys(n).length?n:null}function _t(e,t,n,s={}){let i=()=>{h(e,vu(t,n,s)),yu(e,t,n,i,s)};i()}function An(e,t,n){if(!(n instanceof te)||n.field!=="slug"&&n.field!=="slug_auto")return!1;let s=e.querySelector(`#${t}Note`),i=e.querySelector(`#${t}Slug`);return!s||!i?!1:(e.querySelector(`#${t}Field`)?.classList.add("is-invalid"),h(s,o`<p class="pub-error" role="alert">${n.message}</p>`),i.focus(),!0)}var Tt=V;function Os(e,t,n){let s=e.c_in_flight||0,r=fe(o`<h3>Resolve ${s} ambiguous ${s===1?"delivery":"deliveries"}</h3>
97
92
  <p class="hint">A transport error left ${s} recipient${s===1?"":"s"} in flight: the request went out but the provider never confirmed, so there’s no way to know whether it was accepted. To avoid mailing anyone twice, the send won’t retry ${s===1?"it":"them"} on its own, so it can’t finish until you decide. Neither choice re-sends this post.</p>
98
93
  <p class="hint">Kestrel can’t tell whether ${s===1?"this email":"these emails"} went out, so unless you know, <strong>Assume not sent</strong> is the safe default.</p>
99
94
  <p class="hint"><strong>Assume not sent</strong>: recorded as unsent. ${s===1?"That reader":"Those readers"} may miss this post but ${s===1?"gets":"get"} your next one, and no one is mailed twice.</p>
100
95
  <p class="hint"><strong>Assume sent</strong>: recorded as accepted by your provider, with delivery still waiting on its receipt. Choose this when you know otherwise, such as a reader who says they got it.</p>
101
- <div class="actions"><button type="button" id="rCancel">Cancel</button><button type="button" id="rUnsent">Assume not sent</button><button type="button" class="primary" id="rAccepted">Assume sent</button></div>`,n);c("#rCancel",a.el).onclick=a.close;let r=(u,f,S)=>G(u,"Resolving\u2026",async()=>{a.clearError();try{let b=await R(`/api/sends/${e.id}/resolve`,{method:"POST",json:{resolution:f}});a.close(),O(b.completed?"Send completed":`Marked ${S}`),t()}catch(b){a.error(Et(b))}}),l=c("#rUnsent",a.el),d=c("#rAccepted",a.el);l.onclick=()=>r(l,"unsent","not sent"),d.onclick=()=>r(d,"accepted","sent")}async function Ts(e,t,n,s){let i=s;if(!i)try{let v=await R(`/api/posts/${e.post_id}`,{signal:n});i=Qe(v.post,v.subject_slug_held)}catch(v){n.aborted||O(Et(v));return}let a=i,r={...a},l=yt(os()),d=new Date(yt(new Date(e.fire_at))),u=pe(o`<h3 id="rsHead">Edit schedule</h3>
96
+ <div class="actions"><button type="button" id="rCancel">Cancel</button><button type="button" id="rUnsent">Assume not sent</button><button type="button" class="primary" id="rAccepted">Assume sent</button></div>`,n);c("#rCancel",r.el).onclick=r.close;let a=(u,m,v)=>Z(u,"Resolving\u2026",async()=>{r.clearError();try{let f=await L(`/api/sends/${e.id}/resolve`,{method:"POST",json:{resolution:m}});r.close(),U(f.completed?"Send completed":`Marked ${v}`),t()}catch(f){r.error(Tt(f))}}),l=c("#rUnsent",r.el),d=c("#rAccepted",r.el);l.onclick=()=>a(l,"unsent","not sent"),d.onclick=()=>a(d,"accepted","sent")}async function Ds(e,t,n,s){let i=s;if(!i)try{let S=await L(`/api/posts/${e.post_id}`,{signal:n});i=et(S.post,S.subject_slug_held)}catch(S){n.aborted||U(Tt(S));return}let r=i,a={...r},l=$t(ms()),d=new Date($t(new Date(e.fire_at))),u=fe(o`<h3 id="rsHead">Edit schedule</h3>
102
97
  <p class="hint" id="rsHint">It sends at the time you pick, with a cancelable window until then.</p>
103
- ${Gi()}
104
- <label for="rsWhen">Send at</label><input type="datetime-local" id="rsWhen" min="${l}" value="${yt(d)}">
98
+ ${mr()}
99
+ <label for="rsWhen">Send at</label><input type="datetime-local" id="rsWhen" min="${l}" value="${$t(d)}">
105
100
  <div class="dialog-settings" id="rsForm"></div>
106
- <div class="actions"><button type="button" id="rsCancel">Cancel</button><button type="button" class="primary" id="rsGo">Save</button></div>`,n),f=c(".modal",u.el);f.setAttribute("aria-labelledby","rsHead"),$t(c("#rsForm",f),r,"rs");let S=c("#rsGo",f),b=c("#rsWhen",f),p=!1;c("#rsCancel",f).onclick=()=>{u.close(),p&&t()},S.onclick=()=>G(S,"Saving\u2026",async()=>{u.clearError();let v=b.value,x=v?new Date(v).getTime():Number.NaN;if(Number.isNaN(x)){u.error("Pick a valid date & time",b);return}let M=x===d.getTime();if(!M&&ss(x)){u.error(ns(),b);return}let A=$n(a,r);if(M&&!A){u.close();return}let H=T=>T instanceof te&&T.status===404?(u.close(),O("This post was deleted elsewhere."),Fe(),!0):!1;if(A)try{await R(`/api/posts/${e.post_id}/settings`,{method:"PUT",json:A})}catch(T){!H(T)&&!En(f,"rs",T)&&u.error(Et(T));return}if(!M)try{await R(`/api/sends/${e.id}/reschedule`,{method:"POST",json:{fire_at:new Date(x).toISOString()}})}catch(T){if(H(T))return;let m=T instanceof te&&T.field==="fire_at";if(A){if(a={...r},p=!0,m){u.error(`Settings saved. ${Et(T)}`,b);return}u.close(),O(`Settings saved. The send time didn\u2019t change: ${Et(T)}`),t();return}m?u.error(Et(T),b):u.error(Et(T));return}u.close(),O(M?"Saved":"Rescheduled"),t()}),b.focus()}function ma(e,t={}){return["default-src 'none'","script-src 'none'","object-src 'none'","frame-src 'none'","base-uri 'none'",`form-action ${e}`,t.framed?null:"frame-ancestors 'none'","img-src * data:","style-src 'unsafe-inline' https://fonts.googleapis.com","font-src https://fonts.gstatic.com"].filter(n=>n!==null).join("; ")}var fa=e=>e.preventDefault(),Yt="allow-same-origin allow-popups allow-popups-to-escape-sandbox";function Zt(e){for(let t of e.querySelectorAll("a[href], area[href]")){if(t.getAttribute("href")?.startsWith("#")){t.addEventListener("click",fa),t.addEventListener("auxclick",fa);continue}t.target="_blank",t.rel="noopener noreferrer"}}function _d(e,t){let n=/<head(\s[^>]*)?>/i;return n.test(e)?e.replace(n,s=>s+t):t+e}function Ls(e){return _d(e,`<meta http-equiv="Content-Security-Policy" content="${ma("'none'",{framed:!0})}">`)}function ha(e){return e.replace(/\{\{\s*(?:if\s+)?[\w.]+\s*\}\}/g,t=>`<span class="cx-var">${t}</span>`)}function Td(e){let t=X(e);return t=t.replace(/&quot;[^&]*?&quot;/g,n=>`<span class="cx-str">${n}</span>`),t=t.replace(/(&lt;\/?)([a-zA-Z][\w-]*)/g,(n,s,i)=>`<span class="cx-punct">${s}</span><span class="cx-tag">${i}</span>`),t=t.replace(/(\/?)&gt;/g,(n,s)=>`<span class="cx-punct">${s}&gt;</span>`),ha(t)}function Ld(e){let t=X(e);return t=t.replace(/&quot;[^&]*?&quot;/g,n=>`<span class="cx-str">${n}</span>`),t=t.replace(/#[0-9a-fA-F]{3,8}\b/g,n=>`<span class="cx-num">${n}</span>`),t=t.replace(/@[\w-]+/g,n=>`<span class="cx-at">${n}</span>`),t=t.replace(/^(\s*)(?![@\s])([^\n{}<]+?)(\s*)\{$/gm,(n,s,i,a)=>`${s}<span class="cx-sel">${i}</span>${a}{`),t=t.replace(/^(\s*)([a-z-]+)(\s*:)/gm,(n,s,i,a)=>`${s}<span class="cx-prop">${i}</span>${a}`),ha(t)}function ba(e){return j(String(e).split(/(<style>[\s\S]*?<\/style>)/).map(t=>{let n=t.match(/^<style>([\s\S]*?)<\/style>$/);return n?`<span class="cx-punct">&lt;</span><span class="cx-tag">style</span><span class="cx-punct">&gt;</span>${Ld(n[1]??"")}<span class="cx-punct">&lt;/</span><span class="cx-tag">style</span><span class="cx-punct">&gt;</span>`:Td(t)}).join(""))}function Mo(e){return X(e).replace(/(`[^`\n]+`)|(!?)(\[[^\]\n]*\])\(([^)\n]*)\)|(\*\*|__)([^\n]+?)\5|\*([^*\n]+?)\*|\b_([^_\n]+?)_\b/g,(t,n,s,i,a,r,l,d,u)=>{if(n)return`<span class="cx-md-code">${n}</span>`;if(i!==void 0)return`${s||""}${i}(<span class="cx-md-url">${a}</span>)`;if(r)return`<span class="cx-md-mark">${r}</span><span class="cx-md-strong">${l}</span><span class="cx-md-mark">${r}</span>`;let[f,S]=d!==void 0?["*",d]:["_",u];return`<span class="cx-md-mark">${f}</span><span class="cx-md-em">${S}</span><span class="cx-md-mark">${f}</span>`})}function Rd(e){let t=e.match(/^(\s{0,3}#{1,6})(\s.*)?$/);if(t)return`<span class="cx-md-hmark">${X(t[1]??"")}</span><span class="cx-md-htext">${X(t[2]||"")}</span>`;if(/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(e))return`<span class="cx-md-bmark">${X(e)}</span>`;let n=e.match(/^(\s{0,3})((?:>\s?)+)(.*)$/);if(n)return`${X(n[1]??"")}<span class="cx-md-bmark">${X(n[2]??"")}</span>${Mo(n[3]??"")}`;let s=e.match(/^(\s*)([-*+]|\d{1,9}[.)])(\s+)(.*)$/);return s?`${s[1]}<span class="cx-md-bmark">${X(s[2]??"")}</span>${s[3]}${Mo(s[4]??"")}`:Mo(e)}function ga(e){let t=!1;return j(String(e).split(`
107
- `).map(n=>{let s,i=!1,a=n.match(/^(\s*)(```+|~~~+)(.*)$/);if(a){t=!t;let r=a[3]?`<span class="cx-md-bmark">${X(a[3])}</span>`:"";s=`${a[1]}${X(a[2]??"")}${r}`}else t?(i=!0,s=X(n)):s=Rd(n);return`<span class="cx-md-ln${i?" cx-md-band":""}">${s}</span>`}).join(""))}var Cd=/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*")(\s*:)?|(?<![\w.-])(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?![\w.])|\b(true|false|null)\b|([{}[\],])/g;function Io(e){let t="",n=0;for(let s of e.matchAll(Cd)){t+=X(e.slice(n,s.index));let[i,a,r,l,d,u]=s;a!==void 0?t+=`<span class="cx-punct">${X(a)}</span>`:r!==void 0?t+=l?`<span class="cx-prop">${X(r)}</span><span class="cx-punct">${X(l)}</span>`:`<span class="cx-str">${X(r)}</span>`:d!==void 0?t+=`<span class="cx-num">${d}</span>`:u!==void 0?t+=`<span class="cx-tag">${u}</span>`:t+=`<span class="cx-punct">${X(i)}</span>`,n=s.index+i.length}return j(t+X(e.slice(n)))}function va(e){return Io(JSON.stringify(e,null,2)??"")}var Ad=/(\\\n)|(\\[\s\S])|('[^']*')|("(?:\\[\s\S]|[^"\\])*")|(\$\{?[A-Za-z_]\w*\}?)|(&&|\|\||[|;])|(\n)|(#[^\n]*)|([^\s'"$|&;\\]+)/g,Hd=/\$\{?[A-Za-z_]\w*\}?/g;function Rs(e){let t="",n=0,s=!0;for(let i of e.matchAll(Ad)){t+=X(e.slice(n,i.index));let[a,r,l,d,u,f,S,b,p,v]=i;r!==void 0?t+=`<span class="cx-punct">\\</span>
108
- `:l!==void 0?t+=X(l):d!==void 0?(t+=`<span class="cx-str">${X(d)}</span>`,s=!1):u!==void 0?(t+=`<span class="cx-str">${X(u).replace(Hd,'<span class="cx-var">$&</span>')}</span>`,s=!1):f!==void 0?(t+=`<span class="cx-var">${f}</span>`,s=!1):S!==void 0?(t+=`<span class="cx-punct">${X(S)}</span>`,s=!0):b!==void 0?(t+=`
109
- `,s=!0):p!==void 0?t+=`<span class="cx-punct">${X(p)}</span>`:v!==void 0&&(s&&/^[A-Za-z_]\w*=/.test(v)?t+=X(v):s?(t+=`<span class="cx-tag">${X(v)}</span>`,s=!1):v.startsWith("-")?t+=`<span class="cx-num">${X(v)}</span>`:t+=X(v)),n=i.index+a.length}return j(t+X(e.slice(n)))}var Pd={[Gn]:"Claude Code",[zn]:"Claude"};function Jt(e,t,n){return e?e==="service"?n?`the service token ${n}`:"a service token":t===ln?e:t===null?`${e} via the API`:`${e} via ${Pd[t]??t}`:null}function ya(e){return e.kind==="service"?Jt("service",null,e.token_id)??"a service token":Jt(e.email??null,e.client)??"a person"}var Md=[["scheduled_by","scheduled"],["rescheduled_by","rescheduled"],["canceled_by","canceled"],["resolved_by","resolved"]];function wa(e){let n=Md.flatMap(([s,i])=>{let a=e[s];return a?[`${i} by ${ya(a)}`]:[]}).join(" \xB7 ");return n?n.charAt(0).toUpperCase()+n.slice(1):null}function Id(e,t){return e.kind==="human"&&t?.kind==="human"&&e.email===t.email&&e.client===ln}function Sa(e,t){let n=e.rescheduled_by?{verb:"Rescheduled",actor:e.rescheduled_by}:e.scheduled_by?{verb:"Scheduled",actor:e.scheduled_by}:null;return!n||Id(n.actor,t)?null:`${n.verb} by ${ya(n.actor)}`}var Nd={idleMs:5e3,maxMs:3e4};function $a(e,t=Nd){let n=null,s=null,i=()=>{n!==null&&clearTimeout(n),s!==null&&clearTimeout(s),n=null,s=null},a=()=>{i(),e()};return{touch(){n!==null&&clearTimeout(n),n=setTimeout(a,t.idleMs),s===null&&(s=setTimeout(a,t.maxMs))},cancel:i,get pending(){return n!==null||s!==null}}}var Cs=class{constructor(t){this.read=t;this.#e=JSON.stringify(t())}read;#e;snapshot(){return JSON.stringify(this.read())}get dirty(){return this.snapshot()!==this.#e}markSaved(t=this.snapshot()){this.#e=t}};var Ea=Promise.resolve();function No(e){Ea=e}function xa(){return Ea.then(()=>{},()=>{})}function ka(e){if(!(e instanceof te)||e.status!==409)return null;let t=e.data;return t?.error==="stale_revision"&&typeof t.current_revision=="string"?{kind:"stale",revision:t.current_revision,author:typeof t.author=="string"?t.author:null,client:typeof t.author_client=="string"?t.author_client:null}:{kind:"locked"}}var As=class{base;warnedRevision=null;constructor(t){this.base=t}saved(t){this.base=t}noteWarned(t){t.kind==="stale"&&(this.warnedRevision=t.revision)}adoptWarned(){this.warnedRevision!==null&&(this.base=this.warnedRevision),this.warnedRevision=null}clearWarning(){this.warnedRevision=null}decide(t,n){if(n.saving||this.base!==n.baseAtRequest)return"ignore";if(t.status!=="draft")return{kind:"locked"};let s=t.revision;return s&&s!==this.base&&s!==this.warnedRevision?{kind:"stale",revision:s,author:t.author,client:t.client}:"fresh"}};function Ta(e){return`#/web/post/${encodeURIComponent(e)}`}function La(e,t){if(e!=="post"||!t)return null;try{return decodeURIComponent(t)}catch{return null}}function Bd(e){let t=o`<span class="web-bar-tag">Web version</span>`;return e?o`${t} <span class="web-bar-text">Not public yet</span>`:t}function _a(e){try{return new URL(e).href}catch{return null}}function Ra(e,t,n){let s=t?_a(t):null;if(s)for(let i of e.querySelectorAll("a[href], area[href]")){let a=i.getAttribute("href");a&&_a(a)===s&&i.setAttribute("href",n)}}function Od(e){location.replace(e)}async function Dd(e,t){try{return await R(`/api/posts/${encodeURIComponent(e)}`,{signal:t})}catch{return null}}async function Bo(e,t,n){se(n,"Web version");try{await xa();let[s,i]=await Promise.all([Mt(`/api/posts/${encodeURIComponent(e)}/web`,{signal:n}),Dd(e,n)]);if(n.aborted)return;if(i&&i.post.published_at!==null){Od(i.post.unlisted_url);return}let a=Bd(i!==null);h(t,o`<div class="web-page">
110
- <div class="web-bar" role="note"><div class="web-bar-in">${a}</div></div>
111
- <iframe class="web-frame" sandbox="${Yt}" title="Web version" scrolling="no"></iframe>
112
- </div>`);let r=t.querySelector(".web-frame");if(!r)return;r.onload=()=>{let l=r.contentDocument;if(!l||n.aborted)return;Zt(l),se(n,l.title?`${l.title} (web version)`:"Web version");let d=()=>{let u=l.body?.scrollHeight;u&&(r.style.height=`${u}px`)};if(d(),l.body&&typeof ResizeObserver<"u"){let u=new ResizeObserver(d);u.observe(l.body),Pt(n,()=>u.disconnect())}},r.srcdoc=Ls(s)}catch(s){if(n.aborted)return;h(t,o`<div class="web-error"></div>`);let i=t.querySelector(".web-error");if(i){let r=s instanceof te&&s.status===404?"There\u2019s no post here. It may have been deleted.":F(s);oe(i,r,()=>ee((l,d)=>Bo(e,l,d)))}}}var Xe=F,Ud=[[["heading","Heading"],["bold","Bold (\u2318B)"],["italic","Italic (\u2318I)"]],[["quote","Quote"],["code","Code"],["link","Link (\u2318K)"]],[["ul","Bulleted list"],["ol","Numbered list"],["indent","Indent"]]],Fd=o` readonly`,qd=o` hidden`,jd=o` aria-disabled="true"`;async function Oo(e,t,n){let s=()=>{n.aborted||ee((w,P)=>Oo(e,w,P))},i=!1,a=(w="This post was deleted elsewhere.")=>{i||(i=!0,O(w),n.aborted||Hs("#/drafts"))};se(n,"Draft"),h(t,o`<p class="muted">Loading…</p>`);let r,l=null;try{if(r=await R(`/api/posts/${e}`,{signal:n}),n.aborted)return;let w=Vd(r);if(w){Hs(w);return}}catch(w){if(Be(w)){a("There\u2019s no post here. It may have been deleted.");return}oe(t,Xe(w),s);return}let d=gn(r.post);if(d){try{l=await R(`/api/sends/${d.id}`,{signal:n})}catch(w){if(n.aborted)return;if(Be(w)){a();return}}if(n.aborted||l&&Ca(l.send,s))return}let{post:u,markdown:f}=r,S=Q.session?.principal??null,b=Qe(u,r.subject_slug_held),p=!Gt(u,"edit"),v=Gt(u,"schedule")!==void 0,x=new As(u.current_revision),M=Ud.map((w,P)=>o`${P?o`<span class="sep"></span>`:null}${w.map(([k,B])=>o`<button type="button" class="tb" data-fmt="${k}" title="${B}" aria-label="${B}"${p?jd:null}>${N(k)}</button>`)}`),A=p?Fd:null,H=`${location.origin}${location.pathname}${Ta(e)}`;h(t,o`
101
+ <div class="actions"><button type="button" id="rsCancel">Cancel</button><button type="button" class="primary" id="rsGo">Save</button></div>`,n),m=c(".modal",u.el);m.setAttribute("aria-labelledby","rsHead"),_t(c("#rsForm",m),a,"rs");let v=c("#rsGo",m),f=c("#rsWhen",m),p=!1;c("#rsCancel",m).onclick=()=>{u.close(),p&&t()},v.onclick=()=>Z(v,"Saving\u2026",async()=>{u.clearError();let S=f.value,$=S?new Date(S).getTime():Number.NaN;if(Number.isNaN($)){u.error("Pick a valid date & time",f);return}let M=$===d.getTime();if(!M&&ps($)){u.error(us(),f);return}let P=Cn(r,a);if(M&&!P){u.close();return}let A=H=>H instanceof te&&H.status===404?(u.close(),U("This post was deleted elsewhere."),Fe(),!0):!1;if(P)try{await L(`/api/posts/${e.post_id}/settings`,{method:"PUT",json:P})}catch(H){!A(H)&&!An(m,"rs",H)&&u.error(Tt(H));return}if(!M)try{await L(`/api/sends/${e.id}/reschedule`,{method:"POST",json:{fire_at:new Date($).toISOString()}})}catch(H){if(A(H))return;let y=H instanceof te&&H.field==="fire_at";if(P){if(r={...a},p=!0,y){u.error(`Settings saved. ${Tt(H)}`,f);return}u.close(),U(`Settings saved. The send time didn\u2019t change: ${Tt(H)}`),t();return}y?u.error(Tt(H),f):u.error(Tt(H));return}u.close(),U(M?"Saved":"Rescheduled"),t()}),f.focus()}function Ka(e,t={}){return["default-src 'none'","script-src 'none'","object-src 'none'","frame-src 'none'","base-uri 'none'",`form-action ${e}`,t.framed?null:"frame-ancestors 'none'","img-src * data:","style-src 'unsafe-inline' https://fonts.googleapis.com","font-src https://fonts.gstatic.com"].filter(n=>n!==null).join("; ")}var Ga=e=>e.preventDefault(),Qt="allow-same-origin allow-popups allow-popups-to-escape-sandbox";function Xt(e){for(let t of e.querySelectorAll("a[href], area[href]")){if(t.getAttribute("href")?.startsWith("#")){t.addEventListener("click",Ga),t.addEventListener("auxclick",Ga);continue}t.target="_blank",t.rel="noopener noreferrer"}}function wu(e,t){let n=/<head(\s[^>]*)?>/i;return n.test(e)?e.replace(n,s=>s+t):t+e}function Bs(e){return wu(e,`<meta http-equiv="Content-Security-Policy" content="${Ka("'none'",{framed:!0})}">`)}function za(e){return e.replace(/\{\{\s*(?:if\s+)?[\w.]+\s*\}\}/g,t=>`<span class="cx-var">${t}</span>`)}function Su(e){let t=X(e);return t=t.replace(/&quot;[^&]*?&quot;/g,n=>`<span class="cx-str">${n}</span>`),t=t.replace(/(&lt;\/?)([a-zA-Z][\w-]*)/g,(n,s,i)=>`<span class="cx-punct">${s}</span><span class="cx-tag">${i}</span>`),t=t.replace(/(\/?)&gt;/g,(n,s)=>`<span class="cx-punct">${s}&gt;</span>`),za(t)}function $u(e){let t=X(e);return t=t.replace(/&quot;[^&]*?&quot;/g,n=>`<span class="cx-str">${n}</span>`),t=t.replace(/#[0-9a-fA-F]{3,8}\b/g,n=>`<span class="cx-num">${n}</span>`),t=t.replace(/@[\w-]+/g,n=>`<span class="cx-at">${n}</span>`),t=t.replace(/^(\s*)(?![@\s])([^\n{}<]+?)(\s*)\{$/gm,(n,s,i,r)=>`${s}<span class="cx-sel">${i}</span>${r}{`),t=t.replace(/^(\s*)([a-z-]+)(\s*:)/gm,(n,s,i,r)=>`${s}<span class="cx-prop">${i}</span>${r}`),za(t)}function Ya(e){return z(String(e).split(/(<style>[\s\S]*?<\/style>)/).map(t=>{let n=t.match(/^<style>([\s\S]*?)<\/style>$/);return n?`<span class="cx-punct">&lt;</span><span class="cx-tag">style</span><span class="cx-punct">&gt;</span>${$u(n[1]??"")}<span class="cx-punct">&lt;/</span><span class="cx-tag">style</span><span class="cx-punct">&gt;</span>`:Su(t)}).join(""))}function Qo(e){return X(e).replace(/(`[^`\n]+`)|(!?)(\[[^\]\n]*\])\(([^)\n]*)\)|(\*\*|__)([^\n]+?)\5|\*([^*\n]+?)\*|\b_([^_\n]+?)_\b/g,(t,n,s,i,r,a,l,d,u)=>{if(n)return`<span class="cx-md-code">${n}</span>`;if(i!==void 0)return`${s||""}${i}(<span class="cx-md-url">${r}</span>)`;if(a)return`<span class="cx-md-mark">${a}</span><span class="cx-md-strong">${l}</span><span class="cx-md-mark">${a}</span>`;let[m,v]=d!==void 0?["*",d]:["_",u];return`<span class="cx-md-mark">${m}</span><span class="cx-md-em">${v}</span><span class="cx-md-mark">${m}</span>`})}function xu(e){let t=e.match(/^(\s{0,3}#{1,6})(\s.*)?$/);if(t)return`<span class="cx-md-hmark">${X(t[1]??"")}</span><span class="cx-md-htext">${X(t[2]||"")}</span>`;if(/^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/.test(e))return`<span class="cx-md-bmark">${X(e)}</span>`;let n=e.match(/^(\s{0,3})((?:>\s?)+)(.*)$/);if(n)return`${X(n[1]??"")}<span class="cx-md-bmark">${X(n[2]??"")}</span>${Qo(n[3]??"")}`;let s=e.match(/^(\s*)([-*+]|\d{1,9}[.)])(\s+)(.*)$/);return s?`${s[1]}<span class="cx-md-bmark">${X(s[2]??"")}</span>${s[3]}${Qo(s[4]??"")}`:Qo(e)}function Za(e){let t=!1;return z(String(e).split(`
102
+ `).map(n=>{let s,i=!1,r=n.match(/^(\s*)(```+|~~~+)(.*)$/);if(r){t=!t;let a=r[3]?`<span class="cx-md-bmark">${X(r[3])}</span>`:"";s=`${r[1]}${X(r[2]??"")}${a}`}else t?(i=!0,s=X(n)):s=xu(n);return`<span class="cx-md-ln${i?" cx-md-band":""}">${s}</span>`}).join(""))}var Eu=/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*")(\s*:)?|(?<![\w.-])(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?![\w.])|\b(true|false|null)\b|([{}[\],])/g;function Xo(e){let t="",n=0;for(let s of e.matchAll(Eu)){t+=X(e.slice(n,s.index));let[i,r,a,l,d,u]=s;r!==void 0?t+=`<span class="cx-punct">${X(r)}</span>`:a!==void 0?t+=l?`<span class="cx-prop">${X(a)}</span><span class="cx-punct">${X(l)}</span>`:`<span class="cx-str">${X(a)}</span>`:d!==void 0?t+=`<span class="cx-num">${d}</span>`:u!==void 0?t+=`<span class="cx-tag">${u}</span>`:t+=`<span class="cx-punct">${X(i)}</span>`,n=s.index+i.length}return z(t+X(e.slice(n)))}function Ja(e){return Xo(JSON.stringify(e,null,2)??"")}var ku=/(\\\n)|(\\[\s\S])|('[^']*')|("(?:\\[\s\S]|[^"\\])*")|(\$\{?[A-Za-z_]\w*\}?)|(&&|\|\||[|;])|(\n)|(#[^\n]*)|([^\s'"$|&;\\]+)/g,_u=/\$\{?[A-Za-z_]\w*\}?/g;function Us(e){let t="",n=0,s=!0;for(let i of e.matchAll(ku)){t+=X(e.slice(n,i.index));let[r,a,l,d,u,m,v,f,p,S]=i;a!==void 0?t+=`<span class="cx-punct">\\</span>
103
+ `:l!==void 0?t+=X(l):d!==void 0?(t+=`<span class="cx-str">${X(d)}</span>`,s=!1):u!==void 0?(t+=`<span class="cx-str">${X(u).replace(_u,'<span class="cx-var">$&</span>')}</span>`,s=!1):m!==void 0?(t+=`<span class="cx-var">${m}</span>`,s=!1):v!==void 0?(t+=`<span class="cx-punct">${X(v)}</span>`,s=!0):f!==void 0?(t+=`
104
+ `,s=!0):p!==void 0?t+=`<span class="cx-punct">${X(p)}</span>`:S!==void 0&&(s&&/^[A-Za-z_]\w*=/.test(S)?t+=X(S):s?(t+=`<span class="cx-tag">${X(S)}</span>`,s=!1):S.startsWith("-")?t+=`<span class="cx-num">${X(S)}</span>`:t+=X(S)),n=i.index+r.length}return z(t+X(e.slice(n)))}var Tu={[ns]:"Claude Code",[ss]:"Claude"};function en(e,t,n){return e?e==="service"?n?`the service token ${n}`:"a service token":t===un?e:t===null?`${e} via the API`:`${e} via ${Tu[t]??t}`:null}function Qa(e){return e.kind==="service"?en("service",null,e.token_id)??"a service token":en(e.email??null,e.client)??"a person"}var Lu=[["scheduled_by","scheduled"],["rescheduled_by","rescheduled"],["canceled_by","canceled"],["resolved_by","resolved"]];function Xa(e){let n=Lu.flatMap(([s,i])=>{let r=e[s];return r?[`${i} by ${Qa(r)}`]:[]}).join(" \xB7 ");return n?n.charAt(0).toUpperCase()+n.slice(1):null}function Ru(e,t){return e.kind==="human"&&t?.kind==="human"&&e.email===t.email&&e.client===un}function el(e,t){let n=e.rescheduled_by?{verb:"Rescheduled",actor:e.rescheduled_by}:e.scheduled_by?{verb:"Scheduled",actor:e.scheduled_by}:null;return!n||Ru(n.actor,t)?null:`${n.verb} by ${Qa(n.actor)}`}var Cu={idleMs:5e3,maxMs:3e4};function tl(e,t=Cu){let n=null,s=null,i=()=>{n!==null&&clearTimeout(n),s!==null&&clearTimeout(s),n=null,s=null},r=()=>{i(),e()};return{touch(){n!==null&&clearTimeout(n),n=setTimeout(r,t.idleMs),s===null&&(s=setTimeout(r,t.maxMs))},cancel:i,get pending(){return n!==null||s!==null}}}var Fs=class{constructor(t){this.read=t;this.#e=JSON.stringify(t())}read;#e;snapshot(){return JSON.stringify(this.read())}get dirty(){return this.snapshot()!==this.#e}markSaved(t=this.snapshot()){this.#e=t}};var nl=Promise.resolve();function ei(e){nl=e}function sl(){return nl.then(()=>{},()=>{})}function ol(e){if(!(e instanceof te)||e.status!==409)return null;let t=e.data;return t?.error==="stale_revision"&&typeof t.current_revision=="string"?{kind:"stale",revision:t.current_revision,author:typeof t.author=="string"?t.author:null,client:typeof t.author_client=="string"?t.author_client:null}:{kind:"locked"}}var qs=class{base;warnedRevision=null;constructor(t){this.base=t}saved(t){this.base=t}noteWarned(t){t.kind==="stale"&&(this.warnedRevision=t.revision)}adoptWarned(){this.warnedRevision!==null&&(this.base=this.warnedRevision),this.warnedRevision=null}clearWarning(){this.warnedRevision=null}decide(t,n){if(n.saving||this.base!==n.baseAtRequest)return"ignore";if(t.status!=="draft")return{kind:"locked"};let s=t.revision;return s&&s!==this.base&&s!==this.warnedRevision?{kind:"stale",revision:s,author:t.author,client:t.client}:"fresh"}};function rl(e){return`#/web/post/${encodeURIComponent(e)}`}function al(e,t){if(e!=="post"||!t)return null;try{return decodeURIComponent(t)}catch{return null}}function Au(e){let t=o`<span class="web-bar-tag">Web version</span>`;return e?o`${t} <span class="web-bar-text">Not public yet</span>`:t}function il(e){try{return new URL(e).href}catch{return null}}function ll(e,t,n){let s=t?il(t):null;if(s)for(let i of e.querySelectorAll("a[href], area[href]")){let r=i.getAttribute("href");r&&il(r)===s&&i.setAttribute("href",n)}}function Hu(e){location.replace(e)}async function Pu(e,t){try{return await L(`/api/posts/${encodeURIComponent(e)}`,{signal:t})}catch{return null}}async function ti(e,t,n){ie(n,"Web version");try{await sl();let[s,i]=await Promise.all([Ot(`/api/posts/${encodeURIComponent(e)}/web`,{signal:n}),Pu(e,n)]);if(n.aborted)return;if(i&&i.post.published_at!==null){Hu(i.post.unlisted_url);return}let r=Au(i!==null);h(t,o`<div class="web-page">
105
+ <div class="web-bar" role="note"><div class="web-bar-in">${r}</div></div>
106
+ <iframe class="web-frame" sandbox="${Qt}" title="Web version" scrolling="no"></iframe>
107
+ </div>`);let a=t.querySelector(".web-frame");if(!a)return;a.onload=()=>{let l=a.contentDocument;if(!l||n.aborted)return;Xt(l),ie(n,l.title?`${l.title} (web version)`:"Web version");let d=()=>{let u=l.body?.scrollHeight;u&&(a.style.height=`${u}px`)};if(d(),l.body&&typeof ResizeObserver<"u"){let u=new ResizeObserver(d);u.observe(l.body),Nt(n,()=>u.disconnect())}},a.srcdoc=Bs(s)}catch(s){if(n.aborted)return;h(t,o`<div class="web-error"></div>`);let i=t.querySelector(".web-error");if(i){let a=s instanceof te&&s.status===404?"There\u2019s no post here. It may have been deleted.":V(s);re(i,a,()=>ee((l,d)=>ti(e,l,d)))}}}var tt=V,Mu=[[["heading","Heading"],["bold","Bold (\u2318B)"],["italic","Italic (\u2318I)"]],[["quote","Quote"],["code","Code"],["link","Link (\u2318K)"]],[["ul","Bulleted list"],["ol","Numbered list"],["indent","Indent"]]],Iu=o` readonly`,Nu=o` hidden`,Ou=o` aria-disabled="true"`;async function ni(e,t,n){let s=()=>{n.aborted||ee((g,I)=>ni(e,g,I))},i=!1,r=(g="This post was deleted elsewhere.")=>{i||(i=!0,U(g),n.aborted||js("#/drafts"))};ie(n,"Draft"),h(t,o`<p class="muted">Loading…</p>`);let a,l=null;try{if(a=await L(`/api/posts/${e}`,{signal:n}),n.aborted)return;let g=Bu(a);if(g){js(g);return}}catch(g){if(Oe(g)){r("There\u2019s no post here. It may have been deleted.");return}re(t,tt(g),s);return}let d=Sn(a.post);if(d){try{l=await L(`/api/sends/${d.id}`,{signal:n})}catch(g){if(n.aborted)return;if(Oe(g)){r();return}}if(n.aborted||l&&cl(l.send,s))return}let{post:u,markdown:m}=a,v=Y.session?.principal??null,f=et(u,a.subject_slug_held),p=!Zt(u,"edit"),S=Zt(u,"schedule")!==void 0,$=new qs(u.current_revision),M=Mu.map((g,I)=>o`${I?o`<span class="sep"></span>`:null}${g.map(([_,B])=>o`<button type="button" class="tb" data-fmt="${_}" title="${B}" aria-label="${B}"${p?Ou:null}>${O(_)}</button>`)}`),P=p?Iu:null,A=`${location.origin}${location.pathname}${rl(e)}`;h(t,o`
113
108
  <div class="editor-head">
114
109
  <a href="#/drafts" class="back">← Drafts</a>
115
110
  <div class="editor-head-right">
116
- <span class="email-only-mark" id="headEmailOnly"${u.email_only&&!p?null:qd}>${N("mail")}Email only</span>
117
- <a class="ghost btn" id="webLink" href="${H}" target="_blank" rel="noopener" aria-label="Web version (opens in a new tab)">Web version ↗</a>
118
- <button type="button" class="ghost" id="settingsBtn">${N("settings")}<span>Post settings</span></button>
111
+ <span class="email-only-mark" id="headEmailOnly"${u.email_only&&!p?null:Nu}>${O("mail")}Email only</span>
112
+ <a class="ghost btn" id="webLink" href="${A}" target="_blank" rel="noopener" aria-label="Web version (opens in a new tab)">Web version ↗</a>
113
+ <button type="button" class="ghost" id="settingsBtn">${O("settings")}<span>Post settings</span></button>
119
114
  </div>
120
115
  </div>
121
- ${p&&d?o`<div class="banner banner-scheduled banner-split"><div class="banner-top"><div class="sched-main"><span id="schedWhen"></span><div class="sched-by" id="schedBy" hidden></div>${as("banner")}<div class="sched-remade" id="schedRemade" hidden><span id="schedRemadeMsg"></span></div><div class="sched-note" id="schedDailyWrites" hidden><span class="sched-note-mark" aria-hidden="true">⚠️</span><span class="sched-note-msg" id="schedDailyWritesMsg"></span></div></div><span class="row" id="schedControls"><button type="button" class="ghost" id="rescheduleSchedule">Edit schedule</button><button type="button" class="ghost" id="cancelSchedule">Cancel</button></span></div><div class="banner-bottom sched-dest"><span class="sched-dest-icon" id="schedDestIcon">${Po(b)}</span><span id="schedDest">${Ho(b)}</span></div></div>`:null}
116
+ ${p&&d?o`<div class="banner banner-scheduled banner-split"><div class="banner-top"><div class="sched-main"><span id="schedWhen"></span><div class="sched-by" id="schedBy" hidden></div>${bs("banner")}<div class="sched-remade" id="schedRemade" hidden><span id="schedRemadeMsg"></span></div><div class="sched-note" id="schedDailyWrites" hidden><span class="sched-note-mark" aria-hidden="true">⚠️</span><span class="sched-note-msg" id="schedDailyWritesMsg"></span></div><div class="sched-note" id="schedSandbox" hidden><span class="sched-note-mark" aria-hidden="true">⚠️</span><span class="sched-note-msg" id="schedSandboxMsg"></span></div></div><span class="row" id="schedControls"><button type="button" class="ghost" id="rescheduleSchedule">Edit schedule</button><button type="button" class="ghost" id="cancelSchedule">Cancel</button></span></div><div class="banner-bottom sched-dest"><span class="sched-dest-icon" id="schedDestIcon">${Jo(f)}</span><span id="schedDest">${Zo(f)}</span></div></div>`:null}
122
117
  <div id="freshnessBanner" class="banner banner-conflict" role="alert" hidden></div>
123
118
  <div class="editor-form">
124
119
  <label for="f-subject">Subject</label>
125
- <input id="f-subject" value="${u.subject}" placeholder="Untitled"${A}>
120
+ <input id="f-subject" value="${u.subject}" placeholder="Untitled"${P}>
126
121
 
127
122
  <label for="f-markdown">Body</label>
128
123
  <div class="composer${p?" composer-locked":""}">
129
124
  <div class="composer-head">
130
125
  <div class="ctabs" role="tablist">
131
- <button type="button" class="ctab active" data-tab="edit" data-text="Edit" role="tab" aria-selected="true"><span class="ctab-label">${N("editable")}Edit</span></button>
132
- <button type="button" class="ctab" data-tab="preview" data-text="Preview" role="tab" aria-selected="false"><span class="ctab-label">${N("preview")}Preview</span></button>
126
+ <button type="button" class="ctab active" data-tab="edit" data-text="Edit" role="tab" aria-selected="true"><span class="ctab-label">${O("editable")}Edit</span></button>
127
+ <button type="button" class="ctab" data-tab="preview" data-text="Preview" role="tab" aria-selected="false"><span class="ctab-label">${O("preview")}Preview</span></button>
133
128
  </div>
134
129
  <div class="toolbar" role="toolbar" aria-label="Formatting">${M}</div>
135
130
  </div>
136
131
  <div class="composer-body${p?" locked":""}" id="composerBody">
137
132
  <pre class="md-hl" id="mdHl" aria-hidden="true"><code></code></pre>
138
- <textarea id="f-markdown" class="editor"${p?null:o` placeholder="Type your post in Markdown…"`}${A}>${f}</textarea>
139
- <iframe id="previewFrame" class="preview" sandbox="${Yt}" title="Email preview" hidden></iframe>
133
+ <textarea id="f-markdown" class="editor"${p?null:o` placeholder="Type your post in Markdown…"`}${P}>${m}</textarea>
134
+ <iframe id="previewFrame" class="preview" sandbox="${Qt}" title="Email preview" hidden></iframe>
140
135
  </div>
141
- ${p?o`<div class="composer-foot composer-foot-lock" id="lockFoot" role="status">${N("readonly")}<span>Cancel the schedule to edit</span></div>`:o`<div class="composer-foot" id="dropFoot">${N("paperclip")}<span>Paste, drop, or click to add images</span></div>`}
136
+ ${p?o`<div class="composer-foot composer-foot-lock" id="lockFoot" role="status">${O("readonly")}<span>Cancel the schedule to edit</span></div>`:o`<div class="composer-foot" id="dropFoot">${O("paperclip")}<span>Paste, drop, or click to add images</span></div>`}
142
137
  <input type="file" id="imgInput" accept="image/png,image/jpeg,image/webp,image/gif" multiple hidden>
143
138
  </div>
144
139
  <div id="warnings"></div>
145
- ${p?null:rs("editor-not-connected",o`No email provider connected: you can write and preview, not send. ${Ae()}.`)}
140
+ ${p?null:hs("editor-not-connected",o`No email provider connected: you can write and preview, not send. ${Ae()}.`)}
146
141
 
147
142
  <div class="actions-bar">
148
- ${p?o`<div class="row test-row"><span class="test-hint" id="testHint" hidden>Not tested yet</span><button type="button" class="secondary" id="testBtn">${N("send")}<span>Send test email</span></button></div>`:o`<div class="row">
143
+ ${p?o`<div class="row test-row"><span class="test-hint" id="testHint" hidden>Not tested yet</span><button type="button" class="secondary" id="testBtn">${O("send")}<span>Send test email</span></button></div>`:o`<div class="row">
149
144
  <button type="button" class="ghost" id="saveBtn">Save draft</button>
150
145
  <span class="save-status" id="saveStatus" aria-live="polite"></span>
151
146
  </div>
152
147
  <div class="row">
153
- <button type="button" class="secondary" id="testBtn">${N("send")}<span>Send test email</span></button>
148
+ <button type="button" class="secondary" id="testBtn">${O("send")}<span>Send test email</span></button>
154
149
  <button type="button" class="primary" id="scheduleBtn">Schedule</button>
155
150
  </div>`}
156
151
  </div>
157
- </div>`);let T=c("#f-subject"),m=()=>se(n,T.value.trim()||"Untitled");m();let y=c("#f-markdown"),C=c(".toolbar",t),U=c("#previewFrame"),J=c("#mdHl"),z=c("code",J),q=()=>{J.scrollTop=y.scrollTop,J.scrollLeft=y.scrollLeft},g=()=>{h(z,ga(y.value)),q()};y.addEventListener("scroll",q),g();let E=()=>({subject:T.value,markdown:y.value}),L=null;function $(){L?.(),L=null}function _(){return T.value.trim()===""?(L=Ne(T,"Add a subject before you schedule."),T.focus(),!1):($(),!0)}let K=c("#headEmailOnly"),D=()=>{K.hidden=p||!b.emailOnly;let w=t.querySelector("#schedDestIcon");w&&h(w,Po(b));let P=t.querySelector("#schedDest");P&&h(P,Ho(b))},ae=async w=>{let P=await R(`/api/posts/${e}/settings`,{method:"PUT",json:w});b=Qe(P.post,P.subject_slug_held),D(),P.changed&&Fe()},V=async()=>{try{let w=await R(`/api/posts/${e}`,{signal:n});b=Qe(w.post,w.subject_slug_held),D()}catch{}};c("#settingsBtn").onclick=()=>{let w={...b,subject:T.value},P=pe(o`<h3 id="psHead">Post settings</h3><p class="hint">Neither is part of the email, so both stay open while the post is scheduled.</p><div id="psForm"></div><div class="actions"><button type="button" id="psCancel">Cancel</button><button type="button" class="primary" id="psSave">Save</button></div>`,n),k=c(".modal",P.el);k.setAttribute("aria-labelledby","psHead"),$t(c("#psForm",k),w,"ps"),c("#psCancel",k).onclick=P.close;let B=c("#psSave",k);B.onclick=()=>G(B,"Saving\u2026",async()=>{P.clearError();let ne=$n(b,w);if(!ne){P.close();return}try{await ae(ne),P.close(),O("Post settings saved")}catch(ce){if(n.aborted||Rt(ce)){P.close();return}En(k,"ps",ce)||P.error(Xe(ce))}}),c("#psInclude",k).focus()},p||T.addEventListener("input",()=>{m(),T.value.trim()!==""&&$()});let re=$a(()=>{Oe(!0).catch(()=>{})});Pt(n,()=>re.cancel());let lt=I(".ctab",t);function Y(w){for(let P of lt){let k=P.dataset.tab===w;P.classList.toggle("active",k),P.setAttribute("aria-selected",k?"true":"false")}y.hidden=w!=="edit",J.hidden=w!=="edit",U.hidden=w!=="preview",C.classList.toggle("off",w!=="edit"),t.querySelector("#dropFoot")?.classList.toggle("off",w!=="edit"),w==="edit"&&q()}async function le(){Y("preview");try{p||await Oe(!0),U.srcdoc=await Mt(`/api/posts/${e}/preview`),U.onload=()=>{try{let w=U.contentDocument;w&&(Zt(w),Ra(w,u.unlisted_url,H),U.style.height=`${w.body.scrollHeight+24}px`)}catch{}}}catch(w){if(n.aborted||Rt(w))return;O(Xe(w))}}for(let w of lt)w.onclick=()=>w.dataset.tab==="preview"?le():Y("edit");p&&le();let de=p?c("#lockFoot"):null,He;function Re(){de&&(de.classList.remove("nudge"),requestAnimationFrame(()=>de.classList.add("nudge")),clearTimeout(He),He=setTimeout(()=>de.classList.remove("nudge"),900))}function Pe(w,P,k){let B=y.selectionStart,ne=y.selectionEnd,ce=y.value.slice(B,ne)||k;y.value=y.value.slice(0,B)+w+ce+P+y.value.slice(ne),y.focus(),y.selectionStart=B+w.length,y.selectionEnd=B+w.length+ce.length}function ct(w){let P=y.selectionStart,k=y.selectionEnd,B=y.value.lastIndexOf(`
158
- `,P-1)+1,ne=(y.value.slice(B,k)||"").split(`
159
- `).map(ce=>w+ce).join(`
160
- `);y.value=y.value.slice(0,B)+ne+y.value.slice(k),y.focus(),y.selectionStart=B,y.selectionEnd=B+ne.length}function dt(w){if(p){Re();return}if(Y("edit"),w==="bold")Pe("**","**","bold text");else if(w==="italic")Pe("*","*","italic text");else if(w==="heading")ct("## ");else if(w==="quote")ct("> ");else if(w==="ul")ct("- ");else if(w==="ol")ct("1. ");else if(w==="indent")ct(" ");else if(w==="link")Pe("[","](https://)","link text");else if(w==="code"){let P=y.selectionStart,k=y.selectionEnd;P===k||y.value.slice(P,k).includes(`
161
- `)?Pe("```\n","\n```","code"):Pe("`","`","code")}Js()}for(let w of I(".tb[data-fmt]",t))w.onclick=()=>dt(w.dataset.fmt??"");y.addEventListener("keydown",w=>{if(!(w.metaKey||w.ctrlKey))return;let P=w.key.toLowerCase();P==="b"?(w.preventDefault(),dt("bold")):P==="i"?(w.preventDefault(),dt("italic")):P==="k"&&(w.preventDefault(),dt("link"))});let ue=!1,On=!1,Ve=!1,et=null,ut=0,Dn=!1,Ys=0,Me=p?null:c("#saveBtn"),Ie=p?null:c("#saveStatus"),Tt=new Cs(E),nn=!1;function Zs(){Ie&&(p?(Ie.className="save-status",Ie.textContent=""):nn?(Ie.className="save-status is-saving",Ie.textContent="Saving\u2026"):et&&ue?(Ie.className="save-status is-error",Ie.textContent=`Not saved: ${et}`):ue?(Ie.className="save-status is-dirty",Ie.textContent="Unsaved changes"):(Ie.className="save-status is-saved",Ie.textContent="Saved"))}function Un(){ue=Tt.dirty,ue||(et=null,On=!1,ut=0),Zs()}Zs();function xi(){re.touch()}function Js(){p||(g(),Un(),Ve||xi())}let Lt=Promise.resolve();function Oe(w){let P=Lt.catch(()=>{}).then(()=>zl(w));return Lt=P,No(Lt),P}async function zl(w){if(w&&!Tt.dirty)return"unchanged";if(Ve)return"refused";re.cancel(),nn=!0,Zs();let P=E(),k=JSON.stringify(P);try{let B={...P,base_revision:x.base},{post:ne,subject_slug_held:ce}=await R(`/api/posts/${e}`,{method:"PUT",json:B});return b=Qe(ne,ce),D(),x.saved(ne.current_revision),Tt.markSaved(k),On=!1,et=null,ut=0,w||O("Saved"),"saved"}catch(B){let ne=ka(B);if(ne)return Ti(ne),"refused";if(Be(B))return a(),"refused";On=!0;let ce=B instanceof te&&B.field==="subject"?T:void 0;if(ce?(Ne(ce,F(B)),et="fix the field marked above."):et=F(B),!(lo(B)||B instanceof te&&(B.status>=500||B.status===429)))Ys+=1,Dn=!1,ut=0;else if(!Dn){Dn=!0,ut=ut?Math.min(ut*2,6e4):5e3;let ie=Ys;ft(Date.now()+ut,()=>{ie===Ys&&(Dn=!1,et&&!Ve&&Oe(!0).catch(()=>{}))},n)}throw B}finally{nn=!1,Un()}}Me&&(Me.onclick=()=>{if(Ve){Ke.scrollIntoView({block:"nearest"});return}G(Me,"Saving\u2026",()=>Oe(!1).catch(()=>{})).finally(Un)});function ki(){Me&&(Ve?(Me.setAttribute("aria-disabled","true"),Me.title="Saving is paused: choose Reload or Keep editing above"):(Me.removeAttribute("aria-disabled"),Me.removeAttribute("title")))}let Yl=()=>{if(re.cancel(),p||!Tt.dirty)return;let w=E(),P=JSON.stringify(w);ue=!1,Lt=Lt.catch(()=>{}).then(async()=>{if(!Tt.dirty)return;let k={...w,base_revision:x.base},{post:B}=await R(`/api/posts/${e}`,{method:"PUT",json:k});x.saved(B.current_revision),Tt.markSaved(P)}).catch(k=>{if(Be(k)){O("This post was deleted elsewhere, so your last edits weren\u2019t saved.");return}O(k instanceof te&&k.status===409?"Changed elsewhere, so your edits weren\u2019t saved":`Couldn\u2019t save your changes: ${Xe(k)}`)}),No(Lt)},Zl={dirty:()=>ue,beforeLeave(){return i?"leave":ue&&(On||Ve)?"confirm":(Yl(),"leave")},manualSave(){Me&&!Me.disabled&&Me.click()}};if(!p){for(let w of[T,y])w.addEventListener("input",Js);for(let w of[T])w.addEventListener("blur",()=>Oe(!0).catch(()=>{})),w.addEventListener("keydown",P=>{P.key==="Enter"&&!P.isComposing&&P.keyCode!==229&&(P.preventDefault(),Oe(!0).catch(()=>{}))})}let Ke=c("#freshnessBanner");function _i(){Ve=!1,ki(),x.clearWarning(),Ke.hidden=!0,h(Ke,o``)}function Ti(w){if(p)return;if(Ve=!0,et=null,ki(),x.noteWarned(w),w.kind==="locked")h(Ke,o`<span><span aria-hidden="true">⚠️</span> This draft was scheduled elsewhere and can no longer be edited here.</span><span class="row"><button type="button" class="ghost" id="freshReload">Reload</button></span>`);else{let k=Jt(w.author,w.client);h(Ke,o`<span><span aria-hidden="true">⚠️</span> This draft was changed elsewhere${k?o`, last edited by <strong>${k}</strong>`:null}. Saving is paused until you choose: Reload to load that version (discards your unsaved edits), or Keep editing to keep yours, and your next save overwrites that version.</span><span class="row"><button type="button" class="ghost" id="freshReload">Reload</button><button type="button" class="ghost" id="freshKeep">Keep editing</button></span>`)}Ke.hidden=!1,c("#freshReload",Ke).onclick=()=>{_i(),s()};let P=Ke.querySelector("#freshKeep");P&&(P.onclick=()=>{x.adoptWarned(),_i(),Un(),ue&&xi()})}function Rt(w){return Be(w)?(a(),!0):!1}if(!p){let w=async()=>{if(nn||Ve||i||document.hidden)return;let P=x.base;try{let k=await R(`/api/posts/${e}`,{signal:n}),B=x.decide({status:k.post.status,revision:k.post.current_revision,author:k.post.author,client:k.post.author_client},{saving:nn,baseAtRequest:P});B!=="ignore"&&B!=="fresh"&&Ti(B)}catch(k){Be(k)&&a()}};mt(1e4,w,n),Kd(w,n)}if(c("#webLink").addEventListener("click",()=>{p||Oe(!0).catch(()=>{})}),p&&d){let w=l?.send??{...d,conditions:[]},P=c("#schedWhen"),k=c("#schedControls"),B="",ne=0,ce=!1,Ee=c("#rescheduleSchedule"),ie=c("#cancelSchedule"),Z=be=>w.actions===void 0||Ze({actions:w.actions},be),Se=()=>{let be=Date.now(),ke=w.phase==="due"||be>=w.fire_at;ke?ce||(Ee.hidden=!0,ie.hidden=!0):(ce=!0,Ee.hidden=!Z("reschedule"),ie.hidden=!Z("cancel")),Ee.disabled=ke,ie.disabled=ke,k.hidden=Ee.hidden&&ie.hidden;let _e=Wd(w,ke),At=String(_e);At!==B&&(B=At,h(P,_e)),!ke&&w.fire_at-be<=1e3&&w.fire_at!==ne&&(ne=w.fire_at,ft(w.fire_at,Se,n))};Se(),mt(1e3,Se,n);let pt=c("#schedRemade"),De=c("#testHint"),xe=c("#schedDailyWrites"),sn=c("#schedBy"),Ct=()=>{let be=Sa(w,S);sn.hidden=be===null,sn.textContent=be??"";let ke=he(w,"remade");pt.hidden=!ke,c("#schedRemadeMsg").textContent=ke?.message??"",De.hidden=!he(w,"untested");let _e=he(w,"daily_writes");xe.hidden=!_e,c("#schedDailyWritesMsg").textContent=_e?.message??""};Ct();let on=be=>mn(be,{update(ke,_e){let At=!_e&&ke.rev!==w.rev;if(w=ke,At&&V(),_e?.to==="sending"||_e?.to==="sent"||_e?.to==="complete"){O("Your send started, so this page switched to its live watch."),Hs(`#/sent/${ke.id}`);return}if(_e?.to==="canceled"){O("The schedule was canceled elsewhere, so this post is a draft again."),s();return}Se(),Ct()},removed:a,stale:s},n);l?on(l):Hi(5e3,async()=>{let be=await R(`/api/sends/${d.id}`,{signal:n});return Ca(be.send,s)||(w=be.send,Se(),Ct(),on(be)),!1},n),Ee.onclick=()=>{Ts({id:w.id,post_id:e,fire_at:w.fire_at},s,n,{...b})},ie.onclick=()=>G(ie,"Canceling\u2026",async()=>{try{await R(`/api/sends/${d.id}/cancel`,{method:"POST"}),O("Schedule canceled"),s()}catch(be){Be(be)?a():be instanceof te&&be.code==="window_closed"?(w={...w,phase:"due"},O("Too late to cancel: the send time has passed, so this email is going out."),Fe()):O(Xe(be))}}).finally(Se)}async function Qs(w){if(w.type.startsWith("image/"))try{let P=new FormData;P.append("file",w);let{image:k}=await R(`/api/posts/${e}/images`,{method:"POST",body:P}),B=y.selectionStart,ne=`
162
- ![${w.name}](${k.filename})
163
- `;y.value=y.value.slice(0,B)+ne+y.value.slice(B),y.selectionStart=y.selectionEnd=B+ne.length,Js(),O("Image added")}catch(P){Rt(P)||O(Xe(P))}}let Ge=c("#composerBody");if(p){let w=k=>k.metaKey||k.ctrlKey?["x","z","y"].includes(k.key.toLowerCase()):k.key.length===1||k.key==="Enter"||k.key==="Backspace"||k.key==="Delete",P=[y,T];for(let k of P)k.addEventListener("keydown",B=>{w(B)&&Re()}),k.addEventListener("paste",Re);Ge.addEventListener("dragover",k=>k.preventDefault()),Ge.addEventListener("drop",k=>{k.preventDefault(),Re()})}else{let w=c("#imgInput"),P=c("#dropFoot");Ge.addEventListener("dragover",k=>{k.preventDefault(),Ge.classList.add("dragover")}),Ge.addEventListener("dragleave",k=>{k.target===Ge&&Ge.classList.remove("dragover")}),Ge.addEventListener("drop",k=>{k.preventDefault(),Ge.classList.remove("dragover"),Y("edit");for(let B of k.dataTransfer?.files??[])Qs(B)}),y.addEventListener("paste",k=>{for(let B of k.clipboardData?.items||[])if(B.type.startsWith("image/")){let ne=B.getAsFile();ne&&(k.preventDefault(),Qs(ne))}}),P.onclick=()=>w.click(),w.onchange=()=>{for(let k of w.files??[])Qs(k);w.value=""}}let Jl=c("#warnings");function Ql(w){h(Jl,w?.length?o`<div class="warnings"><strong>Warnings:</strong> ${w.join("; ")}</div>`:o``)}c("#testBtn").onclick=()=>{let w=p?"Delivers the frozen copy that will send, exactly as it will fire, so you can check it in a client. One address per line.":"Delivers the rendered email to real inboxes so you can check it in a client. One address per line.",P=ve(),k=pe(o`<h3>Send a test</h3><p class="hint">${w}</p>${cs()}${P?null:o`<label for="testTo">Recipients</label><textarea id="testTo" rows="3" placeholder="you@example.com"></textarea><p class="hint" id="testDefaultsHint" hidden></p>`}<div class="actions"><button type="button" id="tCancel">Cancel</button><button type="button" class="primary" id="tGo">Send test</button></div>`,n),B=c("#tGo",k.el);if(c("#tCancel",k.el).onclick=k.close,B.disabled=P,P){c("#tCancel",k.el).focus();return}let ne=c("#testTo",k.el);ne.focus(),R("/api/settings").then(ce=>{let Ee=ce.settings.test_recipients||[];if(Ee.length&&!ne.value.trim()){ne.value=Ee.join(`
164
- `),k.clearError();let ie=c("#testDefaultsHint",k.el);ie.textContent="Pre-filled from your default test recipients (Settings).",ie.hidden=!1}}).catch(()=>{}),B.onclick=()=>G(B,"Sending\u2026",async()=>{k.clearError();let{valid:ce,invalid:Ee}=fs(ne.value),ie=hs(Ee);if(ie){k.error(ie,ne);return}if(!ce.length){k.error("Enter at least one email address",ne);return}try{p||await Oe(!0);let Z=0,Se=[],pt=null;for(let De of ce)try{let xe=await R(`/api/posts/${e}/test`,{method:"POST",json:{to:De}});xe.sent?Z++:Se.push({email:De,message:xe.not_sent?.message??""}),pt=xe.warnings}catch(xe){if(Be(xe)||xe instanceof te&&xe.status===401)throw xe;Se.push({email:De,message:F(xe)})}if(Ql(pt),p&&Z>0&&Fe(),Se.length){ne.value=Se.map(De=>De.email).join(`
165
- `),k.error(bs(Z,ce.length,Se));return}k.close(),O(Nt(`Test sent to ${Z} address${Z===1?"":"es"}`))}catch(Z){if(Be(Z)){k.close(),Rt(Z);return}k.error(Xe(Z))}})};let Li=p?null:c("#scheduleBtn");return Li&&(Li.onclick=()=>{if(!_())return;let w=yt(os()),P=yt(new Date(Date.now()+24*3600*1e3)),k=!v,B={...b,subject:T.value};B.slugAuto&&!B.slugTaken&&(B.slug=ks(B.subject)||B.slug);let ne="It sends at the time you pick, with a cancelable window until then.",ce=()=>o`<h3 id="schHead">Schedule this post</h3><p class="hint" id="schHint">${ne}</p>${Ki()}${vo()}${k?null:o`<label for="schWhen">Send at</label><input type="datetime-local" id="schWhen" min="${w}" value="${P}"><div class="dialog-settings" id="schForm"></div>`}<div class="actions"><button type="button" id="schCancel">Cancel</button><button type="button" class="primary" id="schGo">Schedule</button></div>${k?null:o`<div class="altrow"><span class="altrow-note">Or send as soon as possible.</span><button type="button" class="linkbtn" id="toSendNow">Send now →</button></div>`}`,Ee=P,ie=pe(ce(),n),Z=c(".modal",ie.el),Se=null,pt=()=>(Se??=R("/api/subscribers?status=confirmed&suppressed=hide&limit=1",{signal:n}).then(me=>me.page.total).catch(()=>null),Se),De=async()=>{if(!Z.querySelector("#schDailyWrites"))return;let me=await pt(),Ce=Z.querySelector("#schDailyWrites");Ce&&me!==null&&me>Ao&&(Ce.textContent=ca(me),Ce.hidden=!1)},xe=()=>{ie.close(),Ke.scrollIntoView({block:"nearest"})},sn=()=>$t(c("#schForm",Z),B,"sch"),Ct=()=>({email_only:B.emailOnly,...$n(b,B)}),on=me=>{En(Z,"sch",me)||ie.error(Xe(me))},be=()=>G(c("#schGo",Z),"Scheduling\u2026",async()=>{ie.clearError();let me=c("#schWhen",Z),Ce=me.value?new Date(me.value).getTime():Number.NaN;if(Number.isNaN(Ce)){ie.error("Pick a valid date & time",me);return}if(ss(Ce)){ie.error(ns(),me);return}try{if(await Oe(!0)==="refused"){xe();return}await R(`/api/posts/${e}/schedule`,{method:"POST",json:{fire_at:new Date(Ce).toISOString(),...Ct()}}),ie.close(),O(Nt(`Scheduled for ${W(Ce)}. Send yourself a test.`)),s()}catch(ze){if(Be(ze)){ie.close(),Rt(ze);return}if(ze instanceof te&&ze.field==="fire_at"){ie.error(Xe(ze),c("#schWhen",Z));return}on(ze)}}),ke=()=>G(c("#snGo",Z),"Queuing\u2026",async()=>{ie.clearError();try{if(await Oe(!0)==="refused"){xe();return}let{send:me}=await R(`/api/posts/${e}/send`,{method:"POST",json:Ct()});ie.close(),O(Nt(`Sends at ${W(me.fire_at)}, cancelable until then.`)),s()}catch(me){if(Be(me)){ie.close(),Rt(me);return}on(me)}});function _e(){if(Z.setAttribute("aria-labelledby","schHead"),c("#schCancel",Z).onclick=ie.close,c("#schGo",Z).onclick=be,c("#schGo",Z).disabled=k,k){c("#schCancel",Z).focus();return}c("#toSendNow",Z).onclick=At,c("#schWhen",Z).value=Ee,sn(),c("#schWhen",Z).focus(),De()}async function At(){let me=Z.querySelector("#schWhen");me&&(Ee=me.value),h(Z,o`<h3 id="snHead">Send now?</h3><p class="hint">Sends this draft, as it is now, to <strong id="snWho">your subscribers</strong> in ${Wi()}. The post locks until then, and you can cancel any time before it starts sending.</p><div class="dialog-settings" id="schForm"></div>${vo()}<div class="actions"><button type="button" class="linkbtn actions-back" id="toSchedule">← Back to schedule</button><button type="button" id="snCancel">Cancel</button><button type="button" class="primary" id="snGo">Send now</button></div>`),Z.setAttribute("aria-labelledby","snHead"),c("#snCancel",Z).onclick=ie.close,c("#snGo",Z).onclick=ke,sn(),c("#snGo",Z).disabled=!Gt(u,"send_now"),c("#toSchedule",Z).onclick=()=>{h(Z,ce()),_e()},c("#snGo",Z).focus(),De();let Ce=await pt(),ze=Z.querySelector("#snWho");ze&&Ce!==null&&(ze.textContent=`${Ce} recipient${Ce===1?"":"s"}`)}_e()}),Zl}function Ca(e,t){return e.status==="sending"||e.status==="sent"?(Hs(`#/sent/${e.id}`),!0):e.status==="canceled"?(t(),!0):!1}function Wd(e,t){return Le(e,"missed")?o`Scheduled for <strong>${W(e.fire_at)}</strong> · <span class="countdown countdown-missed">${gs(e.fire_at)}</span>`:t?o`Scheduled for <strong>${W(e.fire_at)}</strong> · <span class="countdown">${fn(e.fire_at,!0)}</span>`:o`Scheduled for <strong>${W(e.fire_at)}</strong> · <span class="countdown">${fn(e.fire_at)}</span>`}function Be(e){return e instanceof te&&e.status===404}function Vd(e){let t=e.post.send;return t?.status==="sending"?`#/sent/${t.id}`:e.post.status==="sent"?t?`#/sent/${t.id}`:"#/sent":null}function Hs(e){location.replace(e)}function Kd(e,t){document.addEventListener("visibilitychange",()=>{document.hidden||e()},{signal:t})}function Gd(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-")}function Aa(e){let t=new Map;return e.map(n=>{let s=Gd(n),i=t.get(s)??0;return t.set(s,i+1),i?`${s}-${i}`:s})}var Do=null;function zd(e){let t=document.createElement("div");h(t,j(e.html||""));let n=(t.querySelector("p")?.textContent||"").trim().replace(/\s+/g," "),s=/[:;,]$/.test(n),i=n.replace(/[\s:;,]+$/,""),a=150;return i.length>a?`${i.slice(0,a).replace(/[\s.,;:]+\S*$/,"")}\u2026`:s?`${i}\u2026`:i}function Yd(e){let t=e.querySelector("code"),n=t?.className.match(/(?:^|\s)language-(\S+)/)?.[1]??null,s=(t??e).textContent?.replace(/\n$/,"")??"",i=n==="bash"||n==="sh"||n==="shell"?Rs(s):n==="json"||n==="jsonc"?Io(s):o`${s}`;return Zr(i,s)}async function Uo(e,t,n,s){if(se(n,"Docs"),h(t,Bt("docs",null,o`<div class="docs-index"><p class="muted">Loading…</p></div>`)),!Do)try{Do=await R("/api/docs",{signal:n})}catch(d){n.aborted||oe(c(".room-main",t),F(d),()=>ee((u,f)=>Uo(e,u,f,s)));return}let{sets:i,docs:a}=Do,r=i[0];if(!a.length||!r){h(c(".room-main"),o`<p class="muted">No documentation.</p>`);return}let l=e?i.find(d=>d.id===e):r;l?Ma(t,l,i,a,n):e&&Qd(t,i,a,e,n,s?Zd(s):void 0)}function Zd(e){try{return decodeURIComponent(e)}catch{return}}function Ma(e,t,n,s,i){se(i,`${t.name} docs`);let a=(b,p)=>{let v=zd(b);return o`<li><a class="doc-card" href="#/docs/${b.slug}">${p===null?null:o`<span class="doc-card-n">${String(p).padStart(2,"0")}</span>`}<span class="doc-card-main"><span class="doc-card-t">${b.title} <span class="doc-card-go" aria-hidden="true">→</span></span>${v?o`<span class="doc-card-d">${v}</span>`:null}</span></a></li>`},r=t.sections.map(b=>{let p=s.filter(M=>M.set===t.id&&M.section===b.id);if(!p.length)return null;let v=p.map((M,A)=>a(M,b.numbered?A+1:null)),x=b.blurb?o`<div class="doc-section-blurb">${j(b.blurb)}</div>`:null;return o`<section class="doc-section"><h2 class="doc-section-t">${b.title}</h2>${x}${b.numbered?o`<ol class="doc-cards">${v}</ol>`:o`<ul class="doc-cards">${v}</ul>`}</section>`}),l=o`<nav class="docs-tabs" aria-label="Doc sets">${n.map(b=>o`<a href="#/docs/${b.id}" title="${b.title}"${b.id===t.id?o` aria-current="page"`:null}>${b.name}</a>`)}</nav>`,d=o`<div class="docs-index"><h1>Kestrel docs</h1><p class="docs-index-intro"><strong>Publishing</strong> covers writing and sending your newsletter, from naming your publication to what happens after each send. <strong>Self-hosting</strong> covers deploying Kestrel to your own Cloudflare account and keeping it running. One person often does both.</p>${l}${r}</div>`,u=Q.appConfig?.deployment.build.repo_url||"",f=(b,p,v=p)=>o`<a class="rail-link" href="${b}" target="_blank" rel="noopener" aria-label="${p}"><span class="rail-link-full">${p}</span><span class="rail-link-short" aria-hidden="true">${v}</span> <span aria-hidden="true">↗</span></a>`,S=o`<div class="toc-label">Kestrel</div>${f("https://getkestrel.dev","Project site","Project")}${u?[f(u,"Source on GitHub","Source"),f(`${u}/blob/HEAD/LICENSE`,"License")]:null}`;h(e,Bt("docs",S,d)),window.scrollTo(0,0)}var Fo=matchMedia("(max-width: 720px)");function Ia(e){if(!e)return;let t=Fo.matches;e.open=!t,c("summary",e).tabIndex=t?0:-1}var Na=()=>document.querySelector("details#tocOnPage"),Ha=!1;function Jd(){Ha||(Ha=!0,Fo.addEventListener("change",()=>Ia(Na())))}var Pa=e=>`doc-h-${e}`;function Qd(e,t,n,s,i,a){let r=n.findIndex($=>$.slug===s),l=n[r],d=t.find($=>$.id===l?.set);if(!l||!d){let $=t[0];O(`No doc named \u201C${s}\u201D, so here\u2019s the index.`),history.replaceState(history.state,"","#/docs"),$&&Ma(e,$,t,n,i);return}se(i,l.title);let u=n.filter($=>$.set===l.set&&$.section===l.section),f=u.indexOf(l),S=u[f-1],b=u[f+1],p=($,_)=>o`<a href="#/docs/${$.slug}" aria-label="${_}: ${$.title}">${_==="Previous"?o`<span aria-hidden="true">←</span><span class="doc-topnav-word">Previous</span>`:o`<span class="doc-topnav-word">Next</span><span aria-hidden="true">→</span>`}</a>`,v=S||b?o`<nav class="doc-topnav" aria-label="Adjacent docs">${S?p(S,"Previous"):null}${b?p(b,"Next"):null}</nav>`:null;h(e,Bt("docs",o`<div id="docToc"></div>`,o`<article class="doc" id="docsMain"></article>`));let x=c("#docToc"),M=c("#docsMain");h(M,o`<section class="doc-part" id="doc-${l.slug}">${j(l.html)}</section>`);let A=c("section.doc-part",M),H=I("h1, h2, h3, h4",A),T=Aa(H.map($=>$.textContent||""));for(let[$,_]of H.entries()){let K=T[$]??"";_.dataset.anchor=K,_.id=Pa(K)}let m=A.querySelector("h1"),y=[];if(m&&y.push({id:m.id,anchor:"",title:m.textContent||l.title}),v){let $=document.createElement("div");$.className="doc-head",h($,v),m?(m.before($),$.prepend(m)):A.prepend($)}let C=document.createElement("p");C.className="eyebrow doc-set",h(C,o`<a href="#/docs/${d.id}">${d.name}</a>`),A.prepend(C);for(let $ of I("h2",A))y.push({id:$.id,anchor:$.dataset.anchor||"",title:$.textContent||""});let U=document.createElement("nav");U.className="doc-pager",h(U,o`${S?o`<a class="doc-pager-btn prev" href="#/docs/${S.slug}"><span class="doc-pager-dir">← Previous</span><span class="doc-pager-title">${S.title}</span></a>`:o`<span></span>`}${b?o`<a class="doc-pager-btn next" href="#/docs/${b.slug}"><span class="doc-pager-dir">Next →</span><span class="doc-pager-title">${b.title}</span></a>`:o`<span></span>`}`),M.appendChild(U);let J=y.map($=>o`<a class="toc-sub" href="#/docs/${l.slug}${$.anchor?`/${$.anchor}`:""}" data-target="${$.id}">${$.title}</a>`);h(x,y.length?o`<details class="toc-onpage" id="tocOnPage"><summary class="toc-label">On this page</summary>${J}</details>`:o``);let z=Na();Ia(z),Jd();let q=$=>{if(z)for(let _ of I(".toc-sub",z))_.classList.toggle("on",_.dataset.target===$)};x.addEventListener("click",$=>{let _=$.target instanceof Element?$.target.closest("a[data-target]"):null,K=_?.dataset.target;K&&($.preventDefault(),q(K),z&&Fo.matches&&(z.open=!1),history.replaceState(history.state,"",_?.getAttribute("href")??location.hash),document.getElementById(K)?.scrollIntoView({block:"start"}))});for(let $ of I("a[href^='http']",M))$.target="_blank",$.rel="noopener";for(let $ of I("pre",A)){let _=document.createElement("div");h(_,Yd($)),$.replaceWith(..._.childNodes)}je(M);let g=y.map($=>$.id),E=g[0];if(z&&E){let $=g[g.length-1]??E,K=(document.querySelector(".room-bar")?.getBoundingClientRect().height||54)+26,D=()=>{if(!document.getElementById(E)){document.onscroll=null;return}let ae=E;if(Math.ceil(window.innerHeight+window.scrollY)>=document.documentElement.scrollHeight)ae=$;else for(let V of g)if((document.getElementById(V)?.getBoundingClientRect().top??Number.POSITIVE_INFINITY)<=K)ae=V;else break;q(ae)};document.onscroll=D,D()}let L=a?document.getElementById(Pa(a)):null;L?L.scrollIntoView({block:"start"}):window.scrollTo(0,0)}function qo(e){let t=new Set(e.groups.flatMap(n=>n.routes.flatMap(s=>(s.errors??[]).map(i=>i.code))));return e.refusals.flatMap(n=>n.codes.filter(s=>!t.has(s.code)).map(s=>({...s,move:n.move})))}function xt(e){return e.replace(/\([^)]*\)/g,"").replace(/\{[^}]*\}\??/g,"")||"/"}function Qt(e){return e.title.toLowerCase().replace(/'s\b/g,"").split(/[^a-z0-9]+/).filter(t=>t!==""&&t!=="a"&&t!=="an"&&t!=="the").join("-")}var Xd=/`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g;function eu(e){return/^https:\/\//i.test(e)||/^\/(?![/\\])/.test(e)}function ge(e){let t=[],n=0;for(let s of e.matchAll(Xd)){let i=s.index??0;t.push(e.slice(n,i));let[,a,r,l,d]=s;a!==void 0?t.push(o`<code>${a}</code>`):r!==void 0?t.push(o`<strong>${ge(r)}</strong>`):l!==void 0&&d!==void 0&&t.push(eu(d)?o`<a href="${d}">${ge(l)}</a>`:ge(l)),n=i+s[0].length}return t.push(e.slice(n)),o`${t}`}function xn(e,t){return o`${e.split(/\n\s*\n/).filter(n=>n.trim()).map(n=>{let s=n.trim().split(`
166
- `),i=s.findIndex(l=>l.startsWith("- "));if(i===-1)return o`<p class="${t}">${ge(n.trim())}</p>`;let a=s.slice(0,i).join(" ").trim(),r=s.slice(i).reduce((l,d)=>(d.startsWith("- ")||l.length===0?l.push(d.replace(/^- /,"")):l[l.length-1]=`${l[l.length-1]} ${d.trim()}`,l),[]);return o`${a?o`<p class="${t}">${ge(a)}</p>`:null}<ul class="${t} prose-list">${r.map(l=>o`<li>${ge(l)}</li>`)}</ul>`})}`}function tu(e){return e==="access"?['-H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID"','-H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET"']:['-H "Authorization: Bearer $TOKEN"']}function Ba(e,t,n){if(e.access==="webhook")return null;let s=(e.query??[]).filter(l=>l.required),i=s.length?`?${s.map(l=>`${l.name}=:${l.name}`).join("&")}`:"",a=`"${t}${xt(e.path)}${i}"`,r=[e.method==="GET"?`curl ${a}`:`curl -X ${e.method} ${a}`];if(e.access==="admin"&&r.push(...tu(n)),e.example?.request!==void 0){let l=JSON.stringify(e.example.request).replaceAll("'","'\\''");r.push('-H "Content-Type: application/json"',`-d '${l}'`)}else if(e.accepts?.includes("multipart/form-data"))for(let l of(e.body??[]).filter(d=>d.required))r.push(`-F "${l.name}=${l.type==="file"?"@":""}:${l.name}"`);return r.join(` \\
167
- `)}function Wo(e,t){return t===void 0?null:zt(e,va(t),JSON.stringify(t,null,2))}function nu(e){let t=Ba(e,location.origin,Q.session?.auth.mode??"dev");return t===null?null:zt("curl",Rs(t),t)}function Ps(e){return o`${e.split(/(?<=[_./])/).map((t,n)=>o`${n?o`<wbr>`:null}${t}`)}`}function rt(e,t,n,s){return o`<div class="block api-sec"><div class="block-head"><span class="block-label">${e}${n?o`<span class="api-sec-meta">${n}</span>`:null}</span></div>${s??null}${t}</div>`}function Vo(e,t,n,s){return o`<div class="api-row"><div class="api-row-head"><code class="api-row-name">${Ps(e)}</code>${t?o`<span class="api-row-type">${t}</span>`:null}${n?o`<span class="api-req">Required</span>`:null}</div><div class="api-row-desc">${s}</div></div>`}function Ko(e,t,n,s){return o`<div class="api-lrow"><span class="api-st api-st-${String(e)[0]}xx">${e}</span><div><div class="api-row-head"><code class="api-row-name">${t}</code></div>${n?o`<div class="api-with">${n}</div>`:null}<div class="api-row-desc">${s}</div></div></div>`}function su(e){if(!e?.length)return null;let t=e.map(n=>Vo(n.name,null,n.required,ge(n.description)));return rt("Query",o`<div class="api-list api-query">${t}</div>`)}function ou(e,t){if(!e?.length)return null;let n=e.map(i=>Vo(i.name,i.type,i.required,ge(i.description))),s=t?.length?o` · ${t.map((i,a)=>o`${a?", ":""}<code>${i}</code>`)}`:null;return rt("Body",o`<div class="api-list api-body">${n}</div>`,s)}function iu(e,t){if(!e?.length)return null;let n=e.map(s=>Ko(s.status,Ps(s.code),s.details?.length?o`with ${s.details.map((i,a)=>o`${a?", ":""}<code>${i}</code>`)}`:null,o`${ge(s.when??t.get(s.code)??"")}<span class="api-move-next">${s.move}</span>`));return rt("Refusals",o`<div class="api-ledger api-errors">${n}</div>`)}function ru(e){let t=s=>o`<ul class="api-values">${s.map(i=>o`<li><code>${i.value}</code> ${ge(i.description)}</li>`)}</ul>`,n=[...new Set(e.map(s=>s.group).filter(s=>s!==void 0))];return n.length?o`${n.map(s=>o`<div class="api-values-group">${ge(s)}</div>${t(e.filter(i=>i.group===s))}`)}`:t(e)}function Go(e){let t=e.map(n=>Vo(n.name,n.object?o`<a href="#/api-reference/objects-${n.object}" class="api-obj-link" data-sec="objects-${n.object}">${n.type}</a>`:n.type,!1,o`${ge(n.description)}${n.values?.length?ru(n.values):null}`));return o`<div class="api-list api-fields">${t}</div>`}function au(e,t){if(!e)return null;let n=e.object?o`<a href="#/api-reference/objects-${e.object}" class="api-obj-link" data-sec="objects-${e.object}">${t.get(e.object)??e.object}</a>`:null,s=n?e.as?o`<p class="api-returns"><code>${e.as}</code>: ${e.list?o`a list of ${n}`:n}${e.fields?.length?", and:":null}</p>`:o`<p class="api-returns">${n}${e.fields?.length?", and:":null}</p>`:null;return rt("Returns",e.fields?.length?Go(e.fields):null,null,s)}function lu(e){return o`${xt(e).split(/(:[A-Za-z_]+)/).map((t,n)=>n%2?o`<span class="api-param">${t}</span>`:t)}`}function kn(e,t){return"route"in t?o`<a class="api-self" href="#/api-reference/${t.route}" data-route="${t.route}">${N("link")}${e}</a>`:o`<a class="api-self" href="#/api-reference/${t.sec}" data-sec="${t.sec}">${N("link")}${e}</a>`}function cu(e){let t=new Map;for(let n of e.objects){let s=e.groups.find(i=>i.resources.some(a=>a.key===n.resource));if(s){let i=`${s.access}-${n.resource}`;t.set(i,[...t.get(i)??[],n])}}return t}function du(e,t){let n=e.returns?.object;return[e.title,e.method,xt(e.path),e.summary,...(e.errors??[]).map(s=>s.code),...n?[n,t.objects.get(n)??"",e.returns?.as??""]:[]].join(" ").toLowerCase()}function uu(e,t){return o`<li data-hay="${du(e,t)}" data-path="${xt(e.path).toLowerCase()}" id="route-${Qt(e)}" data-route="${Qt(e)}"><article class="api-op">
152
+ </div>`);let H=c("#f-subject"),y=()=>ie(n,H.value.trim()||"Untitled");y();let w=c("#f-markdown"),T=c(".toolbar",t),D=c("#previewFrame"),R=c("#mdHl"),F=c("code",R),K=()=>{R.scrollTop=w.scrollTop,R.scrollLeft=w.scrollLeft},b=()=>{h(F,Za(w.value)),K()};w.addEventListener("scroll",K),b();let E=()=>({subject:H.value,markdown:w.value}),C=null;function x(){C?.(),C=null}function W(){return H.value.trim()===""?(C=qe(H,"Add a subject before you schedule."),H.focus(),!1):(x(),!0)}let oe=c("#headEmailOnly"),k=()=>{oe.hidden=p||!f.emailOnly;let g=t.querySelector("#schedDestIcon");g&&h(g,Jo(f));let I=t.querySelector("#schedDest");I&&h(I,Zo(f))},G=async g=>{let I=await L(`/api/posts/${e}/settings`,{method:"PUT",json:g});f=et(I.post,I.subject_slug_held),k(),I.changed&&Fe()},q=async()=>{try{let g=await L(`/api/posts/${e}`,{signal:n});f=et(g.post,g.subject_slug_held),k()}catch{}};c("#settingsBtn").onclick=()=>{let g={...f,subject:H.value},I=fe(o`<h3 id="psHead">Post settings</h3><p class="hint">Neither is part of the email, so both stay open while the post is scheduled.</p><div id="psForm"></div><div class="actions"><button type="button" id="psCancel">Cancel</button><button type="button" class="primary" id="psSave">Save</button></div>`,n),_=c(".modal",I.el);_.setAttribute("aria-labelledby","psHead"),_t(c("#psForm",_),g,"ps"),c("#psCancel",_).onclick=I.close;let B=c("#psSave",_);B.onclick=()=>Z(B,"Saving\u2026",async()=>{I.clearError();let se=Cn(f,g);if(!se){I.close();return}try{await G(se),I.close(),U("Post settings saved")}catch(ce){if(n.aborted||Pt(ce)){I.close();return}An(_,"ps",ce)||I.error(tt(ce))}}),c("#psInclude",_).focus()},p||H.addEventListener("input",()=>{y(),H.value.trim()!==""&&x()});let ne=tl(()=>{De(!0).catch(()=>{})});Nt(n,()=>ne.cancel());let He=N(".ctab",t);function Q(g){for(let I of He){let _=I.dataset.tab===g;I.classList.toggle("active",_),I.setAttribute("aria-selected",_?"true":"false")}w.hidden=g!=="edit",R.hidden=g!=="edit",D.hidden=g!=="preview",T.classList.toggle("off",g!=="edit"),t.querySelector("#dropFoot")?.classList.toggle("off",g!=="edit"),g==="edit"&&K()}async function le(){Q("preview");try{p||await De(!0),D.srcdoc=await Ot(`/api/posts/${e}/preview`),D.onload=()=>{try{let g=D.contentDocument;g&&(Xt(g),ll(g,u.unlisted_url,A),D.style.height=`${g.body.scrollHeight+24}px`)}catch{}}}catch(g){if(n.aborted||Pt(g))return;U(tt(g))}}for(let g of He)g.onclick=()=>g.dataset.tab==="preview"?le():Q("edit");p&&le();let de=p?c("#lockFoot"):null,Pe;function Ce(){de&&(de.classList.remove("nudge"),requestAnimationFrame(()=>de.classList.add("nudge")),clearTimeout(Pe),Pe=setTimeout(()=>de.classList.remove("nudge"),900))}function Me(g,I,_){let B=w.selectionStart,se=w.selectionEnd,ce=w.value.slice(B,se)||_;w.value=w.value.slice(0,B)+g+ce+I+w.value.slice(se),w.focus(),w.selectionStart=B+g.length,w.selectionEnd=B+g.length+ce.length}function pt(g){let I=w.selectionStart,_=w.selectionEnd,B=w.value.lastIndexOf(`
153
+ `,I-1)+1,se=(w.value.slice(B,_)||"").split(`
154
+ `).map(ce=>g+ce).join(`
155
+ `);w.value=w.value.slice(0,B)+se+w.value.slice(_),w.focus(),w.selectionStart=B,w.selectionEnd=B+se.length}function mt(g){if(p){Ce();return}if(Q("edit"),g==="bold")Me("**","**","bold text");else if(g==="italic")Me("*","*","italic text");else if(g==="heading")pt("## ");else if(g==="quote")pt("> ");else if(g==="ul")pt("- ");else if(g==="ol")pt("1. ");else if(g==="indent")pt(" ");else if(g==="link")Me("[","](https://)","link text");else if(g==="code"){let I=w.selectionStart,_=w.selectionEnd;I===_||w.value.slice(I,_).includes(`
156
+ `)?Me("```\n","\n```","code"):Me("`","`","code")}po()}for(let g of N(".tb[data-fmt]",t))g.onclick=()=>mt(g.dataset.fmt??"");w.addEventListener("keydown",g=>{if(!(g.metaKey||g.ctrlKey))return;let I=g.key.toLowerCase();I==="b"?(g.preventDefault(),mt("bold")):I==="i"?(g.preventDefault(),mt("italic")):I==="k"&&(g.preventDefault(),mt("link"))});let me=!1,Gn=!1,Ke=!1,nt=null,ft=0,zn=!1,co=0,Ie=p?null:c("#saveBtn"),Ne=p?null:c("#saveStatus"),At=new Fs(E),rn=!1;function uo(){Ne&&(p?(Ne.className="save-status",Ne.textContent=""):rn?(Ne.className="save-status is-saving",Ne.textContent="Saving\u2026"):nt&&me?(Ne.className="save-status is-error",Ne.textContent=`Not saved: ${nt}`):me?(Ne.className="save-status is-dirty",Ne.textContent="Unsaved changes"):(Ne.className="save-status is-saved",Ne.textContent="Saved"))}function Yn(){me=At.dirty,me||(nt=null,Gn=!1,ft=0),uo()}uo();function qi(){ne.touch()}function po(){p||(b(),Yn(),Ke||qi())}let Ht=Promise.resolve();function De(g){let I=Ht.catch(()=>{}).then(()=>Hc(g));return Ht=I,ei(Ht),I}async function Hc(g){if(g&&!At.dirty)return"unchanged";if(Ke)return"refused";ne.cancel(),rn=!0,uo();let I=E(),_=JSON.stringify(I);try{let B={...I,base_revision:$.base},{post:se,subject_slug_held:ce}=await L(`/api/posts/${e}`,{method:"PUT",json:B});return f=et(se,ce),k(),$.saved(se.current_revision),At.markSaved(_),Gn=!1,nt=null,ft=0,g||U("Saved"),"saved"}catch(B){let se=ol(B);if(se)return Vi(se),"refused";if(Oe(B))return r(),"refused";Gn=!0;let ce=B instanceof te&&B.field==="subject"?H:void 0;if(ce?(qe(ce,V(B)),nt="fix the field marked above."):nt=V(B),!($o(B)||B instanceof te&&(B.status>=500||B.status===429)))co+=1,zn=!1,ft=0;else if(!zn){zn=!0,ft=ft?Math.min(ft*2,6e4):5e3;let ae=co;gt(Date.now()+ft,()=>{ae===co&&(zn=!1,nt&&!Ke&&De(!0).catch(()=>{}))},n)}throw B}finally{rn=!1,Yn()}}Ie&&(Ie.onclick=()=>{if(Ke){Ge.scrollIntoView({block:"nearest"});return}Z(Ie,"Saving\u2026",()=>De(!1).catch(()=>{})).finally(Yn)});function ji(){Ie&&(Ke?(Ie.setAttribute("aria-disabled","true"),Ie.title="Saving is paused: choose Reload or Keep editing above"):(Ie.removeAttribute("aria-disabled"),Ie.removeAttribute("title")))}let Pc=()=>{if(ne.cancel(),p||!At.dirty)return;let g=E(),I=JSON.stringify(g);me=!1,Ht=Ht.catch(()=>{}).then(async()=>{if(!At.dirty)return;let _={...g,base_revision:$.base},{post:B}=await L(`/api/posts/${e}`,{method:"PUT",json:_});$.saved(B.current_revision),At.markSaved(I)}).catch(_=>{if(Oe(_)){U("This post was deleted elsewhere, so your last edits weren\u2019t saved.");return}U(_ instanceof te&&_.status===409?"Changed elsewhere, so your edits weren\u2019t saved":`Couldn\u2019t save your changes: ${tt(_)}`)}),ei(Ht)},Mc={dirty:()=>me,beforeLeave(){return i?"leave":me&&(Gn||Ke)?"confirm":(Pc(),"leave")},manualSave(){Ie&&!Ie.disabled&&Ie.click()}};if(!p){for(let g of[H,w])g.addEventListener("input",po);for(let g of[H])g.addEventListener("blur",()=>De(!0).catch(()=>{})),g.addEventListener("keydown",I=>{I.key==="Enter"&&!I.isComposing&&I.keyCode!==229&&(I.preventDefault(),De(!0).catch(()=>{}))})}let Ge=c("#freshnessBanner");function Wi(){Ke=!1,ji(),$.clearWarning(),Ge.hidden=!0,h(Ge,o``)}function Vi(g){if(p)return;if(Ke=!0,nt=null,ji(),$.noteWarned(g),g.kind==="locked")h(Ge,o`<span><span aria-hidden="true">⚠️</span> This draft was scheduled elsewhere and can no longer be edited here.</span><span class="row"><button type="button" class="ghost" id="freshReload">Reload</button></span>`);else{let _=en(g.author,g.client);h(Ge,o`<span><span aria-hidden="true">⚠️</span> This draft was changed elsewhere${_?o`, last edited by <strong>${_}</strong>`:null}. Saving is paused until you choose: Reload to load that version (discards your unsaved edits), or Keep editing to keep yours, and your next save overwrites that version.</span><span class="row"><button type="button" class="ghost" id="freshReload">Reload</button><button type="button" class="ghost" id="freshKeep">Keep editing</button></span>`)}Ge.hidden=!1,c("#freshReload",Ge).onclick=()=>{Wi(),s()};let I=Ge.querySelector("#freshKeep");I&&(I.onclick=()=>{$.adoptWarned(),Wi(),Yn(),me&&qi()})}function Pt(g){return Oe(g)?(r(),!0):!1}if(!p){let g=async()=>{if(rn||Ke||i||document.hidden)return;let I=$.base;try{let _=await L(`/api/posts/${e}`,{signal:n}),B=$.decide({status:_.post.status,revision:_.post.current_revision,author:_.post.author,client:_.post.author_client},{saving:rn,baseAtRequest:I});B!=="ignore"&&B!=="fresh"&&Vi(B)}catch(_){Oe(_)&&r()}};bt(1e4,g,n),Uu(g,n)}if(c("#webLink").addEventListener("click",()=>{p||De(!0).catch(()=>{})}),p&&d){let g=l?.send??{...d,conditions:[]},I=c("#schedWhen"),_=c("#schedControls"),B="",se=0,ce=!1,ke=c("#rescheduleSchedule"),ae=c("#cancelSchedule"),J=be=>g.actions===void 0||Qe({actions:g.actions},be),$e=()=>{let be=Date.now(),xe=g.phase==="due"||be>=g.fire_at;xe?ce||(ke.hidden=!0,ae.hidden=!0):(ce=!0,ke.hidden=!J("reschedule"),ae.hidden=!J("cancel")),ke.disabled=xe,ae.disabled=xe,_.hidden=ke.hidden&&ae.hidden;let Le=Du(g,xe),Ye=String(Le);Ye!==B&&(B=Ye,h(I,Le)),!xe&&g.fire_at-be<=1e3&&g.fire_at!==se&&(se=g.fire_at,gt(g.fire_at,$e,n))};$e(),bt(1e3,$e,n);let ht=c("#schedRemade"),Be=c("#testHint"),_e=c("#schedDailyWrites"),an=c("#schedBy"),Mt=()=>{let be=el(g,v);an.hidden=be===null,an.textContent=be??"";let xe=he(g,"remade");ht.hidden=!xe,c("#schedRemadeMsg").textContent=xe?.message??"",Be.hidden=!he(g,"untested");let Le=he(g,"daily_writes");_e.hidden=!Le,c("#schedDailyWritesMsg").textContent=Le?.message??"";let Ye=he(g,"sandbox");c("#schedSandbox").hidden=!Ye,c("#schedSandboxMsg").textContent=Ye?.message??""};Mt();let ln=be=>gn(be,{update(xe,Le){let Ye=!Le&&xe.rev!==g.rev;if(g=xe,Ye&&q(),Le?.to==="sending"||Le?.to==="sent"||Le?.to==="complete"){U("Your send started, so this page switched to its live watch."),js(`#/sent/${xe.id}`);return}if(Le?.to==="canceled"){U("The schedule was canceled elsewhere, so this post is a draft again."),s();return}$e(),Mt()},removed:r,stale:s},n);l?ln(l):Ji(5e3,async()=>{let be=await L(`/api/sends/${d.id}`,{signal:n});return cl(be.send,s)||(g=be.send,$e(),Mt(),ln(be)),!1},n),ke.onclick=()=>{Ds({id:g.id,post_id:e,fire_at:g.fire_at},s,n,{...f})},ae.onclick=()=>Z(ae,"Canceling\u2026",async()=>{try{await L(`/api/sends/${d.id}/cancel`,{method:"POST"}),U("Schedule canceled"),s()}catch(be){Oe(be)?r():be instanceof te&&be.code==="window_closed"?(g={...g,phase:"due"},U("Too late to cancel: the send time has passed, so this email is going out."),Fe()):U(tt(be))}}).finally($e)}async function mo(g){if(g.type.startsWith("image/"))try{let I=new FormData;I.append("file",g);let{image:_}=await L(`/api/posts/${e}/images`,{method:"POST",body:I}),B=w.selectionStart,se=`
157
+ ![${g.name}](${_.filename})
158
+ `;w.value=w.value.slice(0,B)+se+w.value.slice(B),w.selectionStart=w.selectionEnd=B+se.length,po(),U("Image added")}catch(I){Pt(I)||U(tt(I))}}let ze=c("#composerBody");if(p){let g=_=>_.metaKey||_.ctrlKey?["x","z","y"].includes(_.key.toLowerCase()):_.key.length===1||_.key==="Enter"||_.key==="Backspace"||_.key==="Delete",I=[w,H];for(let _ of I)_.addEventListener("keydown",B=>{g(B)&&Ce()}),_.addEventListener("paste",Ce);ze.addEventListener("dragover",_=>_.preventDefault()),ze.addEventListener("drop",_=>{_.preventDefault(),Ce()})}else{let g=c("#imgInput"),I=c("#dropFoot");ze.addEventListener("dragover",_=>{_.preventDefault(),ze.classList.add("dragover")}),ze.addEventListener("dragleave",_=>{_.target===ze&&ze.classList.remove("dragover")}),ze.addEventListener("drop",_=>{_.preventDefault(),ze.classList.remove("dragover"),Q("edit");for(let B of _.dataTransfer?.files??[])mo(B)}),w.addEventListener("paste",_=>{for(let B of _.clipboardData?.items||[])if(B.type.startsWith("image/")){let se=B.getAsFile();se&&(_.preventDefault(),mo(se))}}),I.onclick=()=>g.click(),g.onchange=()=>{for(let _ of g.files??[])mo(_);g.value=""}}let Ic=c("#warnings");function Nc(g){h(Ic,g?.length?o`<div class="warnings"><strong>Warnings:</strong> ${g.join("; ")}</div>`:o``)}c("#testBtn").onclick=()=>{let g=p?"Delivers the frozen copy that will send, exactly as it will fire, so you can check it in a client. One address per line.":"Delivers the rendered email to real inboxes so you can check it in a client. One address per line.",I=ge(),_=fe(o`<h3>Send a test</h3><p class="hint">${g}</p>${vs()}${I?null:o`<label for="testTo">Recipients</label><textarea id="testTo" rows="3" placeholder="you@example.com"></textarea><p class="hint" id="testDefaultsHint" hidden></p>`}<div class="actions"><button type="button" id="tCancel">Cancel</button><button type="button" class="primary" id="tGo">Send test</button></div>`,n),B=c("#tGo",_.el);if(c("#tCancel",_.el).onclick=_.close,B.disabled=I,I){c("#tCancel",_.el).focus();return}let se=c("#testTo",_.el);se.focus(),L("/api/settings").then(ce=>{let ke=ce.settings.test_recipients||[];if(ke.length&&!se.value.trim()){se.value=ke.join(`
159
+ `),_.clearError();let ae=c("#testDefaultsHint",_.el);ae.textContent="Pre-filled from your default test recipients (Settings).",ae.hidden=!1}}).catch(()=>{}),B.onclick=()=>Z(B,"Sending\u2026",async()=>{_.clearError();let{valid:ce,invalid:ke}=xs(se.value),ae=Es(ke);if(ae){_.error(ae,se);return}if(!ce.length){_.error("Enter at least one email address",se);return}try{p||await De(!0);let J=0,$e=[],ht=null;for(let Be of ce)try{let _e=await L(`/api/posts/${e}/test`,{method:"POST",json:{to:Be}});_e.sent?J++:$e.push({email:Be,message:_e.not_sent?.message??""}),ht=_e.warnings}catch(_e){if(Oe(_e)||_e instanceof te&&_e.status===401)throw _e;$e.push({email:Be,message:V(_e)})}if(Nc(ht),p&&J>0&&Fe(),$e.length){se.value=$e.map(Be=>Be.email).join(`
160
+ `),_.error(ks(J,ce.length,$e));return}_.close(),U(Bt(`Test sent to ${J} address${J===1?"":"es"}`))}catch(J){if(Oe(J)){_.close(),Pt(J);return}_.error(tt(J))}})};let Ki=p?null:c("#scheduleBtn");return Ki&&(Ki.onclick=()=>{if(!W())return;let g=$t(ms()),I=$t(new Date(Date.now()+24*3600*1e3)),_=!S,B={...f,subject:H.value};B.slugAuto&&!B.slugTaken&&(B.slug=Ns(B.subject)||B.slug);let se="It sends at the time you pick, with a cancelable window until then.",ce=()=>o`<h3 id="schHead">Schedule this post</h3><p class="hint" id="schHint">${se}</p>${pr()}${Ao()}${Ho()}${_?null:o`<label for="schWhen">Send at</label><input type="datetime-local" id="schWhen" min="${g}" value="${I}"><div class="dialog-settings" id="schForm"></div>`}<div class="actions"><button type="button" id="schCancel">Cancel</button><button type="button" class="primary" id="schGo">Schedule</button></div>${_?null:o`<div class="altrow"><span class="altrow-note">Or send as soon as possible.</span><button type="button" class="linkbtn" id="toSendNow">Send now →</button></div>`}`,ke=I,ae=fe(ce(),n),J=c(".modal",ae.el),$e=null,ht=()=>($e??=L("/api/subscribers?status=confirmed&suppressed=hide&limit=1",{signal:n}).then(ue=>ue.page.total).catch(()=>null),$e),Be=async()=>{if(!J.querySelector("#schDailyWrites"))return;let ue=await ht(),ye=J.querySelector("#schDailyWrites");ye&&ue!==null&&ue>Yo&&(ye.textContent=qa(ue),ye.hidden=!1)},_e=null,an=async()=>{_e??=at(Y.appConfig?.deployment,n);let ue=lt(await _e),ye=J.querySelector("#schSandbox");ye&&ue&&(ye.textContent=ar,ye.hidden=!1)},Mt=()=>{ae.close(),Ge.scrollIntoView({block:"nearest"})},ln=()=>_t(c("#schForm",J),B,"sch"),be=()=>({email_only:B.emailOnly,...Cn(f,B)}),xe=ue=>{An(J,"sch",ue)||ae.error(tt(ue))},Le=()=>Z(c("#schGo",J),"Scheduling\u2026",async()=>{ae.clearError();let ue=c("#schWhen",J),ye=ue.value?new Date(ue.value).getTime():Number.NaN;if(Number.isNaN(ye)){ae.error("Pick a valid date & time",ue);return}if(ps(ye)){ae.error(us(),ue);return}try{if(await De(!0)==="refused"){Mt();return}await L(`/api/posts/${e}/schedule`,{method:"POST",json:{fire_at:new Date(ye).toISOString(),...be()}}),ae.close(),U(Bt(`Scheduled for ${j(ye)}. Send yourself a test.`)),s()}catch(Ze){if(Oe(Ze)){ae.close(),Pt(Ze);return}if(Ze instanceof te&&Ze.field==="fire_at"){ae.error(tt(Ze),c("#schWhen",J));return}xe(Ze)}}),Ye=()=>Z(c("#snGo",J),"Queuing\u2026",async()=>{ae.clearError();try{if(await De(!0)==="refused"){Mt();return}let{send:ue}=await L(`/api/posts/${e}/send`,{method:"POST",json:be()});ae.close(),U(Bt(`Sends at ${j(ue.fire_at)}, cancelable until then.`)),s()}catch(ue){if(Oe(ue)){ae.close(),Pt(ue);return}xe(ue)}});function Gi(){if(J.setAttribute("aria-labelledby","schHead"),c("#schCancel",J).onclick=ae.close,c("#schGo",J).onclick=Le,c("#schGo",J).disabled=_,_){c("#schCancel",J).focus();return}c("#toSendNow",J).onclick=Oc,c("#schWhen",J).value=ke,ln(),c("#schWhen",J).focus(),Be(),an()}async function Oc(){let ue=J.querySelector("#schWhen");ue&&(ke=ue.value),h(J,o`<h3 id="snHead">Send now?</h3><p class="hint">Sends this draft, as it is now, to <strong id="snWho">your subscribers</strong> in ${dr()}. The post locks until then, and you can cancel any time before it starts sending.</p><div class="dialog-settings" id="schForm"></div>${Ao()}${Ho()}<div class="actions"><button type="button" class="linkbtn actions-back" id="toSchedule">← Back to schedule</button><button type="button" id="snCancel">Cancel</button><button type="button" class="primary" id="snGo">Send now</button></div>`),J.setAttribute("aria-labelledby","snHead"),c("#snCancel",J).onclick=ae.close,c("#snGo",J).onclick=Ye,ln(),c("#snGo",J).disabled=!Zt(u,"send_now"),c("#toSchedule",J).onclick=()=>{h(J,ce()),Gi()},c("#snGo",J).focus(),Be(),an();let ye=await ht(),Ze=J.querySelector("#snWho");Ze&&ye!==null&&(Ze.textContent=`${ye} recipient${ye===1?"":"s"}`)}Gi()}),Mc}function cl(e,t){return e.status==="sending"||e.status==="sent"?(js(`#/sent/${e.id}`),!0):e.status==="canceled"?(t(),!0):!1}function Du(e,t){return Re(e,"missed")?o`Scheduled for <strong>${j(e.fire_at)}</strong> · <span class="countdown countdown-missed">${_s(e.fire_at)}</span>`:t?o`Scheduled for <strong>${j(e.fire_at)}</strong> · <span class="countdown">${vn(e.fire_at,!0)}</span>`:o`Scheduled for <strong>${j(e.fire_at)}</strong> · <span class="countdown">${vn(e.fire_at)}</span>`}function Oe(e){return e instanceof te&&e.status===404}function Bu(e){let t=e.post.send;return t?.status==="sending"?`#/sent/${t.id}`:e.post.status==="sent"?t?`#/sent/${t.id}`:"#/sent":null}function js(e){location.replace(e)}function Uu(e,t){document.addEventListener("visibilitychange",()=>{document.hidden||e()},{signal:t})}function Fu(e){return e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,"").replace(/\s/g,"-")}function dl(e){let t=new Map;return e.map(n=>{let s=Fu(n),i=t.get(s)??0;return t.set(s,i+1),i?`${s}-${i}`:s})}var si=null;function qu(e){let t=document.createElement("div");h(t,z(e.html||""));let n=(t.querySelector("p")?.textContent||"").trim().replace(/\s+/g," "),s=/[:;,]$/.test(n),i=n.replace(/[\s:;,]+$/,""),r=150;return i.length>r?`${i.slice(0,r).replace(/[\s.,;:]+\S*$/,"")}\u2026`:s?`${i}\u2026`:i}function ju(e){let t=e.querySelector("code"),n=t?.className.match(/(?:^|\s)language-(\S+)/)?.[1]??null,s=(t??e).textContent?.replace(/\n$/,"")??"",i=n==="bash"||n==="sh"||n==="shell"?Us(s):n==="json"||n==="jsonc"?Xo(s):o`${s}`;return ka(i,s)}async function oi(e,t,n,s){if(ie(n,"Docs"),h(t,Ut("docs",null,o`<div class="docs-index"><p class="muted">Loading…</p></div>`)),!si)try{si=await L("/api/docs",{signal:n})}catch(d){n.aborted||re(c(".room-main",t),V(d),()=>ee((u,m)=>oi(e,u,m,s)));return}let{sets:i,docs:r}=si,a=i[0];if(!r.length||!a){h(c(".room-main"),o`<p class="muted">No documentation.</p>`);return}let l=e?i.find(d=>d.id===e):a;l?ml(t,l,i,r,n):e&&Ku(t,i,r,e,n,s?Wu(s):void 0)}function Wu(e){try{return decodeURIComponent(e)}catch{return}}function ml(e,t,n,s,i){ie(i,`${t.name} docs`);let r=(f,p)=>{let S=qu(f);return o`<li><a class="doc-card" href="#/docs/${f.slug}">${p===null?null:o`<span class="doc-card-n">${String(p).padStart(2,"0")}</span>`}<span class="doc-card-main"><span class="doc-card-t">${f.title} <span class="doc-card-go" aria-hidden="true">→</span></span>${S?o`<span class="doc-card-d">${S}</span>`:null}</span></a></li>`},a=t.sections.map(f=>{let p=s.filter(M=>M.set===t.id&&M.section===f.id);if(!p.length)return null;let S=p.map((M,P)=>r(M,f.numbered?P+1:null)),$=f.blurb?o`<div class="doc-section-blurb">${z(f.blurb)}</div>`:null;return o`<section class="doc-section"><h2 class="doc-section-t">${f.title}</h2>${$}${f.numbered?o`<ol class="doc-cards">${S}</ol>`:o`<ul class="doc-cards">${S}</ul>`}</section>`}),l=o`<nav class="docs-tabs" aria-label="Doc sets">${n.map(f=>o`<a href="#/docs/${f.id}" title="${f.title}"${f.id===t.id?o` aria-current="page"`:null}>${f.name}</a>`)}</nav>`,d=o`<div class="docs-index"><h1>Kestrel docs</h1><p class="docs-index-intro"><strong>Publishing</strong> covers writing and sending your newsletter, from naming your publication to what happens after each send. <strong>Self-hosting</strong> covers deploying Kestrel to your own Cloudflare account and keeping it running. One person often does both.</p>${l}${a}</div>`,u=Y.appConfig?.deployment.build.repo_url||"",m=(f,p,S=p)=>o`<a class="rail-link" href="${f}" target="_blank" rel="noopener" aria-label="${p}"><span class="rail-link-full">${p}</span><span class="rail-link-short" aria-hidden="true">${S}</span> <span aria-hidden="true">↗</span></a>`,v=o`<div class="toc-label">Kestrel</div>${m("https://getkestrel.dev","Project site","Project")}${u?[m(u,"Source on GitHub","Source"),m(`${u}/blob/HEAD/LICENSE`,"License")]:null}`;h(e,Ut("docs",v,d)),window.scrollTo(0,0)}var ii=matchMedia("(max-width: 720px)");function fl(e){if(!e)return;let t=ii.matches;e.open=!t,c("summary",e).tabIndex=t?0:-1}var hl=()=>document.querySelector("details#tocOnPage"),ul=!1;function Vu(){ul||(ul=!0,ii.addEventListener("change",()=>fl(hl())))}var pl=e=>`doc-h-${e}`;function Ku(e,t,n,s,i,r){let a=n.findIndex(x=>x.slug===s),l=n[a],d=t.find(x=>x.id===l?.set);if(!l||!d){let x=t[0];U(`No doc named \u201C${s}\u201D, so here\u2019s the index.`),history.replaceState(history.state,"","#/docs"),x&&ml(e,x,t,n,i);return}ie(i,l.title);let u=n.filter(x=>x.set===l.set&&x.section===l.section),m=u.indexOf(l),v=u[m-1],f=u[m+1],p=(x,W)=>o`<a href="#/docs/${x.slug}" aria-label="${W}: ${x.title}">${W==="Previous"?o`<span aria-hidden="true">←</span><span class="doc-topnav-word">Previous</span>`:o`<span class="doc-topnav-word">Next</span><span aria-hidden="true">→</span>`}</a>`,S=v||f?o`<nav class="doc-topnav" aria-label="Adjacent docs">${v?p(v,"Previous"):null}${f?p(f,"Next"):null}</nav>`:null;h(e,Ut("docs",o`<div id="docToc"></div>`,o`<article class="doc" id="docsMain"></article>`));let $=c("#docToc"),M=c("#docsMain");h(M,o`<section class="doc-part" id="doc-${l.slug}">${z(l.html)}</section>`);let P=c("section.doc-part",M),A=N("h1, h2, h3, h4",P),H=dl(A.map(x=>x.textContent||""));for(let[x,W]of A.entries()){let oe=H[x]??"";W.dataset.anchor=oe,W.id=pl(oe)}let y=P.querySelector("h1"),w=[];if(y&&w.push({id:y.id,anchor:"",title:y.textContent||l.title}),S){let x=document.createElement("div");x.className="doc-head",h(x,S),y?(y.before(x),x.prepend(y)):P.prepend(x)}let T=document.createElement("p");T.className="eyebrow doc-set",h(T,o`<a href="#/docs/${d.id}">${d.name}</a>`),P.prepend(T);for(let x of N("h2",P))w.push({id:x.id,anchor:x.dataset.anchor||"",title:x.textContent||""});let D=document.createElement("nav");D.className="doc-pager",h(D,o`${v?o`<a class="doc-pager-btn prev" href="#/docs/${v.slug}"><span class="doc-pager-dir">← Previous</span><span class="doc-pager-title">${v.title}</span></a>`:o`<span></span>`}${f?o`<a class="doc-pager-btn next" href="#/docs/${f.slug}"><span class="doc-pager-dir">Next →</span><span class="doc-pager-title">${f.title}</span></a>`:o`<span></span>`}`),M.appendChild(D);let R=w.map(x=>o`<a class="toc-sub" href="#/docs/${l.slug}${x.anchor?`/${x.anchor}`:""}" data-target="${x.id}">${x.title}</a>`);h($,w.length?o`<details class="toc-onpage" id="tocOnPage"><summary class="toc-label">On this page</summary>${R}</details>`:o``);let F=hl();fl(F),Vu();let K=x=>{if(F)for(let W of N(".toc-sub",F))W.classList.toggle("on",W.dataset.target===x)};$.addEventListener("click",x=>{let W=x.target instanceof Element?x.target.closest("a[data-target]"):null,oe=W?.dataset.target;oe&&(x.preventDefault(),K(oe),F&&ii.matches&&(F.open=!1),history.replaceState(history.state,"",W?.getAttribute("href")??location.hash),document.getElementById(oe)?.scrollIntoView({block:"start"}))});for(let x of N("a[href^='http']",M))x.target="_blank",x.rel="noopener";for(let x of N("pre",P)){let W=document.createElement("div");h(W,ju(x)),x.replaceWith(...W.childNodes)}We(M);let b=w.map(x=>x.id),E=b[0];if(F&&E){let x=b[b.length-1]??E,oe=(document.querySelector(".room-bar")?.getBoundingClientRect().height||54)+26,k=()=>{if(!document.getElementById(E)){document.onscroll=null;return}let G=E;if(Math.ceil(window.innerHeight+window.scrollY)>=document.documentElement.scrollHeight)G=x;else for(let q of b)if((document.getElementById(q)?.getBoundingClientRect().top??Number.POSITIVE_INFINITY)<=oe)G=q;else break;K(G)};document.onscroll=k,k()}let C=r?document.getElementById(pl(r)):null;C?C.scrollIntoView({block:"start"}):window.scrollTo(0,0)}function ri(e){let t=new Set(e.groups.flatMap(n=>n.routes.flatMap(s=>(s.errors??[]).map(i=>i.code))));return e.refusals.flatMap(n=>n.codes.filter(s=>!t.has(s.code)).map(s=>({...s,move:n.move})))}function Lt(e){return e.replace(/\([^)]*\)/g,"").replace(/\{[^}]*\}\??/g,"")||"/"}function tn(e){return e.title.toLowerCase().replace(/'s\b/g,"").split(/[^a-z0-9]+/).filter(t=>t!==""&&t!=="a"&&t!=="an"&&t!=="the").join("-")}var Gu=/`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g;function zu(e){return/^https:\/\//i.test(e)||/^\/(?![/\\])/.test(e)}function ve(e){let t=[],n=0;for(let s of e.matchAll(Gu)){let i=s.index??0;t.push(e.slice(n,i));let[,r,a,l,d]=s;r!==void 0?t.push(o`<code>${r}</code>`):a!==void 0?t.push(o`<strong>${ve(a)}</strong>`):l!==void 0&&d!==void 0&&t.push(zu(d)?o`<a href="${d}">${ve(l)}</a>`:ve(l)),n=i+s[0].length}return t.push(e.slice(n)),o`${t}`}function Hn(e,t){return o`${e.split(/\n\s*\n/).filter(n=>n.trim()).map(n=>{let s=n.trim().split(`
161
+ `),i=s.findIndex(l=>l.startsWith("- "));if(i===-1)return o`<p class="${t}">${ve(n.trim())}</p>`;let r=s.slice(0,i).join(" ").trim(),a=s.slice(i).reduce((l,d)=>(d.startsWith("- ")||l.length===0?l.push(d.replace(/^- /,"")):l[l.length-1]=`${l[l.length-1]} ${d.trim()}`,l),[]);return o`${r?o`<p class="${t}">${ve(r)}</p>`:null}<ul class="${t} prose-list">${a.map(l=>o`<li>${ve(l)}</li>`)}</ul>`})}`}function Yu(e){return e==="access"?['-H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID"','-H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET"']:['-H "Authorization: Bearer $TOKEN"']}function bl(e,t,n){if(e.access==="webhook")return null;let s=(e.query??[]).filter(l=>l.required),i=s.length?`?${s.map(l=>`${l.name}=:${l.name}`).join("&")}`:"",r=`"${t}${Lt(e.path)}${i}"`,a=[e.method==="GET"?`curl ${r}`:`curl -X ${e.method} ${r}`];if(e.access==="admin"&&a.push(...Yu(n)),e.example?.request!==void 0){let l=JSON.stringify(e.example.request).replaceAll("'","'\\''");a.push('-H "Content-Type: application/json"',`-d '${l}'`)}else if(e.accepts?.includes("multipart/form-data"))for(let l of(e.body??[]).filter(d=>d.required))a.push(`-F "${l.name}=${l.type==="file"?"@":""}:${l.name}"`);return a.join(` \\
162
+ `)}function li(e,t){return t===void 0?null:Jt(e,Ja(t),JSON.stringify(t,null,2))}function Zu(e){let t=bl(e,location.origin,Y.session?.auth.mode??"dev");return t===null?null:Jt("curl",Us(t),t)}function Ws(e){return o`${e.split(/(?<=[_./])/).map((t,n)=>o`${n?o`<wbr>`:null}${t}`)}`}function dt(e,t,n,s){return o`<div class="block api-sec"><div class="block-head"><span class="block-label">${e}${n?o`<span class="api-sec-meta">${n}</span>`:null}</span></div>${s??null}${t}</div>`}function ci(e,t,n,s){return o`<div class="api-row"><div class="api-row-head"><code class="api-row-name">${Ws(e)}</code>${t?o`<span class="api-row-type">${t}</span>`:null}${n?o`<span class="api-req">Required</span>`:null}</div><div class="api-row-desc">${s}</div></div>`}function di(e,t,n,s){return o`<div class="api-lrow"><span class="api-st api-st-${String(e)[0]}xx">${e}</span><div><div class="api-row-head"><code class="api-row-name">${t}</code></div>${n?o`<div class="api-with">${n}</div>`:null}<div class="api-row-desc">${s}</div></div></div>`}function Ju(e){if(!e?.length)return null;let t=e.map(n=>ci(n.name,null,n.required,ve(n.description)));return dt("Query",o`<div class="api-list api-query">${t}</div>`)}function Qu(e,t){if(!e?.length)return null;let n=e.map(i=>ci(i.name,i.type,i.required,ve(i.description))),s=t?.length?o` · ${t.map((i,r)=>o`${r?", ":""}<code>${i}</code>`)}`:null;return dt("Body",o`<div class="api-list api-body">${n}</div>`,s)}function Xu(e,t){if(!e?.length)return null;let n=e.map(s=>di(s.status,Ws(s.code),s.details?.length?o`with ${s.details.map((i,r)=>o`${r?", ":""}<code>${i}</code>`)}`:null,o`${ve(s.when??t.get(s.code)??"")}<span class="api-move-next">${s.move}</span>`));return dt("Refusals",o`<div class="api-ledger api-errors">${n}</div>`)}function ep(e){let t=s=>o`<ul class="api-values">${s.map(i=>o`<li><code>${i.value}</code> ${ve(i.description)}</li>`)}</ul>`,n=[...new Set(e.map(s=>s.group).filter(s=>s!==void 0))];return n.length?o`${n.map(s=>o`<div class="api-values-group">${ve(s)}</div>${t(e.filter(i=>i.group===s))}`)}`:t(e)}function ui(e){let t=e.map(n=>ci(n.name,n.object?o`<a href="#/api-reference/objects-${n.object}" class="api-obj-link" data-sec="objects-${n.object}">${n.type}</a>`:n.type,!1,o`${ve(n.description)}${n.values?.length?ep(n.values):null}`));return o`<div class="api-list api-fields">${t}</div>`}function tp(e,t){if(!e)return null;let n=e.object?o`<a href="#/api-reference/objects-${e.object}" class="api-obj-link" data-sec="objects-${e.object}">${t.get(e.object)??e.object}</a>`:null,s=n?e.as?o`<p class="api-returns"><code>${e.as}</code>: ${e.list?o`a list of ${n}`:n}${e.fields?.length?", and:":null}</p>`:o`<p class="api-returns">${n}${e.fields?.length?", and:":null}</p>`:null;return dt("Returns",e.fields?.length?ui(e.fields):null,null,s)}function np(e){return o`${Lt(e).split(/(:[A-Za-z_]+)/).map((t,n)=>n%2?o`<span class="api-param">${t}</span>`:t)}`}function Pn(e,t){return"route"in t?o`<a class="api-self" href="#/api-reference/${t.route}" data-route="${t.route}">${O("link")}${e}</a>`:o`<a class="api-self" href="#/api-reference/${t.sec}" data-sec="${t.sec}">${O("link")}${e}</a>`}function sp(e){let t=new Map;for(let n of e.objects){let s=e.groups.find(i=>i.resources.some(r=>r.key===n.resource));if(s){let i=`${s.access}-${n.resource}`;t.set(i,[...t.get(i)??[],n])}}return t}function op(e,t){let n=e.returns?.object;return[e.title,e.method,Lt(e.path),e.summary,...(e.errors??[]).map(s=>s.code),...n?[n,t.objects.get(n)??"",e.returns?.as??""]:[]].join(" ").toLowerCase()}function ip(e,t){return o`<li data-hay="${op(e,t)}" data-path="${Lt(e.path).toLowerCase()}" id="route-${tn(e)}" data-route="${tn(e)}"><article class="api-op">
168
163
  <div class="api-op-head">
169
- <h4 tabindex="-1">${kn(e.title,{route:Qt(e)})}</h4>
164
+ <h4 tabindex="-1">${Pn(e.title,{route:tn(e)})}</h4>
170
165
  </div>
171
- <p class="api-op-call"><span class="api-method m-${e.method}">${e.method}</span><code class="api-path">${lu(e.path)}</code><button type="button" class="copy-btn api-copy-path" data-copy="${xt(e.path)}" data-copy-word="" aria-label="Copy path" title="Copy path">${Te(!1,"")}</button></p>
166
+ <p class="api-op-call"><span class="api-method m-${e.method}">${e.method}</span><code class="api-path">${np(e.path)}</code><button type="button" class="copy-btn api-copy-path" data-copy="${Lt(e.path)}" data-copy-word="" aria-label="Copy path" title="Copy path">${Te(!1,"")}</button></p>
172
167
  <div class="api-op-body">
173
168
  <div class="api-op-text">
174
- <p class="api-summary">${ge(e.summary)}</p>
175
- ${e.description?xn(e.description,"api-desc"):null}
176
- ${su(e.query)}
177
- ${ou(e.body,e.accepts)}
178
- ${au(e.returns,t.objects)}
179
- ${iu(e.errors,t.meanings)}
169
+ <p class="api-summary">${ve(e.summary)}</p>
170
+ ${e.description?Hn(e.description,"api-desc"):null}
171
+ ${Ju(e.query)}
172
+ ${Qu(e.body,e.accepts)}
173
+ ${tp(e.returns,t.objects)}
174
+ ${Xu(e.errors,t.meanings)}
180
175
  </div>
181
176
  <div class="api-op-code">
182
- ${Wo("Request",e.example?.request)}
183
- ${Wo("Response",e.example?.response)}
184
- ${nu(e)}
177
+ ${li("Request",e.example?.request)}
178
+ ${li("Response",e.example?.response)}
179
+ ${Zu(e)}
185
180
  </div>
186
181
  </div>
187
- </article></li>`}var Fa=(e,t)=>e.routes.filter(n=>n.resource===t.key),pu=80;function mu(e){let t=e.columns.map((i,a)=>a>0&&e.rows.every(r=>(r[a]??"").length<=pu)),n=e.columns.findIndex((i,a)=>a>0&&!t[a]),s=e.rows.map(i=>{let a=/^`([^`]+)`$/.exec(i[0]??"")?.[1],r=e.columns.flatMap((d,u)=>t[u]?[o`<span class="api-row-meta"><span class="api-row-key">${d}</span> ${ge(i[u]??"")}</span>`]:[]),l=e.columns.flatMap((d,u)=>u>0&&!t[u]?[o`<div class="api-row-desc">${u===n?null:o`<span class="api-row-key">${d}:</span> `}${ge(i[u]??"")}</div>`]:[]);return o`<div class="api-row"><div class="api-row-head"><code class="api-row-name">${a===void 0?ge(i[0]??""):Ps(a)}</code>${r}</div>${l}</div>`});return rt(e.title,o`<div class="api-list api-value-rows">${s}</div>`,null,xn(e.description,"api-prose"))}function fu(e){return o`<article class="api-op api-object" id="api-objects-${e.key}" data-sec="objects-${e.key}">
188
- <div class="api-op-head"><h4 tabindex="-1">${kn(e.title,{sec:`objects-${e.key}`})}</h4></div>
182
+ </article></li>`}var wl=(e,t)=>e.routes.filter(n=>n.resource===t.key),rp=80;function ap(e){let t=e.columns.map((i,r)=>r>0&&e.rows.every(a=>(a[r]??"").length<=rp)),n=e.columns.findIndex((i,r)=>r>0&&!t[r]),s=e.rows.map(i=>{let r=/^`([^`]+)`$/.exec(i[0]??"")?.[1],a=e.columns.flatMap((d,u)=>t[u]?[o`<span class="api-row-meta"><span class="api-row-key">${d}</span> ${ve(i[u]??"")}</span>`]:[]),l=e.columns.flatMap((d,u)=>u>0&&!t[u]?[o`<div class="api-row-desc">${u===n?null:o`<span class="api-row-key">${d}:</span> `}${ve(i[u]??"")}</div>`]:[]);return o`<div class="api-row"><div class="api-row-head"><code class="api-row-name">${r===void 0?ve(i[0]??""):Ws(r)}</code>${a}</div>${l}</div>`});return dt(e.title,o`<div class="api-list api-value-rows">${s}</div>`,null,Hn(e.description,"api-prose"))}function lp(e){return o`<article class="api-op api-object" id="api-objects-${e.key}" data-sec="objects-${e.key}">
183
+ <div class="api-op-head"><h4 tabindex="-1">${Pn(e.title,{sec:`objects-${e.key}`})}</h4></div>
189
184
  <p class="api-op-call"><span class="api-method m-OBJECT">Object</span><span class="api-path">${e.fields.length} ${e.fields.length===1?"field":"fields"}</span></p>
190
185
  <div class="api-op-body">
191
186
  <div class="api-op-text">
192
- ${xn(e.description,"api-prose")}
193
- ${Go(e.fields)}
194
- ${(e.tables??[]).map(mu)}
187
+ ${Hn(e.description,"api-prose")}
188
+ ${ui(e.fields)}
189
+ ${(e.tables??[]).map(ap)}
195
190
  </div>
196
- <div class="api-op-code">${Wo("Example",e.example)}</div>
191
+ <div class="api-op-code">${li("Example",e.example)}</div>
197
192
  </div>
198
- </article>`}function hu(e,t,n){let s=`${e.access}-${t.key}`,i=Fa(e,t),a=n.heads.get(s)??[];return o`<div class="api-res" id="api-${s}" data-sec="${s}">
199
- <div class="api-res-head"><h3 tabindex="-1">${kn(t.title,{sec:s})}</h3></div>
200
- ${a.map(fu)}
201
- <ul class="api-rows">${i.map(r=>uu(r,n))}</ul>
202
- </div>`}function bu(e,t){return o`<section class="api-section" id="api-${e.access}" data-tier="${e.access}">
203
- <h2 tabindex="-1">${kn(e.title,{sec:e.access})}</h2>
204
- <p class="api-blurb muted">${ge(e.blurb)}</p>
205
- ${e.resources.map(n=>hu(e,n,t))}
206
- </section>`}function gu(e){let t=qo(e);if(!t.length)return null;let n=t.map(s=>Ko(s.status,Ps(s.code),null,ge(s.meaning)));return rt("Refusals any route can give",o`<div class="api-ledger api-refusals">${n}</div>`)}function vu(e){let t=qo(e).map(s=>s.code),n=s=>o`<div class="api-res" id="api-overview-${s.key}" data-sec="overview-${s.key}" data-hay="${[s.title,...s.key==="errors"?t:[]].join(" ").toLowerCase()}">
207
- <div class="api-res-head"><h3 tabindex="-1">${kn(s.title,{sec:`overview-${s.key}`})}</h3></div>
208
- ${xn(s.text,"api-prose")}
209
- ${s.key==="errors"?yu(e.statuses):null}
210
- ${s.fields?.length?rt(s.key==="errors"?"The error body":"Fields",Go(s.fields)):null}
211
- ${s.key==="errors"?gu(e):null}
193
+ </article>`}function cp(e,t,n){let s=`${e.access}-${t.key}`,i=wl(e,t),r=n.heads.get(s)??[];return o`<div class="api-res" id="api-${s}" data-sec="${s}">
194
+ <div class="api-res-head"><h3 tabindex="-1">${Pn(t.title,{sec:s})}</h3></div>
195
+ ${r.map(lp)}
196
+ <ul class="api-rows">${i.map(a=>ip(a,n))}</ul>
197
+ </div>`}function dp(e,t){return o`<section class="api-section" id="api-${e.access}" data-tier="${e.access}">
198
+ <h2 tabindex="-1">${Pn(e.title,{sec:e.access})}</h2>
199
+ <p class="api-blurb muted">${ve(e.blurb)}</p>
200
+ ${e.resources.map(n=>cp(e,n,t))}
201
+ </section>`}function up(e){let t=ri(e);if(!t.length)return null;let n=t.map(s=>di(s.status,Ws(s.code),null,ve(s.meaning)));return dt("Refusals any route can give",o`<div class="api-ledger api-refusals">${n}</div>`)}function pp(e){let t=ri(e).map(s=>s.code),n=s=>o`<div class="api-res" id="api-overview-${s.key}" data-sec="overview-${s.key}" data-hay="${[s.title,...s.key==="errors"?t:[]].join(" ").toLowerCase()}">
202
+ <div class="api-res-head"><h3 tabindex="-1">${Pn(s.title,{sec:`overview-${s.key}`})}</h3></div>
203
+ ${Hn(s.text,"api-prose")}
204
+ ${s.key==="errors"?mp(e.statuses):null}
205
+ ${s.fields?.length?dt(s.key==="errors"?"The error body":"Fields",ui(s.fields)):null}
206
+ ${s.key==="errors"?up(e):null}
212
207
  </div>`;return o`<section class="api-section" id="api-overview" data-tier="overview">
213
208
  ${e.concepts.map(n)}
214
- </section>`}function yu(e){let t=e.map(n=>Ko(n.status,o`${n.name}`,null,ge(n.meaning)));return rt("Status codes",o`<div class="api-ledger api-statuses">${t}</div>`)}function wu(e,t){let n=(i,a)=>o`<a href="#/api-reference/${i}" class="api-nav-res" data-sec="${i}">${a}</a>`,s=(i,a)=>o`<div class="api-nav-ops" data-of="${i.access}-${a.key}">${[...(t.heads.get(`${i.access}-${a.key}`)??[]).map(r=>o`<a href="#/api-reference/objects-${r.key}" class="api-nav-op" data-sec="objects-${r.key}">${r.title}</a>`),...Fa(i,a).map(r=>o`<a href="#/api-reference/${Qt(r)}" class="api-nav-op" data-route="${Qt(r)}">${r.title}</a>`)]}</div>`;return o`<a href="#/api-reference" class="api-nav-tier" data-sec="overview" data-tier="overview">Introduction</a>${e.concepts.map(i=>n(`overview-${i.key}`,i.title))}${e.groups.map(i=>o`<a href="#/api-reference/${i.access}" class="api-nav-tier" data-sec="${i.access}" data-tier="${i.access}">${i.title}</a>${i.resources.map(a=>[i.resources.length>1?n(`${i.access}-${a.key}`,a.title):null,s(i,a)])}`)}`}function Su(e,t){let n=e.replace(/^[a-z]+:\/\/[^/]*/,"").replace(/[?#].*$/,"");if(!n.startsWith("/"))return!1;let s=n.replace(/(.)\/+$/,"$1").split("/"),i=t.split("/");return s.length===i.length&&i.every((a,r)=>a.startsWith(":")?s[r]!=="":a===s[r])}function $u(e,t){let n=e.dataset.path;return(e.dataset.hay??"").includes(t)||n!==void 0&&Su(t,n)}function Oa(e,t,n){let s=e.trim().toLowerCase().split(/\s+/).filter(Boolean);t.classList.toggle("filtering",s.length>0);let i=0;for(let l of I(".api-section",n)){let d=0;for(let f of I(".api-res",l)){let S=f.dataset.hay!==void 0,b=0;for(let v of S?[f]:I("li[data-hay]",f)){let x=s.every(A=>$u(v,A));v.hidden=!x,b+=x?1:0;let M=v.dataset.route?t.querySelector(`a[data-route="${v.dataset.route}"]`):null;M&&(M.hidden=!x)}f.hidden=b===0;for(let v of I(`.api-nav-ops[data-of="${f.dataset.sec}"] a[data-sec]`,t))v.hidden=s.length>0&&b===0;let p=t.querySelector(`a[data-sec="${f.dataset.sec}"]`);p&&(p.hidden=b===0),d+=b}l.hidden=d===0;let u=t.querySelector(`a[data-tier="${l.dataset.tier}"]`);u&&(u.hidden=d===0),i+=d}let a=I(".api-section",n),r=a.filter(l=>!l.hidden).at(-1);for(let l of a)l.classList.toggle("api-last",l===r);c("#apiEmpty",n).hidden=i>0}function jo(e,t,n){let s=(c(".room-bar").getBoundingClientRect().height||54)+8,i=I(".api-section, .api-res, .api-object, li[data-route]",t).filter(v=>!v.closest("[hidden]")),a=window.scrollY>0&&Math.ceil(window.innerHeight+window.scrollY)>=document.documentElement.scrollHeight,r;for(let v of i)if(a||v.getBoundingClientRect().top<=s)r=v;else break;let l=I("a[data-sec], a[data-route]",e).filter(v=>!v.hidden&&getComputedStyle(v).display!=="none"),d=v=>v?(v.dataset.route?l.find(M=>M.dataset.route===v.dataset.route):l.find(M=>M.dataset.sec===(v.dataset.sec??v.dataset.tier)))??d(v.parentElement?.closest(".api-res, .api-section")):void 0,u=r?.closest(".api-res")?.dataset.sec;for(let v of I(".api-nav-ops",e))v.classList.toggle("open",v.dataset.of===u);let f=d(r??i[0]);for(let v of I("a[data-sec], a[data-route]",e))v.classList.toggle("active",v===f);let S=e.closest(".rail-inner");if(f&&S&&S.scrollHeight>S.clientHeight){let v=f.getBoundingClientRect(),x=S.getBoundingClientRect();(v.top<x.top+40||v.bottom>x.bottom-40)&&(S.scrollTop+=v.top-x.top-x.height/3)}let b=r?.dataset.route??r?.dataset.sec??r?.dataset.tier,p=b&&b!=="overview"&&window.scrollY>0?`#/api-reference/${b}`:"#/api-reference";n&&location.hash!==p&&history.replaceState(history.state,"",p)}function Da(e){return document.getElementById(e==="overview"?"api-intro":`api-${e}`)}function Ua(e){e.id==="api-intro"?window.scrollTo(0,0):e.scrollIntoView({block:"start"}),e.querySelector(":scope > h1, :scope > h2, :scope > .api-res-head h3, :scope > .api-op-head h4, :scope > article > .api-op-head h4")?.focus({preventScroll:!0})}async function zo(e,t,n){se(t,"API reference"),h(e,Bt("api-reference",o`<div class="toc-label">API</div><nav class="api-nav" id="apiNav" aria-label="API sections"></nav>`,o`<div class="api-content" id="apiContent"><p class="muted">Loading…</p></div>`));let s=c("#apiNav"),i=c("#apiContent"),a=p=>{let v=p.target instanceof Element?p.target.closest("a[data-sec], a[data-route]"):null,x=v?.dataset.route?document.getElementById(`route-${v.dataset.route}`):v?.dataset.sec?Da(v.dataset.sec):null;!x||p.button!==0||p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||(p.preventDefault(),(x.closest("[hidden]")||v?.closest("#apiEmpty"))&&S(""),history.replaceState(history.state,"",v?.getAttribute("href")??location.hash),Ua(x),jo(s,i,!1))};s.addEventListener("click",a),i.addEventListener("click",a);let r;try{r=await R("/api/reference",{signal:t})}catch(p){oe(i,F(p),()=>ee((v,x)=>zo(v,x,n)));return}let l={meanings:new Map(r.refusals.flatMap(p=>p.codes.map(v=>[v.code,v.meaning]))),objects:new Map(r.objects.map(p=>[p.key,p.title])),heads:cu(r)};h(s,wu(r,l)),h(i,o`<header class="api-head" id="api-intro"><h1 tabindex="-1">API reference</h1><p class="muted">Every endpoint this instance serves, the one API the web editor and Claude both call. It's read from the running code, so it always matches this version. Base URL <code>${location.origin}</code>.</p><div class="api-filter">${N("search")}<input type="search" id="apiFilter" placeholder="Filter by name, path, URL, or error code" autocomplete="off" aria-label="Filter routes" aria-keyshortcuts="/"><kbd aria-hidden="true">/</kbd><button type="button" class="icon api-filter-clear" id="apiFilterClear" aria-label="Clear filter" hidden>${N("x")}</button></div></header>${vu(r)}${r.groups.map(p=>bu(p,l))}<p class="api-empty muted" id="apiEmpty" hidden>Nothing matches. Try a path segment like <code>sends</code>, a method like <code>DELETE</code>, or a code like <code>stale_revision</code>, or start from the <a href="#/api-reference" data-sec="overview">Introduction</a>.</p>`);let d=c("#apiFilter"),u=c("#apiFilterClear"),f=()=>jo(s,i,!1),S=p=>{d.value=p,u.hidden=p==="",Oa(p,s,i),f()};d.addEventListener("input",()=>S(d.value)),u.addEventListener("click",()=>{S(""),d.focus()}),je(i),document.addEventListener("keydown",p=>{let v=p.target instanceof HTMLElement&&(p.target.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(p.target.tagName));p.key==="/"&&!v&&!p.metaKey&&!p.ctrlKey&&!p.altKey?(p.preventDefault(),d.focus()):p.key==="Escape"&&p.target===d&&d.value&&S("")},{signal:t}),Oa("",s,i),window.addEventListener("scroll",()=>jo(s,i,!0),{passive:!0,signal:t}),window.scrollTo(0,0);let b=n?document.getElementById(`route-${n}`)??Da(n):null;b&&Ua(b),f()}var Ms=F;function Eu(e){let t=[Ze(e,"reschedule")?o`<button class="ghost" data-reschedule="${e.id}">Edit schedule</button>`:null,Ze(e,"cancel")?o`<button class="ghost" data-cancel="${e.id}">Cancel</button>`:null];return t.some(Boolean)?o`<div class="row" data-closes="${e.fire_at}">${t}</div>`:null}async function Yo(e,t){se(t,"Sent");let n={status:"sent",search:"",failures:"",sort:"fire_at",dir:"desc",offset:0,limit:50};h(e,o`<h1>Sent</h1>
215
- ${dn()?o`<p class="muted">A local stand-in sends these: they are recorded here, but nothing is delivered.</p>`:null}
216
- ${rs("sent-not-connected",o`No email provider connected, so nothing can be sent yet. ${Ae()} to start sending.`)}
209
+ </section>`}function mp(e){let t=e.map(n=>di(n.status,o`${n.name}`,null,ve(n.meaning)));return dt("Status codes",o`<div class="api-ledger api-statuses">${t}</div>`)}function fp(e,t){let n=(i,r)=>o`<a href="#/api-reference/${i}" class="api-nav-res" data-sec="${i}">${r}</a>`,s=(i,r)=>o`<div class="api-nav-ops" data-of="${i.access}-${r.key}">${[...(t.heads.get(`${i.access}-${r.key}`)??[]).map(a=>o`<a href="#/api-reference/objects-${a.key}" class="api-nav-op" data-sec="objects-${a.key}">${a.title}</a>`),...wl(i,r).map(a=>o`<a href="#/api-reference/${tn(a)}" class="api-nav-op" data-route="${tn(a)}">${a.title}</a>`)]}</div>`;return o`<a href="#/api-reference" class="api-nav-tier" data-sec="overview" data-tier="overview">Introduction</a>${e.concepts.map(i=>n(`overview-${i.key}`,i.title))}${e.groups.map(i=>o`<a href="#/api-reference/${i.access}" class="api-nav-tier" data-sec="${i.access}" data-tier="${i.access}">${i.title}</a>${i.resources.map(r=>[i.resources.length>1?n(`${i.access}-${r.key}`,r.title):null,s(i,r)])}`)}`}function hp(e,t){let n=e.replace(/^[a-z]+:\/\/[^/]*/,"").replace(/[?#].*$/,"");if(!n.startsWith("/"))return!1;let s=n.replace(/(.)\/+$/,"$1").split("/"),i=t.split("/");return s.length===i.length&&i.every((r,a)=>r.startsWith(":")?s[a]!=="":r===s[a])}function bp(e,t){let n=e.dataset.path;return(e.dataset.hay??"").includes(t)||n!==void 0&&hp(t,n)}function gl(e,t,n){let s=e.trim().toLowerCase().split(/\s+/).filter(Boolean);t.classList.toggle("filtering",s.length>0);let i=0;for(let l of N(".api-section",n)){let d=0;for(let m of N(".api-res",l)){let v=m.dataset.hay!==void 0,f=0;for(let S of v?[m]:N("li[data-hay]",m)){let $=s.every(P=>bp(S,P));S.hidden=!$,f+=$?1:0;let M=S.dataset.route?t.querySelector(`a[data-route="${S.dataset.route}"]`):null;M&&(M.hidden=!$)}m.hidden=f===0;for(let S of N(`.api-nav-ops[data-of="${m.dataset.sec}"] a[data-sec]`,t))S.hidden=s.length>0&&f===0;let p=t.querySelector(`a[data-sec="${m.dataset.sec}"]`);p&&(p.hidden=f===0),d+=f}l.hidden=d===0;let u=t.querySelector(`a[data-tier="${l.dataset.tier}"]`);u&&(u.hidden=d===0),i+=d}let r=N(".api-section",n),a=r.filter(l=>!l.hidden).at(-1);for(let l of r)l.classList.toggle("api-last",l===a);c("#apiEmpty",n).hidden=i>0}function ai(e,t,n){let s=(c(".room-bar").getBoundingClientRect().height||54)+8,i=N(".api-section, .api-res, .api-object, li[data-route]",t).filter(S=>!S.closest("[hidden]")),r=window.scrollY>0&&Math.ceil(window.innerHeight+window.scrollY)>=document.documentElement.scrollHeight,a;for(let S of i)if(r||S.getBoundingClientRect().top<=s)a=S;else break;let l=N("a[data-sec], a[data-route]",e).filter(S=>!S.hidden&&getComputedStyle(S).display!=="none"),d=S=>S?(S.dataset.route?l.find(M=>M.dataset.route===S.dataset.route):l.find(M=>M.dataset.sec===(S.dataset.sec??S.dataset.tier)))??d(S.parentElement?.closest(".api-res, .api-section")):void 0,u=a?.closest(".api-res")?.dataset.sec;for(let S of N(".api-nav-ops",e))S.classList.toggle("open",S.dataset.of===u);let m=d(a??i[0]);for(let S of N("a[data-sec], a[data-route]",e))S.classList.toggle("active",S===m);let v=e.closest(".rail-inner");if(m&&v&&v.scrollHeight>v.clientHeight){let S=m.getBoundingClientRect(),$=v.getBoundingClientRect();(S.top<$.top+40||S.bottom>$.bottom-40)&&(v.scrollTop+=S.top-$.top-$.height/3)}let f=a?.dataset.route??a?.dataset.sec??a?.dataset.tier,p=f&&f!=="overview"&&window.scrollY>0?`#/api-reference/${f}`:"#/api-reference";n&&location.hash!==p&&history.replaceState(history.state,"",p)}function vl(e){return document.getElementById(e==="overview"?"api-intro":`api-${e}`)}function yl(e){e.id==="api-intro"?window.scrollTo(0,0):e.scrollIntoView({block:"start"}),e.querySelector(":scope > h1, :scope > h2, :scope > .api-res-head h3, :scope > .api-op-head h4, :scope > article > .api-op-head h4")?.focus({preventScroll:!0})}async function pi(e,t,n){ie(t,"API reference"),h(e,Ut("api-reference",o`<div class="toc-label">API</div><nav class="api-nav" id="apiNav" aria-label="API sections"></nav>`,o`<div class="api-content" id="apiContent"><p class="muted">Loading…</p></div>`));let s=c("#apiNav"),i=c("#apiContent"),r=p=>{let S=p.target instanceof Element?p.target.closest("a[data-sec], a[data-route]"):null,$=S?.dataset.route?document.getElementById(`route-${S.dataset.route}`):S?.dataset.sec?vl(S.dataset.sec):null;!$||p.button!==0||p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||(p.preventDefault(),($.closest("[hidden]")||S?.closest("#apiEmpty"))&&v(""),history.replaceState(history.state,"",S?.getAttribute("href")??location.hash),yl($),ai(s,i,!1))};s.addEventListener("click",r),i.addEventListener("click",r);let a;try{a=await L("/api/reference",{signal:t})}catch(p){re(i,V(p),()=>ee((S,$)=>pi(S,$,n)));return}let l={meanings:new Map(a.refusals.flatMap(p=>p.codes.map(S=>[S.code,S.meaning]))),objects:new Map(a.objects.map(p=>[p.key,p.title])),heads:sp(a)};h(s,fp(a,l)),h(i,o`<header class="api-head" id="api-intro"><h1 tabindex="-1">API reference</h1><p class="muted">Every endpoint this instance serves, the one API the web editor and Claude both call. It's read from the running code, so it always matches this version. Base URL <code>${location.origin}</code>.</p><div class="api-filter">${O("search")}<input type="search" id="apiFilter" placeholder="Filter by name, path, URL, or error code" autocomplete="off" aria-label="Filter routes" aria-keyshortcuts="/"><kbd aria-hidden="true">/</kbd><button type="button" class="icon api-filter-clear" id="apiFilterClear" aria-label="Clear filter" hidden>${O("x")}</button></div></header>${pp(a)}${a.groups.map(p=>dp(p,l))}<p class="api-empty muted" id="apiEmpty" hidden>Nothing matches. Try a path segment like <code>sends</code>, a method like <code>DELETE</code>, or a code like <code>stale_revision</code>, or start from the <a href="#/api-reference" data-sec="overview">Introduction</a>.</p>`);let d=c("#apiFilter"),u=c("#apiFilterClear"),m=()=>ai(s,i,!1),v=p=>{d.value=p,u.hidden=p==="",gl(p,s,i),m()};d.addEventListener("input",()=>v(d.value)),u.addEventListener("click",()=>{v(""),d.focus()}),We(i),document.addEventListener("keydown",p=>{let S=p.target instanceof HTMLElement&&(p.target.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(p.target.tagName));p.key==="/"&&!S&&!p.metaKey&&!p.ctrlKey&&!p.altKey?(p.preventDefault(),d.focus()):p.key==="Escape"&&p.target===d&&d.value&&v("")},{signal:t}),gl("",s,i),window.addEventListener("scroll",()=>ai(s,i,!0),{passive:!0,signal:t}),window.scrollTo(0,0);let f=n?document.getElementById(`route-${n}`)??vl(n):null;f&&yl(f),m()}var Vs=V;function gp(e){let t=[Qe(e,"reschedule")?o`<button class="ghost" data-reschedule="${e.id}">Edit schedule</button>`:null,Qe(e,"cancel")?o`<button class="ghost" data-cancel="${e.id}">Cancel</button>`:null];return t.some(Boolean)?o`<div class="row" data-closes="${e.fire_at}">${t}</div>`:null}async function mi(e,t){ie(t,"Sent");let n={status:"sent",search:"",failures:"",sort:"fire_at",dir:"desc",offset:0,limit:50};h(e,o`<h1>Sent</h1>
210
+ ${fn()?o`<p class="muted">A local stand-in sends these: they are recorded here, but nothing is delivered.</p>`:null}
211
+ ${hs("sent-not-connected",o`No email provider connected, so nothing can be sent yet. ${Ae()} to start sending.`)}
217
212
  <div id="stuck"></div>
218
213
  <h2>Scheduled</h2><div id="scheduled"><p class="muted">Loading…</p></div>
219
214
  <div id="active"></div>
220
215
  <h2>Sent posts</h2>
221
- ${jt({searchPlaceholder:"Search subject\u2026",failures:!0})}
216
+ ${Kt({searchPlaceholder:"Search subject\u2026",failures:!0})}
222
217
  <div id="sendsList"><p class="muted">Loading…</p></div>
223
- <div id="sendsPager"></div>`);let s=c("#stuck",e),i=c("#scheduled",e),a=c("#active",e),r=c("#sendsList",e),l=c("#sendsPager",e),d=Ss(e,t),u=[],f=!1,S=0,b=0,p=new Map;function v(){z(),q(),Fe()}function x(g){let E=g.filter(L=>L.status==="sending"&&!bn(L));h(a,E.length?o`<h2>In progress</h2>${E.map(L=>$s(L))}`:o``);for(let L of I("[data-watch]",a))L.onclick=$=>{$.target instanceof Element&&$.target.tagName==="A"||(location.hash=`#/sent/${L.dataset.watch}`)}}function M(g){let E=g.flatMap(V=>{let re=he(V,"refused");return re?[{s:V,c:re}]:[]}),L=ve()?E.filter(V=>V.c.cause==="not_connected"):[],$=E.filter(V=>!L.includes(V)),_=e.querySelector(".sent-not-connected");_&&(_.hidden=L.length>0);let K=L.map(({s:V},re)=>o`${re===0?"":re===L.length-1?" and ":", "}<a href="#/sent/${V.id}">${V.subject}</a>`),D=L.length?o`<div class="card stuck-card sent-held"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div>${is(o`${K}`,L.length)}</div></div></div>`:null,ae=g.flatMap(V=>{let re=he(V,"wedged");return re?[{s:V,c:re}]:[]});h(s,o`${D}${$.map(({s:V,c:re})=>o`<div class="card stuck-card"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div><strong><a href="#/sent/${V.id}">${V.subject}</a></strong><div class="muted">${re.message}</div></div></div></div>`)}${ae.map(({s:V,c:re})=>o`<div class="card stuck-card"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div><strong><a href="#/sent/${V.id}">${V.subject}</a></strong><div class="muted">${re.message}</div></div></div>${Ze(V,"resolve")?o`<button class="primary" data-resolve="${V.id}">Resolve…</button>`:null}</div>`)}`);for(let V of I("[data-resolve]",s)){let re=ae.find(lt=>lt.s.id===V.dataset.resolve);re&&(V.onclick=()=>_s({id:re.s.id,c_in_flight:re.c.count},v,t))}}function A(){for(let g of p.values()){let E=I("tr[data-id]",r).find(L=>L.dataset.id===g.id)?.querySelector("td.delivered");E&&h(E,Ut(g.counts))}}function H(){let g=Dt(u,p);M(g),f&&x(g),A()}let T=g=>g==="scheduled"||g==="due",m=g=>g==="sent"||g==="complete";function y(g){for(let E of g.sends)p.set(E.id,E);for(let E of g.removed)p.delete(E);H(),(g.sends.some(E=>T(nt(E)))||g.changes.some(E=>T(E.from)))&&z(),g.removed.length?(z(),q()):g.changes.some(E=>m(E.to)&&!m(E.from))&&q()}let C=!1;function U(g){let E=g.filter(L=>L!==null);C||!E.length||(C=!0,Ot({cursor:E.map(L=>L.cursor).reduce(ds),sends:E.flatMap(L=>L.sends)},{update:y,stale:()=>{t.aborted||ee(Yo)}},t))}async function J(){try{let g=await R("/api/sends?status=sending&limit=200",{signal:t});return u=g.sends,f=!0,H(),g}catch(g){return oe(a,Ms(g),async()=>U([await J()])),null}}async function z(){let g=++S;try{let E=await R("/api/sends?status=scheduled&sort=fire_at&dir=asc&limit=200",{signal:t});if(g!==S)return E;let{sends:L}=E,$=D=>o`<div class="card spread clickable sched-card" data-post="${D.post_id}"><div><a class="card-link sched-subj" href="#/edit/${D.post_id}">${D.subject}</a><div class="muted">${ws(D)} · ${W(D.fire_at)} · ${D.audience.count} recipients${ys(D)}</div></div>${Eu(D)}</div>`,[_,...K]=L;if(!_)h(i,o`<p class="muted">Nothing scheduled.</p>`);else{h(i,o`${$(_)}${K.length?o`<div id="schedMore" hidden>${K.map($)}</div><button type="button" class="ghost sched-toggle" id="schedToggle" aria-expanded="false">Show all ${L.length} scheduled</button>`:null}`);let D=i.querySelector("#schedToggle");D&&(D.onclick=()=>{let ae=c("#schedMore",i),V=ae.hidden;ae.hidden=!V,D.setAttribute("aria-expanded",String(V)),D.textContent=V?"Show fewer":`Show all ${L.length} scheduled`})}for(let D of I(".card.clickable",i))D.onclick=ae=>{let V=ae.target;V instanceof Element&&V.tagName!=="A"&&!V.closest("button")&&(location.hash=`#/edit/${D.dataset.post}`)};for(let D of I("[data-reschedule]",i)){let ae=L.find(V=>V.id===D.dataset.reschedule);ae&&(D.onclick=()=>{Ts(ae,v,t)})}for(let D of I("[data-cancel]",i))D.onclick=()=>G(D,"Canceling\u2026",async()=>{try{await R(`/api/sends/${D.dataset.cancel}/cancel`,{method:"POST"}),O("Canceled"),v()}catch(ae){O(Ms(ae))}});return d(),E}catch(E){return g===S&&oe(i,Ms(E),async()=>U([await z()])),null}}async function q(){let g=++b;try{let E=await R(`/api/sends?${qt(n)}`,{signal:t});if(g!==b)return E;let L=E.sends;if(!L.length)return h(r,o`<p class="muted">${n.search?"No sent posts match.":n.failures?"Every sent post delivered cleanly.":"No sent posts yet."}</p>`),h(l,o``),E;h(r,o`<div class="table-wrap"><table class="list-table sent-table stacks"><colgroup><col><col class="c-date"><col class="c-num"><col class="c-delivered"></colgroup><thead><tr>${$e("Subject","subject",n)}${$e("When","fire_at",n)}${$e("Recipients","audience.count",n,"num")}<th class="num">Delivered</th></tr></thead><tbody>${L.map($=>o`<tr class="clickable" data-id="${$.id}"><td class="subject">${wt(o`<a href="#/sent/${$.id}">${$.subject}</a>`,$)}</td><td class="muted">${W($.completed_at??$.fire_at)}</td><td class="num recipients"><span class="n">${$.audience.count.toLocaleString()}</span></td><td class="num delivered">${Ut($.counts)}</td></tr>`)}</tbody></table></div>`),st(r,n,q);for(let $ of I("tr[data-id]",r))$.onclick=_=>{_.target instanceof Element&&_.target.tagName==="A"||(location.hash=`#/sent/${$.dataset.id}`)};return ot(l,n,E.page,q),A(),E}catch(E){return g===b&&oe(r,Ms(E),async()=>U([await q()])),null}}Wt(e,n,q),U(await Promise.all([z(),J(),q()]))}var xu="erased:";function qa(e){return e.startsWith(xu)}function kt(e,t,n){let s=URL.createObjectURL(new Blob([e],{type:n})),i=document.createElement("a");i.href=s,i.download=t,i.click(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function Is(e){if(e.event==="delivered")return{label:"Delivered",sw:"ok"};if(e.event==="bounced")return e.bounce_kind==="hard"?{label:"Hard bounce",sw:"warn"}:e.bounce_kind==="soft"?{label:"Soft bounce",sw:"warn"}:{label:"Bounce",sw:"warn"};if(e.event==="complained")return{label:"Complained",sw:"danger"};switch(e.status){case"unsent":return{label:"Unsent",sw:"neutral"};case"skipped":return{label:"Skipped",sw:"neutral"};case"accepted":return{label:"Accepted",sw:"sending"};default:return{label:"In flight",sw:"sending"}}}var _n=F;async function Zo(e,t,n){let s=()=>{n.aborted||ee((r,l)=>Zo(e,r,l))};se(n,"Sent"),h(t,o`<p class="muted">Loading…</p>`);let i;try{i=await R(`/api/sends/${e}`,{signal:n})}catch(r){oe(t,_n(r),s);return}if(n.aborted)return;let{send:a}=i;if(se(n,a.subject||"Untitled"),a.status==="scheduled"){location.replace(`#/edit/${a.post_id}`);return}return a.status==="sending"?Hu(i,t,n,s):Ou(e,i,t,n,s)}var ku={scheduled:{label:"Scheduled",tone:"scheduled"},due:{label:"Due",tone:"scheduled"},progressing:{label:"Sending",tone:"sending"},retrying:{label:"Retrying",tone:"warn"},backing_off:{label:"Backing off",tone:"warn"},needs_attention:{label:"Needs attention",tone:"danger"},settling:{label:"Settling",tone:"sending"},complete:{label:"Complete",tone:"ok"},canceled:{label:"Canceled",tone:"muted"}},_u={progressing:"Handing recipients to the provider.",retrying:"Some recipients hit a transient error and will be retried.",backing_off:"Some recipients hit a transient error. They\u2019re retried on the next sweep.",needs_attention:"Some deliveries can\u2019t be confirmed either way, and wait on your decision.",settling:"Dispatch complete, waiting on delivery receipts."};function Tu(e){let t=e.provider.halt;return t&&Ja(e)?`${t.cause==="not_connected"?"No email provider is connected":t.reason==="account"?"The provider is refusing this account":"The provider is unavailable"}, so this post waits with the send already held and hasn\u2019t handed anyone off; ${Ft(t.retry_at)}.`:Le(e,"refused")&&t?.cause==="not_connected"?`No email provider is connected, so nothing goes out until one is; ${Ft(t.retry_at)}.`:Le(e,"refused")&&t?`The provider is refusing ${fo(t.cause)?"this send":"this account"}, so nothing more goes out until it\u2019s fixed; ${Ft(t.retry_at)}.`:e.phase==="backing_off"&&t?.reason==="unavailable"?`The provider is unavailable; ${Ft(t.retry_at)}.`:Le(e,"stuck")?"Nothing is being handed off to the provider right now.":e.phase==="progressing"&&e.counts.dispatched===0&&e.counts.pending>0?"Paused between ticks. It resumes on the next sweep.":_u[e.phase]||""}function Tn(e){let t=ku[e]??{label:e,tone:"muted"};return o`<span class="phase-pill tone-${t.tone}">${t.label}</span>`}function Lu(e,t,n,s,i){let a=s>0?hn(100*n/s):0;return o`<div class="wbar-row">
218
+ <div id="sendsPager"></div>`);let s=c("#stuck",e),i=c("#scheduled",e),r=c("#active",e),a=c("#sendsList",e),l=c("#sendsPager",e),d=Cs(e,t),u=[],m=!1,v=0,f=0,p=new Map;function S(){F(),K(),Fe()}function $(b){let E=b.filter(C=>C.status==="sending"&&!wn(C));h(r,E.length?o`<h2>In progress</h2>${E.map(C=>As(C))}`:o``);for(let C of N("[data-watch]",r))C.onclick=x=>{x.target instanceof Element&&x.target.tagName==="A"||(location.hash=`#/sent/${C.dataset.watch}`)}}function M(b){let E=b.flatMap(q=>{let ne=he(q,"refused");return ne?[{s:q,c:ne}]:[]}),C=ge()?E.filter(q=>q.c.cause==="not_connected"):[],x=E.filter(q=>!C.includes(q)),W=e.querySelector(".sent-not-connected");W&&(W.hidden=C.length>0);let oe=C.map(({s:q},ne)=>o`${ne===0?"":ne===C.length-1?" and ":", "}<a href="#/sent/${q.id}">${q.subject}</a>`),k=C.length?o`<div class="card stuck-card sent-held"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div>${fs(o`${oe}`,C.length)}</div></div></div>`:null,G=b.flatMap(q=>{let ne=he(q,"wedged");return ne?[{s:q,c:ne}]:[]});h(s,o`${k}${x.map(({s:q,c:ne})=>o`<div class="card stuck-card"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div><strong><a href="#/sent/${q.id}">${q.subject}</a></strong><div class="muted">${ne.message}</div></div></div></div>`)}${G.map(({s:q,c:ne})=>o`<div class="card stuck-card"><div class="stuck-head"><span class="stuck-dot">⚠️</span><div><strong><a href="#/sent/${q.id}">${q.subject}</a></strong><div class="muted">${ne.message}</div></div></div>${Qe(q,"resolve")?o`<button class="primary" data-resolve="${q.id}">Resolve…</button>`:null}</div>`)}`);for(let q of N("[data-resolve]",s)){let ne=G.find(He=>He.s.id===q.dataset.resolve);ne&&(q.onclick=()=>Os({id:ne.s.id,c_in_flight:ne.c.count},S,t))}}function P(){for(let b of p.values()){let E=N("tr[data-id]",a).find(C=>C.dataset.id===b.id)?.querySelector("td.delivered");E&&h(E,jt(b.counts))}}function A(){let b=qt(u,p);M(b),m&&$(b),P()}let H=b=>b==="scheduled"||b==="due",y=b=>b==="sent"||b==="complete";function w(b){for(let E of b.sends)p.set(E.id,E);for(let E of b.removed)p.delete(E);A(),(b.sends.some(E=>H(ot(E)))||b.changes.some(E=>H(E.from)))&&F(),b.removed.length?(F(),K()):b.changes.some(E=>y(E.to)&&!y(E.from))&&K()}let T=!1;function D(b){let E=b.filter(C=>C!==null);T||!E.length||(T=!0,Ft({cursor:E.map(C=>C.cursor).reduce(ys),sends:E.flatMap(C=>C.sends)},{update:w,stale:()=>{t.aborted||ee(mi)}},t))}async function R(){try{let b=await L("/api/sends?status=sending&limit=200",{signal:t});return u=b.sends,m=!0,A(),b}catch(b){return re(r,Vs(b),async()=>D([await R()])),null}}async function F(){let b=++v;try{let E=await L("/api/sends?status=scheduled&sort=fire_at&dir=asc&limit=200",{signal:t});if(b!==v)return E;let{sends:C}=E,x=k=>o`<div class="card spread clickable sched-card" data-post="${k.post_id}"><div><a class="card-link sched-subj" href="#/edit/${k.post_id}">${k.subject}</a><div class="muted">${Rs(k)} · ${j(k.fire_at)} · ${k.audience.count} recipients${Ls(k)}</div></div>${gp(k)}</div>`,[W,...oe]=C;if(!W)h(i,o`<p class="muted">Nothing scheduled.</p>`);else{h(i,o`${x(W)}${oe.length?o`<div id="schedMore" hidden>${oe.map(x)}</div><button type="button" class="ghost sched-toggle" id="schedToggle" aria-expanded="false">Show all ${C.length} scheduled</button>`:null}`);let k=i.querySelector("#schedToggle");k&&(k.onclick=()=>{let G=c("#schedMore",i),q=G.hidden;G.hidden=!q,k.setAttribute("aria-expanded",String(q)),k.textContent=q?"Show fewer":`Show all ${C.length} scheduled`})}for(let k of N(".card.clickable",i))k.onclick=G=>{let q=G.target;q instanceof Element&&q.tagName!=="A"&&!q.closest("button")&&(location.hash=`#/edit/${k.dataset.post}`)};for(let k of N("[data-reschedule]",i)){let G=C.find(q=>q.id===k.dataset.reschedule);G&&(k.onclick=()=>{Ds(G,S,t)})}for(let k of N("[data-cancel]",i))k.onclick=()=>Z(k,"Canceling\u2026",async()=>{try{await L(`/api/sends/${k.dataset.cancel}/cancel`,{method:"POST"}),U("Canceled"),S()}catch(G){U(Vs(G))}});return d(),E}catch(E){return b===v&&re(i,Vs(E),async()=>D([await F()])),null}}async function K(){let b=++f;try{let E=await L(`/api/sends?${Vt(n)}`,{signal:t});if(b!==f)return E;let C=E.sends;if(!C.length)return h(a,o`<p class="muted">${n.search?"No sent posts match.":n.failures?"Every sent post delivered cleanly.":"No sent posts yet."}</p>`),h(l,o``),E;h(a,o`<div class="table-wrap"><table class="list-table sent-table stacks"><colgroup><col><col class="c-date"><col class="c-num"><col class="c-delivered"></colgroup><thead><tr>${Ee("Subject","subject",n)}${Ee("When","fire_at",n)}${Ee("Recipients","audience.count",n,"num")}<th class="num">Delivered</th></tr></thead><tbody>${C.map(x=>o`<tr class="clickable" data-id="${x.id}"><td class="subject">${xt(o`<a href="#/sent/${x.id}">${x.subject}</a>`,x)}</td><td class="muted">${j(x.completed_at??x.fire_at)}</td><td class="num recipients"><span class="n">${x.audience.count.toLocaleString()}</span></td><td class="num delivered">${jt(x.counts)}</td></tr>`)}</tbody></table></div>`),it(a,n,K);for(let x of N("tr[data-id]",a))x.onclick=W=>{W.target instanceof Element&&W.target.tagName==="A"||(location.hash=`#/sent/${x.dataset.id}`)};return rt(l,n,E.page,K),P(),E}catch(E){return b===f&&re(a,Vs(E),async()=>D([await K()])),null}}Gt(e,n,K),D(await Promise.all([F(),R(),K()]))}var vp="erased:";function Sl(e){return e.startsWith(vp)}function Rt(e,t,n){let s=URL.createObjectURL(new Blob([e],{type:n})),i=document.createElement("a");i.href=s,i.download=t,i.click(),setTimeout(()=>URL.revokeObjectURL(s),1e4)}function Ks(e){if(e.event==="delivered")return{label:"Delivered",sw:"ok"};if(e.event==="bounced")return e.bounce_kind==="hard"?{label:"Hard bounce",sw:"warn"}:e.bounce_kind==="soft"?{label:"Soft bounce",sw:"warn"}:{label:"Bounce",sw:"warn"};if(e.event==="complained")return{label:"Complained",sw:"danger"};switch(e.status){case"unsent":return{label:"Unsent",sw:"neutral"};case"skipped":return{label:"Skipped",sw:"neutral"};case"accepted":return{label:"Accepted",sw:"sending"};default:return{label:"In flight",sw:"sending"}}}var Mn=V;async function fi(e,t,n){let s=()=>{n.aborted||ee((a,l)=>fi(e,a,l))};ie(n,"Sent"),h(t,o`<p class="muted">Loading…</p>`);let i;try{i=await L(`/api/sends/${e}`,{signal:n})}catch(a){re(t,Mn(a),s);return}if(n.aborted)return;let{send:r}=i;if(ie(n,r.subject||"Untitled"),r.status==="scheduled"){location.replace(`#/edit/${r.post_id}`);return}return r.status==="sending"?_p(i,t,n,s):Hp(e,i,t,n,s)}var yp={scheduled:{label:"Scheduled",tone:"scheduled"},due:{label:"Due",tone:"scheduled"},progressing:{label:"Sending",tone:"sending"},retrying:{label:"Retrying",tone:"warn"},backing_off:{label:"Backing off",tone:"warn"},needs_attention:{label:"Needs attention",tone:"danger"},settling:{label:"Settling",tone:"sending"},complete:{label:"Complete",tone:"ok"},canceled:{label:"Canceled",tone:"muted"}},wp={progressing:"Handing recipients to the provider.",retrying:"Some recipients hit a transient error and will be retried.",backing_off:"Some recipients hit a transient error. They\u2019re retried on the next sweep.",needs_attention:"Some deliveries can\u2019t be confirmed either way, and wait on your decision.",settling:"Dispatch complete, waiting on delivery receipts."};function Sp(e){let t=e.provider.halt;return t&&Cl(e)?`${t.cause==="not_connected"?"No email provider is connected":t.reason==="account"?"The provider is refusing this account":"The provider is unavailable"}, so this post waits with the send already held and hasn\u2019t handed anyone off; ${Wt(t.retry_at)}.`:Re(e,"refused")&&t?.cause==="not_connected"?`No email provider is connected, so nothing goes out until one is; ${Wt(t.retry_at)}.`:Re(e,"refused")&&t?`The provider is refusing ${To(t.cause)?"this send":"this account"}, so nothing more goes out until it\u2019s fixed; ${Wt(t.retry_at)}.`:e.phase==="backing_off"&&t?.reason==="unavailable"?`The provider is unavailable; ${Wt(t.retry_at)}.`:Re(e,"stuck")?"Nothing is being handed off to the provider right now.":e.phase==="progressing"&&e.counts.dispatched===0&&e.counts.pending>0?"Paused between ticks. It resumes on the next sweep.":wp[e.phase]||""}function In(e){let t=yp[e]??{label:e,tone:"muted"};return o`<span class="phase-pill tone-${t.tone}">${t.label}</span>`}function $p(e,t,n,s,i){let r=s>0?yn(100*n/s):0;return o`<div class="wbar-row">
224
219
  <div class="wbar-head"><span class="wbar-label">${t}</span><span class="wbar-count">${n.toLocaleString()} / ${s.toLocaleString()}</span></div>
225
- <div class="wbar" role="progressbar" aria-valuenow="${a}" aria-valuemin="0" aria-valuemax="100"><div class="wbar-fill tone-${e}" style="width:${a}%"></div></div>
220
+ <div class="wbar" role="progressbar" aria-valuenow="${r}" aria-valuemin="0" aria-valuemax="100"><div class="wbar-fill tone-${e}" style="width:${r}%"></div></div>
226
221
  ${i?o`<div class="wbar-sub muted">${i}</div>`:null}
227
- </div>`}function Ru(e,t,n,s,i){let a=s>0?hn(100*n/s):0,r=s>0?hn(100*t/s):0;return o`<div class="wbar-row">
222
+ </div>`}function xp(e,t,n,s,i){let r=s>0?yn(100*n/s):0,a=s>0?yn(100*t/s):0;return o`<div class="wbar-row">
228
223
  <div class="wbar-head"><span class="wbar-label">${e}</span><span class="wbar-count">${t.toLocaleString()} of ${n.toLocaleString()} accepted</span></div>
229
- <div class="wbar dual" role="progressbar" aria-valuenow="${r}" aria-valuemin="0" aria-valuemax="100">
230
- <div class="wbar-fill tone-accepted" style="width:${a}%"></div>
231
- <div class="wbar-fill tone-ok" style="width:${r}%"></div>
224
+ <div class="wbar dual" role="progressbar" aria-valuenow="${a}" aria-valuemin="0" aria-valuemax="100">
225
+ <div class="wbar-fill tone-accepted" style="width:${r}%"></div>
226
+ <div class="wbar-fill tone-ok" style="width:${a}%"></div>
232
227
  </div>
233
228
  <div class="wbar-sub muted">${i}</div>
234
- </div>`}var Cu=[{key:"pending",label:"Pending",sw:"neutral"},{key:"dispatched",label:"In flight",sw:"sending"},{key:"accepted",label:"Accepted",sw:"sending"},{key:"delivered",label:"Delivered",sw:"ok"},{key:"bounced",label:"Bounced",sw:"warn"},{key:"complained",label:"Complained",sw:"danger"},{key:"unsent",label:"Unsent",sw:"neutral"},{key:"skipped",label:"Skipped",sw:"neutral"}];function Au(e){return o`<div class="wcounts">${Cu.map(t=>o`<div class="wcount"><div class="wcount-n">${(e[t.key]||0).toLocaleString()}</div><div class="wcount-l"><span class="rec-sw sw-${t.sw}"></span>${t.label}</div></div>`)}</div>`}function Za(e){let t=e.counts,n=t.accepted+t.delivered+t.bounced+t.complained,s=e.dispatch.rate_per_min,i=e.dispatch.eta_ms,a=e.status==="sending"?`${Tu(e)}${i?`${s?` \xB7 ~${s.toLocaleString()}/min`:""} \xB7 ETA ${vs(i)}`:""}`:"Dispatch complete.",r=(t.unsent||0)+(t.bounced||0)+(t.complained||0),l=dn()?"Local stand-in: nothing is delivered":ve()?"No email provider connected":`Provider: ${e.provider?.name||"unknown"}`,d=he(e,"refused"),u=d?.cause==="not_connected",f=fo(d?.cause??null),S=he(e,"stuck"),b=he(e,"provider_unavailable"),p=b?.severity==="warn"?b:void 0;return o`
235
- ${S?o`<div class="health amber" role="status"><span class="health-dot">⚠️</span><div>${S.message}</div></div>`:null}
229
+ </div>`}var Ep=[{key:"pending",label:"Pending",sw:"neutral"},{key:"dispatched",label:"In flight",sw:"sending"},{key:"accepted",label:"Accepted",sw:"sending"},{key:"delivered",label:"Delivered",sw:"ok"},{key:"bounced",label:"Bounced",sw:"warn"},{key:"complained",label:"Complained",sw:"danger"},{key:"unsent",label:"Unsent",sw:"neutral"},{key:"skipped",label:"Skipped",sw:"neutral"}];function kp(e){return o`<div class="wcounts">${Ep.map(t=>o`<div class="wcount"><div class="wcount-n">${(e[t.key]||0).toLocaleString()}</div><div class="wcount-l"><span class="rec-sw sw-${t.sw}"></span>${t.label}</div></div>`)}</div>`}function Rl(e){let t=e.counts,n=t.accepted+t.delivered+t.bounced+t.complained,s=e.dispatch.rate_per_min,i=e.dispatch.eta_ms,r=e.status==="sending"?`${Sp(e)}${i?`${s?` \xB7 ~${s.toLocaleString()}/min`:""} \xB7 ETA ${Ts(i)}`:""}`:"Dispatch complete.",a=(t.unsent||0)+(t.bounced||0)+(t.complained||0),l=fn()?"Local stand-in: nothing is delivered":ge()?"No email provider connected":`Provider: ${e.provider?.name||"unknown"}`,d=he(e,"refused"),u=d?.cause==="not_connected",m=To(d?.cause??null),v=he(e,"stuck"),f=he(e,"provider_unavailable"),p=f?.severity==="warn"?f:void 0;return o`
230
+ ${v?o`<div class="health amber" role="status"><span class="health-dot">⚠️</span><div>${v.message}</div></div>`:null}
236
231
  ${p?o`<div class="health amber" role="status"><span class="health-dot">⚠️</span><div>${p.message}</div></div>`:null}
237
- ${d?o`<div class="health red" role="alert"><span class="health-dot">⚠️</span><div><strong>${u?"No email provider is connected":f?"The provider is refusing this send":"The provider is refusing this account"}</strong>${u?null:o`<div>${d.error}</div>`}<div class="refused-advice">${u?go():d.advice}</div><div>${d.since===null?null:`Since ${W(d.since)}. `}No one has been marked unsent because of this, and once ${u?"one is connected":"this is fixed"} the send resumes at its next retry${d.retry_at===null?"":`, ${W(d.retry_at)}`}.</div></div></div>`:null}
232
+ ${d?o`<div class="health red" role="alert"><span class="health-dot">⚠️</span><div><strong>${u?"No email provider is connected":m?"The provider is refusing this send":"The provider is refusing this account"}</strong>${u?null:o`<div>${d.error}</div>`}<div class="refused-advice">${u?Co():d.advice}</div><div>${d.since===null?null:`Since ${j(d.since)}. `}No one has been marked unsent because of this, and once ${u?"one is connected":"this is fixed"} the send resumes at its next retry${d.retry_at===null?"":`, ${j(d.retry_at)}`}.</div></div></div>`:null}
238
233
  <div class="wbars">
239
- ${Lu("sending","Dispatch: provider-accepted",n,e.audience.count,a)}
240
- ${Ru("Delivery: webhook-confirmed",e.delivery.confirmed,n,e.audience.count,"Delivery lags acceptance: grey is accepted but unconfirmed, and green fills in as receipts arrive.")}
234
+ ${$p("sending","Dispatch: provider-accepted",n,e.audience.count,r)}
235
+ ${xp("Delivery: webhook-confirmed",e.delivery.confirmed,n,e.audience.count,"Delivery lags acceptance: grey is accepted but unconfirmed, and green fills in as receipts arrive.")}
241
236
  </div>
242
- ${Au(t)}
243
- <div class="whealth${r?" has-failures":""}"><span class="whealth-dot"></span><span>${l} · ${r?`${r.toLocaleString()} bounced / unsent / complained`:"no delivery failures"}</span></div>`}function Ja(e){return e.status==="sending"&&e.provider.halt!==null&&!e.audience.fixed}function Ns(e){let t=wa(e);return t===null?null:o`<div class="rec-meta rec-by">${t}</div>`}function Qa(e){if(Ja(e))return o`Due ${W(e.fire_at)} · held before handing anyone off · about ${e.audience.count.toLocaleString()} recipients`;let t=e.started_at?`Started ${W(e.started_at)}`:"Sending now";return o`${t} · ${e.audience.count.toLocaleString()} recipients`}function ja(e){let t=e;return o`
237
+ ${kp(t)}
238
+ <div class="whealth${a?" has-failures":""}"><span class="whealth-dot"></span><span>${l} · ${a?`${a.toLocaleString()} bounced / unsent / complained`:"no delivery failures"}</span></div>`}function Cl(e){return e.status==="sending"&&e.provider.halt!==null&&!e.audience.fixed}function Gs(e){let t=Xa(e);return t===null?null:o`<div class="rec-meta rec-by">${t}</div>`}function Al(e){if(Cl(e))return o`Due ${j(e.fire_at)} · held before handing anyone off · about ${e.audience.count.toLocaleString()} recipients`;let t=e.started_at?`Started ${j(e.started_at)}`:"Sending now";return o`${t} · ${e.audience.count.toLocaleString()} recipients`}function $l(e){let t=e;return o`
244
239
  <div class="editor-head">
245
240
  <a href="#/sent" class="back">← Sent</a>
246
- ${Ze(t,"resolve")?o`<button type="button" class="primary" id="resolveBtn">Resolve…</button>`:null}
241
+ ${Qe(t,"resolve")?o`<button type="button" class="primary" id="resolveBtn">Resolve…</button>`:null}
247
242
  </div>
248
243
  <div class="card rec-card watch-card">
249
244
  <div class="rec-head">
250
- <div class="watch-title"><h1>${e.subject||o`<em>untitled</em>`}</h1><span id="watchPill">${Tn(t.phase)}</span></div>
251
- <div class="rec-meta" id="watchMeta">${Qa(e)}</div>
252
- <div id="watchBy">${Ns(e)}</div>
245
+ <div class="watch-title"><h1>${e.subject||o`<em>untitled</em>`}</h1><span id="watchPill">${In(t.phase)}</span></div>
246
+ <div class="rec-meta" id="watchMeta">${Al(e)}</div>
247
+ <div id="watchBy">${Gs(e)}</div>
253
248
  </div>
254
- <div id="watchBody">${Za(t)}</div>
249
+ <div id="watchBody">${Rl(t)}</div>
255
250
  <p class="rec-note muted">This view updates live while the send is in flight. Delivery receipts keep arriving after dispatch finishes, and the record stays accurate as they settle.</p>
256
- </div>`}function Wa(e,t,n,s){let i=e.querySelector("#resolveBtn");if(i){let a=he(t,"wedged")?.count??t.counts.dispatched;i.onclick=()=>_s({id:t.id,c_in_flight:a},n,s)}}function Va(e,t){let n=e.querySelector("#watchPill");n&&h(n,Tn(t.phase));let s=e.querySelector("#watchMeta");s&&h(s,Qa(t));let i=e.querySelector("#watchBy");i&&h(i,o`${Ns(t)}`);let a=e.querySelector("#watchBody");a&&h(a,Za(t))}function Hu(e,t,n,s){h(t,ja(e.send)),Wa(t,e.send,s,n);let i=e.send;mt(1e3,()=>Va(t,i),n),mn(e,{update:a=>{if(a.status!=="sending"){s();return}i=a,Ze(a,"resolve")!==!!t.querySelector("#resolveBtn")?(h(t,ja(a)),Wa(t,a,s,n)):Va(t,a)},removed:s,stale:s},n)}function Ka(e){let t=[{n:e.recipients,label:"Recipients",cls:"",sw:"neutral"},{n:e.delivered,label:"Delivered",cls:"ok",sw:"ok"},{n:e.bounced,label:"Bounced",cls:"warn",sw:"warn"},{n:e.complained,label:"Complained",cls:"danger",sw:"danger"},{n:e.unsent,label:"Unsent",cls:"",sw:"neutral"}];return o`${t.map(n=>o`<div class="rec-tile"><div class="rec-n ${n.cls}">${n.n.toLocaleString()}</div><div class="rec-l"><span class="rec-sw sw-${n.sw}"></span>${n.label}</div></div>`)}`}function Ga(e){let t=e.recipients,n=[`${e.delivered.toLocaleString()} delivered`];e.bounced&&n.push(`${e.bounced.toLocaleString()} bounced`),e.complained&&n.push(`${e.complained.toLocaleString()} complained`),e.unsent&&n.push(`${e.unsent.toLocaleString()} unsent`),e.accepted&&n.push(`${e.accepted.toLocaleString()} accepted, awaiting a delivery receipt`),e.skipped&&n.push(`${e.skipped.toLocaleString()} skipped (unsubscribed or suppressed before hand-off, never mailed)`),e.pending&&n.push(`${e.pending.toLocaleString()} pending`),e.dispatched&&n.push(`${e.dispatched.toLocaleString()} in flight`);let s=`All ${t.toLocaleString()} accounted for: ${n.join(", ")}.`,i=e.bounced||e.complained?" Hard bounces are suppressed automatically and spam complaints unsubscribe the reader, so those addresses won\u2019t be mailed again.":"",a=e.bounced?" A soft bounce is temporary, so it\u2019s counted and the address stays on the list.":"";return`${s}${i}${a}`}function Pu(e,t){return Object.keys(e).every(n=>e[n]===t[n])}var Mu=[{v:"all",label:"All"},{v:"delivered",label:"Delivered"},{v:"failures",label:"Failures"}];function Iu(e){return e.search?"No recipients match that address.":e.view==="failures"?"No delivery failures. Every recipient was accepted or delivered.":e.view==="delivered"?"No delivery receipts confirmed yet.":"No recipients on this send."}function Nu(e){let t=new URLSearchParams;t.set("view",e.view);let n=(e.search||"").trim();return n&&t.set("search",n),e.sort&&(t.set("sort",e.sort),t.set("dir",e.dir??"asc")),t.set("limit",String(e.limit)),t.set("offset",String(e.offset)),t.toString()}function Bu(e,t){let n=e.map(s=>{let i=Is(s),a=o`<span class="rec-out"><span class="rec-sw sw-${i.sw}"></span>${i.label}</span>`,r=s.error||s.event_detail||"",l=s.event_at?W(s.event_at):"",d=qa(s.email)?o`<span class="muted">Erased recipient</span>`:s.email;return o`<tr><td class="rec-email">${d}</td><td>${a}</td><td class="muted">${r||"\u2014"}</td><td class="muted">${l||"\u2014"}</td></tr>`});return o`<div class="table-wrap"><table class="list-table rec-people-table"><colgroup><col><col class="c-out"><col><col class="c-date"></colgroup><thead><tr>${$e("Recipient","email",t)}<th class="c-out">Outcome</th><th>Detail</th><th class="c-date">When</th></tr></thead><tbody>${n}</tbody></table></div>`}function Ou(e,t,n,s,i){let{send:a,outcomes:r}=t;if(a.status==="canceled"){Uu(a,n);return}let l=r.recipients,d=a.completed_at??a.fire_at;h(n,o`
251
+ </div>`}function xl(e,t,n,s){let i=e.querySelector("#resolveBtn");if(i){let r=he(t,"wedged")?.count??t.counts.dispatched;i.onclick=()=>Os({id:t.id,c_in_flight:r},n,s)}}function El(e,t){let n=e.querySelector("#watchPill");n&&h(n,In(t.phase));let s=e.querySelector("#watchMeta");s&&h(s,Al(t));let i=e.querySelector("#watchBy");i&&h(i,o`${Gs(t)}`);let r=e.querySelector("#watchBody");r&&h(r,Rl(t))}function _p(e,t,n,s){h(t,$l(e.send)),xl(t,e.send,s,n);let i=e.send;bt(1e3,()=>El(t,i),n),gn(e,{update:r=>{if(r.status!=="sending"){s();return}i=r,Qe(r,"resolve")!==!!t.querySelector("#resolveBtn")?(h(t,$l(r)),xl(t,r,s,n)):El(t,r)},removed:s,stale:s},n)}function kl(e){let t=[{n:e.recipients,label:"Recipients",cls:"",sw:"neutral"},{n:e.delivered,label:"Delivered",cls:"ok",sw:"ok"},{n:e.bounced,label:"Bounced",cls:"warn",sw:"warn"},{n:e.complained,label:"Complained",cls:"danger",sw:"danger"},{n:e.unsent,label:"Unsent",cls:"",sw:"neutral"}];return o`${t.map(n=>o`<div class="rec-tile"><div class="rec-n ${n.cls}">${n.n.toLocaleString()}</div><div class="rec-l"><span class="rec-sw sw-${n.sw}"></span>${n.label}</div></div>`)}`}function _l(e){let t=e.recipients,n=[`${e.delivered.toLocaleString()} delivered`];e.bounced&&n.push(`${e.bounced.toLocaleString()} bounced`),e.complained&&n.push(`${e.complained.toLocaleString()} complained`),e.unsent&&n.push(`${e.unsent.toLocaleString()} unsent`),e.accepted&&n.push(`${e.accepted.toLocaleString()} accepted, awaiting a delivery receipt`),e.skipped&&n.push(`${e.skipped.toLocaleString()} skipped (unsubscribed or suppressed before hand-off, never mailed)`),e.pending&&n.push(`${e.pending.toLocaleString()} pending`),e.dispatched&&n.push(`${e.dispatched.toLocaleString()} in flight`);let s=`All ${t.toLocaleString()} accounted for: ${n.join(", ")}.`,i=e.bounced||e.complained?" Hard bounces are suppressed automatically and spam complaints unsubscribe the reader, so those addresses won\u2019t be mailed again.":"",r=e.bounced?" A soft bounce is temporary, so it\u2019s counted and the address stays on the list.":"";return`${s}${i}${r}`}function Tp(e,t){return Object.keys(e).every(n=>e[n]===t[n])}var Lp=[{v:"all",label:"All"},{v:"delivered",label:"Delivered"},{v:"failures",label:"Failures"}];function Rp(e){return e.search?"No recipients match that address.":e.view==="failures"?"No delivery failures. Every recipient was accepted or delivered.":e.view==="delivered"?"No delivery receipts confirmed yet.":"No recipients on this send."}function Cp(e){let t=new URLSearchParams;t.set("view",e.view);let n=(e.search||"").trim();return n&&t.set("search",n),e.sort&&(t.set("sort",e.sort),t.set("dir",e.dir??"asc")),t.set("limit",String(e.limit)),t.set("offset",String(e.offset)),t.toString()}function Ap(e,t){let n=e.map(s=>{let i=Ks(s),r=o`<span class="rec-out"><span class="rec-sw sw-${i.sw}"></span>${i.label}</span>`,a=s.error||s.event_detail||"",l=s.event_at?j(s.event_at):"",d=Sl(s.email)?o`<span class="muted">Erased recipient</span>`:s.email;return o`<tr><td class="rec-email">${d}</td><td>${r}</td><td class="muted">${a||"\u2014"}</td><td class="muted">${l||"\u2014"}</td></tr>`});return o`<div class="table-wrap"><table class="list-table rec-people-table"><colgroup><col><col class="c-out"><col><col class="c-date"></colgroup><thead><tr>${Ee("Recipient","email",t)}<th class="c-out">Outcome</th><th>Detail</th><th class="c-date">When</th></tr></thead><tbody>${n}</tbody></table></div>`}function Hp(e,t,n,s,i){let{send:r,outcomes:a}=t;if(r.status==="canceled"){Mp(r,n);return}let l=a.recipients,d=r.completed_at??r.fire_at;h(n,o`
257
252
  <div class="editor-head">
258
253
  <a href="#/sent" class="back">← Sent</a>
259
254
  </div>
260
255
  <div class="rec-head rec-head-page">
261
- <div class="watch-title"><h1>${a.subject||o`<em>untitled</em>`}</h1><span id="recPill">${Tn(a.phase)}</span></div>
262
- <div class="rec-meta">Sent ${W(d)} · ${l.toLocaleString()} recipients</div>
263
- ${Ns(a)}
256
+ <div class="watch-title"><h1>${r.subject||o`<em>untitled</em>`}</h1><span id="recPill">${In(r.phase)}</span></div>
257
+ <div class="rec-meta">Sent ${j(d)} · ${l.toLocaleString()} recipients</div>
258
+ ${Gs(r)}
264
259
  </div>
265
260
  <section class="card rec-post" aria-labelledby="recPostTitle">
266
261
  <h2 class="rec-part-title" id="recPostTitle">The post</h2>
267
- <div class="rec-web" id="recWeb">${za(a)}</div>
262
+ <div class="rec-web" id="recWeb">${Tl(r)}</div>
268
263
  </section>
269
264
  <section class="card rec-card" aria-labelledby="recDeliveryTitle">
270
265
  <h2 class="rec-part-title" id="recDeliveryTitle">Delivery</h2>
271
- <div id="recAlert">${Ya(a)}</div>
266
+ <div id="recAlert">${Ll(r)}</div>
272
267
  <p class="rec-tiles-cap muted">Delivery outcomes keep updating as receipts arrive; the audience at fire and the published post are fixed.</p>
273
- <div class="rec-tiles">${Ka(r)}</div>
274
- <p class="rec-recon muted">${Ga(r)}</p>
268
+ <div class="rec-tiles">${kl(a)}</div>
269
+ <p class="rec-recon muted">${_l(a)}</p>
275
270
  <div class="rec-actions">
276
271
  <button type="button" class="ghost" id="csvBtn">Export recipients (CSV)</button>
277
272
  </div>
@@ -279,7 +274,7 @@
279
274
  <div class="rec-people-head">
280
275
  <h3 class="rec-people-title">Recipients</h3>
281
276
  <div class="rec-views" role="group" aria-label="Which recipients to show">
282
- ${Mu.map((g,E)=>o`<button type="button" class="rec-view-btn" data-view="${g.v}" aria-pressed="${E===0?"true":"false"}">${g.label}</button>`)}
277
+ ${Lp.map((b,E)=>o`<button type="button" class="rec-view-btn" data-view="${b.v}" aria-pressed="${E===0?"true":"false"}">${b.label}</button>`)}
283
278
  </div>
284
279
  </div>
285
280
  <input class="rec-people-search" type="search" placeholder="Search email…" aria-label="Search recipients by email" autocomplete="off">
@@ -287,38 +282,38 @@
287
282
  <div id="recPager"></div>
288
283
  </div>
289
284
  <p class="rec-note muted">This is the record of what went out: the published post is the exact frozen copy readers received, and nothing here is editable.</p>
290
- </section>`);let u=c("#recWeb",n),f=a,S=()=>{h(u,za(f));let g=u.querySelector("#recOpen"),E=u.querySelector("#recCopy"),L=u.querySelector("#recListing"),$=Xa(f);g&&$&&(g.onclick=()=>window.open($,"_blank","noopener")),E&&$&&(E.onclick=()=>{wn(E,$)}),L&&(L.onclick=()=>f.email_only?v():p())},b=(g,E,L)=>G(g,E.email_only?"Updating\u2026":"Adding\u2026",async()=>{L.clearError();try{let $=await R(`/api/posts/${a.post_id}/settings`,{method:"PUT",json:E});L.close();let _=$.post.archive_live?$.post.archive_url:null;f={...f,email_only:$.post.email_only,links:{...f.links,archive:_}},S(),O($.post.email_only?"Removed from your archive":`Added to your archive at ${_?Sn(_):$.post.slug}`),Fe()}catch($){L.error(_n($))}}),p=()=>{let g=f.links.archive,E=f.web_link==="archive",L=pe(o`<h3 id="eoHead">Remove this post from your archive?</h3>
285
+ </section>`);let u=c("#recWeb",n),m=r,v=()=>{h(u,Tl(m));let b=u.querySelector("#recOpen"),E=u.querySelector("#recCopy"),C=u.querySelector("#recListing"),x=Hl(m);b&&x&&(b.onclick=()=>window.open(x,"_blank","noopener")),E&&x&&(E.onclick=()=>{Tn(E,x)}),C&&(C.onclick=()=>m.email_only?S():p())},f=(b,E,C)=>Z(b,E.email_only?"Updating\u2026":"Adding\u2026",async()=>{C.clearError();try{let x=await L(`/api/posts/${r.post_id}/settings`,{method:"PUT",json:E});C.close();let W=x.post.archive_live?x.post.archive_url:null;m={...m,email_only:x.post.email_only,links:{...m.links,archive:W}},v(),U(x.post.email_only?"Removed from your archive":`Added to your archive at ${W?Rn(W):x.post.slug}`),Fe()}catch(x){C.error(Mn(x))}}),p=()=>{let b=m.links.archive,E=m.web_link==="archive",C=fe(o`<h3 id="eoHead">Remove this post from your archive?</h3>
291
286
  ${E?o`<p class="hint">It comes off your home page and your public archive. Its emails link to its archive address, so that address keeps working for anyone who has them, and isn’t listed or indexed.</p>`:o`<p class="hint">It comes off your home page and your public archive, and its archive address stops working, including links people have shared. The link in the email keeps working for anyone who has it.</p>
292
- ${g?o`<div class="url-gone"><s>${Sn(g)}</s></div>`:null}
287
+ ${b?o`<div class="url-gone"><s>${Rn(b)}</s></div>`:null}
293
288
  <p class="pub-note">The address stays this post’s. Add it back and the same address, and the links people shared, work again.</p>`}
294
- <div class="actions"><button type="button" id="eoCancel">Cancel</button><button type="button" class="primary" id="eoGo">Remove from archive</button></div>`,s);c(".modal",L.el).setAttribute("aria-labelledby","eoHead"),c("#eoCancel",L.el).onclick=L.close;let $=c("#eoGo",L.el);$.onclick=()=>b($,{email_only:!0},L),$.focus()},v=async()=>{let g;try{g=await R(`/api/posts/${a.post_id}`,{signal:s})}catch(K){s.aborted||O(_n(K));return}let L={...Qe(g.post,g.subject_slug_held),emailOnly:!1},$=pe(o`<h3 id="addArchHead">Add this post to your archive?</h3>
289
+ <div class="actions"><button type="button" id="eoCancel">Cancel</button><button type="button" class="primary" id="eoGo">Remove from archive</button></div>`,s);c(".modal",C.el).setAttribute("aria-labelledby","eoHead"),c("#eoCancel",C.el).onclick=C.close;let x=c("#eoGo",C.el);x.onclick=()=>f(x,{email_only:!0},C),x.focus()},S=async()=>{let b;try{b=await L(`/api/posts/${r.post_id}`,{signal:s})}catch(oe){s.aborted||U(Mn(oe));return}let C={...et(b.post,b.subject_slug_held),emailOnly:!1},x=fe(o`<h3 id="addArchHead">Add this post to your archive?</h3>
295
290
  <p class="hint">It will be listed on your home page and in your public archive, where anyone visiting can find it. The link in the email keeps working, and forwards to it.</p>
296
291
  <div class="dialog-settings" id="addForm"></div>
297
- <div class="actions"><button type="button" id="addArchCancel">Cancel</button><button type="button" class="primary" id="addArchGo">Add to archive</button></div>`,s);c(".modal",$.el).setAttribute("aria-labelledby","addArchHead"),c("#addArchCancel",$.el).onclick=$.close,$t(c("#addForm",$.el),L,"add",{include:!1,fixedNote:"Its address since it was sent: links people shared work again."});let _=c("#addArchGo",$.el);_.onclick=()=>b(_,{email_only:!1},$),_.focus()};S();let x={view:"all",search:"",sort:"email",dir:"asc",offset:0,limit:50},M=c("#recRows",n),A=c("#recPager",n),H=0,T=!1,m=async g=>{let E=++H;g||(T=!0);try{let L=await R(`/api/sends/${e}/deliveries?${Nu(x)}`,{signal:s});if(E!==H)return;let $=L.page.total>0?Math.floor((L.page.total-1)/L.page.limit)*L.page.limit:0;if(!L.deliveries.length&&x.offset>$)return x.offset=$,m(g);T=!1,C(()=>{if(!L.deliveries.length){h(M,o`<p class="rec-people-empty muted">${Iu(x)}</p>`),h(A,o``);return}h(M,Bu(L.deliveries,x)),st(M,x,y),ot(A,x,L.page,y)})}catch(L){E===H&&(!g||T)&&(T=!1,oe(M,_n(L),y))}},y=()=>m(!1),C=g=>{let E=document.activeElement,L=E instanceof HTMLElement&&(M.contains(E)||A.contains(E)),$=L?E.dataset.sort:void 0,_=L?["pager-prev","pager-next"].find(D=>E.classList.contains(D)):void 0;g();let K=$?M.querySelector(`.th-sort[data-sort="${$}"]`):_?A.querySelector(`.${_}`):null;K&&!K.disabled&&K.focus()},U=I(".rec-view-btn",n);for(let g of U)g.onclick=()=>{let E=g.dataset.view;(E==="failures"||E==="delivered"||E==="all")&&(x.view=E),x.offset=0;for(let L of U)L.setAttribute("aria-pressed",String(L===g));y()};let J=n.querySelector(".rec-people-search");if(J){let g;J.oninput=()=>{clearTimeout(g),g=setTimeout(()=>{x.search=J.value,x.offset=0,y()},250)}}y();let z=c("#csvBtn");z.onclick=()=>G(z,"Exporting\u2026",async()=>{try{let g=await Qn(a.links.deliveries_csv);kt(g.text,g.filename??"deliveries.csv","text/csv")}catch(g){O(g instanceof te&&g.status===404?"This send no longer exists, so there are no deliveries to export.":_n(g))}});let q=r;mn(t,{update(g){if(g.status==="sending"){i();return}h(c("#recPill",n),Tn(g.phase)),h(c("#recAlert",n),Ya(g)),(g.email_only!==f.email_only||g.links.archive!==f.links.archive||g.links.unlisted!==f.links.unlisted)&&(f=g,S());let E=Du(g);Pu(q,E)||(q=E,h(c(".rec-tiles",n),Ka(E)),c(".rec-recon",n).textContent=Ga(E),m(!0))},removed:i,stale:i},s)}function Xa(e){return e.email_only&&e.web_link==="unlisted"?e.links.unlisted:e.links.archive??e.links.unlisted}function za(e){let t=Xa(e),n=t?Sn(t):null,s=e.web_link==="archive",i=e.email_only?s?"Its emails link here. Anyone with the link can open it; nothing lists or indexes it.":"Anyone with the link can open it. Nothing lists or indexes it.":s?"Its emails link here.":"The link in the email forwards here.",a=t&&n?o`<p class="rec-link-label">Link</p><div class="rec-link"><code title="${n}">${n}</code><button type="button" class="copy-btn" id="recCopy" data-copy-word="Copy" aria-label="Copy link">${Te(!1,"Copy")}</button><button type="button" class="rec-open" id="recOpen">Open&nbsp;↗</button></div><p class="rec-link-note muted">${i}</p>`:null,r=e.email_only?o`<div class="rec-arch-what"><strong>${N("mail")}Email only</strong><span class="rec-arch-note">Not on your home page or in your public archive.</span></div><button type="button" class="secondary" id="recListing">Add to archive…</button>`:o`<div class="rec-arch-what"><strong>${N("link")}In your archive</strong><span class="rec-arch-note">Listed on your home page and in your public archive.</span></div><button type="button" class="secondary" id="recListing">Remove from archive…</button>`;return o`${a}<div class="rec-arch">${r}</div>`}function Ya(e){let t=he(e,"no_receipts");return t?o`<div class="health amber" role="status"><span class="health-dot">⚠️</span><div>${t.message}</div></div>`:o``}function Du(e){let t=e.counts;return{recipients:e.audience.count,delivered:t.delivered,bounced:t.bounced,complained:t.complained,unsent:t.unsent,skipped:t.skipped,accepted:t.accepted,pending:t.pending,dispatched:t.dispatched}}function Uu(e,t){h(t,o`
292
+ <div class="actions"><button type="button" id="addArchCancel">Cancel</button><button type="button" class="primary" id="addArchGo">Add to archive</button></div>`,s);c(".modal",x.el).setAttribute("aria-labelledby","addArchHead"),c("#addArchCancel",x.el).onclick=x.close,_t(c("#addForm",x.el),C,"add",{include:!1,fixedNote:"Its address since it was sent: links people shared work again."});let W=c("#addArchGo",x.el);W.onclick=()=>f(W,{email_only:!1},x),W.focus()};v();let $={view:"all",search:"",sort:"email",dir:"asc",offset:0,limit:50},M=c("#recRows",n),P=c("#recPager",n),A=0,H=!1,y=async b=>{let E=++A;b||(H=!0);try{let C=await L(`/api/sends/${e}/deliveries?${Cp($)}`,{signal:s});if(E!==A)return;let x=C.page.total>0?Math.floor((C.page.total-1)/C.page.limit)*C.page.limit:0;if(!C.deliveries.length&&$.offset>x)return $.offset=x,y(b);H=!1,T(()=>{if(!C.deliveries.length){h(M,o`<p class="rec-people-empty muted">${Rp($)}</p>`),h(P,o``);return}h(M,Ap(C.deliveries,$)),it(M,$,w),rt(P,$,C.page,w)})}catch(C){E===A&&(!b||H)&&(H=!1,re(M,Mn(C),w))}},w=()=>y(!1),T=b=>{let E=document.activeElement,C=E instanceof HTMLElement&&(M.contains(E)||P.contains(E)),x=C?E.dataset.sort:void 0,W=C?["pager-prev","pager-next"].find(k=>E.classList.contains(k)):void 0;b();let oe=x?M.querySelector(`.th-sort[data-sort="${x}"]`):W?P.querySelector(`.${W}`):null;oe&&!oe.disabled&&oe.focus()},D=N(".rec-view-btn",n);for(let b of D)b.onclick=()=>{let E=b.dataset.view;(E==="failures"||E==="delivered"||E==="all")&&($.view=E),$.offset=0;for(let C of D)C.setAttribute("aria-pressed",String(C===b));w()};let R=n.querySelector(".rec-people-search");if(R){let b;R.oninput=()=>{clearTimeout(b),b=setTimeout(()=>{$.search=R.value,$.offset=0,w()},250)}}w();let F=c("#csvBtn");F.onclick=()=>Z(F,"Exporting\u2026",async()=>{try{let b=await as(r.links.deliveries_csv);Rt(b.text,b.filename??"deliveries.csv","text/csv")}catch(b){U(b instanceof te&&b.status===404?"This send no longer exists, so there are no deliveries to export.":Mn(b))}});let K=a;gn(t,{update(b){if(b.status==="sending"){i();return}h(c("#recPill",n),In(b.phase)),h(c("#recAlert",n),Ll(b)),(b.email_only!==m.email_only||b.links.archive!==m.links.archive||b.links.unlisted!==m.links.unlisted)&&(m=b,v());let E=Pp(b);Tp(K,E)||(K=E,h(c(".rec-tiles",n),kl(E)),c(".rec-recon",n).textContent=_l(E),y(!0))},removed:i,stale:i},s)}function Hl(e){return e.email_only&&e.web_link==="unlisted"?e.links.unlisted:e.links.archive??e.links.unlisted}function Tl(e){let t=Hl(e),n=t?Rn(t):null,s=e.web_link==="archive",i=e.email_only?s?"Its emails link here. Anyone with the link can open it; nothing lists or indexes it.":"Anyone with the link can open it. Nothing lists or indexes it.":s?"Its emails link here.":"The link in the email forwards here.",r=t&&n?o`<p class="rec-link-label">Link</p><div class="rec-link"><code title="${n}">${n}</code><button type="button" class="copy-btn" id="recCopy" data-copy-word="Copy" aria-label="Copy link">${Te(!1,"Copy")}</button><button type="button" class="rec-open" id="recOpen">Open&nbsp;↗</button></div><p class="rec-link-note muted">${i}</p>`:null,a=e.email_only?o`<div class="rec-arch-what"><strong>${O("mail")}Email only</strong><span class="rec-arch-note">Not on your home page or in your public archive.</span></div><button type="button" class="secondary" id="recListing">Add to archive…</button>`:o`<div class="rec-arch-what"><strong>${O("link")}In your archive</strong><span class="rec-arch-note">Listed on your home page and in your public archive.</span></div><button type="button" class="secondary" id="recListing">Remove from archive…</button>`;return o`${r}<div class="rec-arch">${a}</div>`}function Ll(e){let t=he(e,"no_receipts");return t?o`<div class="health amber" role="status"><span class="health-dot">⚠️</span><div>${t.message}</div></div>`:o``}function Pp(e){let t=e.counts;return{recipients:e.audience.count,delivered:t.delivered,bounced:t.bounced,complained:t.complained,unsent:t.unsent,skipped:t.skipped,accepted:t.accepted,pending:t.pending,dispatched:t.dispatched}}function Mp(e,t){h(t,o`
298
293
  <div class="editor-head">
299
294
  <a href="#/sent" class="back">← Sent</a>
300
295
  </div>
301
296
  <div class="card rec-card">
302
297
  <div class="rec-head">
303
- <div class="watch-title"><h1>${e.subject||o`<em>untitled</em>`}</h1><span id="recPill">${Tn(e.phase)}</span></div>
304
- <div class="rec-meta">Canceled ${W(e.completed_at)} · was scheduled for ${W(e.fire_at)}</div>
305
- ${Ns(e)}
298
+ <div class="watch-title"><h1>${e.subject||o`<em>untitled</em>`}</h1><span id="recPill">${In(e.phase)}</span></div>
299
+ <div class="rec-meta">Canceled ${j(e.completed_at)} · was scheduled for ${j(e.fire_at)}</div>
300
+ ${Gs(e)}
306
301
  </div>
307
302
  <p class="rec-note muted">This send was canceled before it fired, so no one was mailed.</p>
308
- </div>`)}function Jo(e){let t=document.getElementById(e);if(!t)throw new Error(`the admin page has no #${e}`);return t}var Bs=(()=>{let e=Jo("savebar"),t=e.querySelector(".savebar-msg"),n=Jo("savebarSave"),s=Jo("savebarDiscard"),i=0,a=u=>{t&&h(t,o`<span class="savebar-dot"></span><span>${u}</span>`)},r=()=>{e.hidden=!1,e.offsetHeight,e.classList.add("show")};function l(){i++,e.classList.remove("show","is-error"),e.hidden=!0,n.onclick=null,s.onclick=null,document.body.classList.remove("has-savebar")}function d({onSave:u,onDiscard:f,saveLabel:S="Save changes",discardLabel:b="Discard"},p){if(p.aborted)return{setDirty(){},showError(){}};let v=++i;p.addEventListener("abort",()=>{i===v&&l()},{once:!0}),n.textContent=S,s.textContent=b,e.classList.remove("show","is-error"),a("You have unsaved changes."),e.hidden=!0,document.body.classList.add("has-savebar"),n.onclick=()=>G(n,"Saving\u2026",()=>Promise.resolve(u())),s.onclick=()=>f();let x=()=>i===v;return{setDirty(M){x()&&(e.classList.remove("is-error"),M?(a("You have unsaved changes."),r()):e.classList.remove("show"))},showError(M){x()&&(e.classList.add("is-error"),a(M),r())}}}return{attach:d}})();var at=F,Ln=o` hidden`;function ye(e,t){return o`<span class="set-chip ${e}">${N(e)}${t}</span>`}function we(e,t,n=null){return o`<div class="set-sec-head"><h2 class="set-sec-title">${e}</h2>${t}${n}<span class="set-rule"></span></div>`}function Rn(e,t){return(String(e||t).trim()[0]||"K").toUpperCase()}function el(e){let{state:t,fromName:n}=e;return o`
303
+ </div>`)}function hi(e){let t=document.getElementById(e);if(!t)throw new Error(`the admin page has no #${e}`);return t}var zs=(()=>{let e=hi("savebar"),t=e.querySelector(".savebar-msg"),n=hi("savebarSave"),s=hi("savebarDiscard"),i=0,r=u=>{t&&h(t,o`<span class="savebar-dot"></span><span>${u}</span>`)},a=()=>{e.hidden=!1,e.offsetHeight,e.classList.add("show")};function l(){i++,e.classList.remove("show","is-error"),e.hidden=!0,n.onclick=null,s.onclick=null,document.body.classList.remove("has-savebar")}function d({onSave:u,onDiscard:m,saveLabel:v="Save changes",discardLabel:f="Discard"},p){if(p.aborted)return{setDirty(){},showError(){}};let S=++i;p.addEventListener("abort",()=>{i===S&&l()},{once:!0}),n.textContent=v,s.textContent=f,e.classList.remove("show","is-error"),r("You have unsaved changes."),e.hidden=!0,document.body.classList.add("has-savebar"),n.onclick=()=>Z(n,"Saving\u2026",()=>Promise.resolve(u())),s.onclick=()=>m();let $=()=>i===S;return{setDirty(M){$()&&(e.classList.remove("is-error"),M?(r("You have unsaved changes."),a()):e.classList.remove("show"))},showError(M){$()&&(e.classList.add("is-error"),r(M),a())}}}return{attach:d}})();var ut=V,Nn=o` hidden`;function we(e,t){return o`<span class="set-chip ${e}">${O(e)}${t}</span>`}function Se(e,t,n=null){return o`<div class="set-sec-head"><h2 class="set-sec-title">${e}</h2>${t}${n}<span class="set-rule"></span></div>`}function On(e,t){return(String(e||t).trim()[0]||"K").toUpperCase()}function Pl(e){let{state:t,fromName:n}=e;return o`
309
304
  <section class="set-sec">
310
- ${we("Confirmation email",ye("editable","Editable"))}
305
+ ${Se("Confirmation email",we("editable","Editable"))}
311
306
  <p class="set-lede">The email that asks a new subscriber to confirm. Edit the wording as you see fit. Kestrel adds the confirmation link.</p>
312
307
  <div class="set-preview">
313
308
  <div class="set-preview-bar set-ce-bar">
314
309
  <div class="set-ce-modetog" role="group" aria-label="Confirmation email view">
315
- <button type="button" class="set-ce-modebtn" id="ceTabPreview" aria-pressed="true">${N("preview")}Preview</button>
316
- <button type="button" class="set-ce-modebtn" id="ceTabEdit" aria-pressed="false">${N("editable")}Edit</button>
310
+ <button type="button" class="set-ce-modebtn" id="ceTabPreview" aria-pressed="true">${O("preview")}Preview</button>
311
+ <button type="button" class="set-ce-modebtn" id="ceTabEdit" aria-pressed="false">${O("editable")}Edit</button>
317
312
  </div>
318
313
  </div>
319
314
  <div id="cePreviewBody">
320
315
  <div class="set-inbox">
321
- <div class="set-inbox-avatar" id="cePvAvatar">${Rn(t.name,n)}</div>
316
+ <div class="set-inbox-avatar" id="cePvAvatar">${On(t.name,n)}</div>
322
317
  <div class="set-inbox-body">
323
318
  <div class="set-inbox-top"><span class="set-inbox-from" id="cePvFrom">${t.name||n}</span><span class="set-inbox-time">now</span></div>
324
319
  <div class="set-inbox-subj" id="cePvSubject"></div>
@@ -367,69 +362,75 @@
367
362
  </div>
368
363
  </div>
369
364
  </div>
370
- </section>`}function tl(e,t){let{state:n}=t,s=t.data.settings.confirmation_email_default,i={subject:c("#ceSubject",e),message:c("#ceMessage",e),button:c("#ceButton",e),footer:c("#ceFooter",e)},a={avatar:c("#cePvAvatar",e),from:c("#cePvFrom",e),subject:c("#cePvSubject",e),body:c("#cePvBody",e),button:c("#cePvButton",e),foot:c("#cePvFoot",e),mast:c("#cePvMast",e),mastLogo:c("#cePvMastLogo",e),mastName:c("#cePvMastName",e),mastTag:c("#cePvMastTag",e)},r=()=>{let p=n.confirmation;a.avatar.textContent=Rn(n.name,t.fromName),a.from.textContent=n.name||t.fromName,a.subject.textContent=p.subject.trim()||s.subject||"",a.body.textContent=p.body.trim()||s.body||"",a.button.textContent=p.button_label.trim()||s.button_label||"Confirm",a.foot.textContent=p.reassurance,a.foot.hidden=!p.reassurance.trim();let v=n.name||t.fromDisplay,x=!!n.logoUrl,M=x||!!v;a.mast.hidden=!M,M&&(a.mastLogo.hidden=!x,x&&h(a.mastLogo,o`<img src="${n.logoUrl}" alt="">`),a.mastName.textContent=v,a.mastName.hidden=!v,a.mastTag.textContent=n.tagline,a.mastTag.hidden=!n.tagline)},l=()=>{n.confirmation.subject=i.subject.value,n.confirmation.body=i.message.value,n.confirmation.button_label=i.button.value,n.confirmation.reassurance=i.footer.value,t.changed()};for(let p of Object.values(i))p.addEventListener("input",l);let d=c("#ceEditBody",e),u=c("#cePreviewBody",e),f=c("#ceTabEdit",e),S=c("#ceTabPreview",e),b=p=>{d.hidden=!p,u.hidden=p,f.setAttribute("aria-pressed",String(p)),S.setAttribute("aria-pressed",String(!p)),p&&i.subject.focus()};return S.onclick=()=>b(!1),f.onclick=()=>b(!0),c("#ceToPreview",e).onclick=()=>b(!1),c("#ceReset",e).onclick=()=>{i.subject.value=s.subject||"",i.message.value=s.body||"",i.button.value=s.button_label||"",i.footer.value=s.reassurance||"",l()},r(),{repaint:r,reset(){i.subject.value=n.confirmation.subject,i.message.value=n.confirmation.body,i.button.value=n.confirmation.button_label,i.footer.value=n.confirmation.reassurance,r()}}}var Fu={none:"No email provider connected",fake:"Fake (dev, dead-end)",ses:"Amazon SES"};function Os(e){return Fu[e]||e}function qu(e){return e.provider==="none"?o`${Os(e.provider)}. ${Ae("set-link")} to start sending.`:o`${Os(e.provider)}${e.simulation?o`<span class="set-pill">Simulating ${ju[e.simulation.profile]}${e.simulation.faults==="none"?", no failures":""}</span>`:null}`}var ju={generic:"a generic provider",ses:"Amazon SES"},Wu="#/docs/ses/9-receive-replies-at-your-from-address";function Vu(e){let t=String(e||"").match(/<([^>]+)>/);return t?.[1]?t[1]:String(e||"")}function nl(e){let t=e.data.deployment,{fromName:n}=e;return o`
365
+ </section>`}function Ml(e,t){let{state:n}=t,s=t.data.settings.confirmation_email_default,i={subject:c("#ceSubject",e),message:c("#ceMessage",e),button:c("#ceButton",e),footer:c("#ceFooter",e)},r={avatar:c("#cePvAvatar",e),from:c("#cePvFrom",e),subject:c("#cePvSubject",e),body:c("#cePvBody",e),button:c("#cePvButton",e),foot:c("#cePvFoot",e),mast:c("#cePvMast",e),mastLogo:c("#cePvMastLogo",e),mastName:c("#cePvMastName",e),mastTag:c("#cePvMastTag",e)},a=()=>{let p=n.confirmation;r.avatar.textContent=On(n.name,t.fromName),r.from.textContent=n.name||t.fromName,r.subject.textContent=p.subject.trim()||s.subject||"",r.body.textContent=p.body.trim()||s.body||"",r.button.textContent=p.button_label.trim()||s.button_label||"Confirm",r.foot.textContent=p.reassurance,r.foot.hidden=!p.reassurance.trim();let S=n.name||t.fromDisplay,$=!!n.logoUrl,M=$||!!S;r.mast.hidden=!M,M&&(r.mastLogo.hidden=!$,$&&h(r.mastLogo,o`<img src="${n.logoUrl}" alt="">`),r.mastName.textContent=S,r.mastName.hidden=!S,r.mastTag.textContent=n.tagline,r.mastTag.hidden=!n.tagline)},l=()=>{n.confirmation.subject=i.subject.value,n.confirmation.body=i.message.value,n.confirmation.button_label=i.button.value,n.confirmation.reassurance=i.footer.value,t.changed()};for(let p of Object.values(i))p.addEventListener("input",l);let d=c("#ceEditBody",e),u=c("#cePreviewBody",e),m=c("#ceTabEdit",e),v=c("#ceTabPreview",e),f=p=>{d.hidden=!p,u.hidden=p,m.setAttribute("aria-pressed",String(p)),v.setAttribute("aria-pressed",String(!p)),p&&i.subject.focus()};return v.onclick=()=>f(!1),m.onclick=()=>f(!0),c("#ceToPreview",e).onclick=()=>f(!1),c("#ceReset",e).onclick=()=>{i.subject.value=s.subject||"",i.message.value=s.body||"",i.button.value=s.button_label||"",i.footer.value=s.reassurance||"",l()},a(),{repaint:a,reset(){i.subject.value=n.confirmation.subject,i.message.value=n.confirmation.body,i.button.value=n.confirmation.button_label,i.footer.value=n.confirmation.reassurance,a()}}}var Ip={none:"No email provider connected",fake:"Fake (dev, dead-end)",ses:"Amazon SES"};function Ys(e){return Ip[e]||e}function Np(e,t){if(e.provider==="none")return o`${Ys(e.provider)}. ${Ae("set-link")} to start sending.`;let n=e.simulation?o`<span class="set-pill">Simulating ${Op[e.simulation.profile]}${e.simulation.faults==="none"?", no failures":""}</span>`:null,s=t?ba(t,j):null;if(t&&t.unknown_reason!=="stand_in"){let i=[s?.pill,n].filter(r=>!!r);return o`${la(t,i.length?o`${i.map(r=>o` ${r}`)}`:null)}${s?.line??null}`}return o`<span>${Ys(e.provider)}${s?.pill?o` ${s.pill}`:null}${n}</span>${s?.line??null}`}var Op={generic:"a generic provider",ses:"Amazon SES"},Dp="#/docs/ses/8-receive-replies-at-your-from-address";function Bp(e){let t=String(e||"").match(/<([^>]+)>/);return t?.[1]?t[1]:String(e||"")}function Il(e){let t=e.data.deployment,{fromName:n}=e,s=e.provider,i=s?da(s):null;return o`
371
366
  <section class="set-sec">
372
- ${we("Email sender",ye("readonly","Read-only \xB7 set at deploy"))}
367
+ ${Se("Email sender",we("readonly","Read-only \xB7 set at deploy"))}
373
368
  <div class="set-card sunken">
374
- <div class="set-ro-note">${N("readonly")}<span>The sender is set at deploy in <code>wrangler.jsonc</code>, with the AWS keys stored as secrets, so it can’t be edited here. Change it in the <a class="set-link" href="#/docs/self-hosting">setup guide</a>, then redeploy. Credentials are never shown.</span></div>
369
+ <div class="set-ro-note">${O("readonly")}<span>The sender is set at deploy in <code>wrangler.jsonc</code>, with the AWS keys stored as secrets, so it can’t be edited here. Change it in the <a class="set-link" href="#/docs/self-hosting">setup guide</a>, then redeploy. Credentials are never shown.</span></div>
375
370
  <div class="set-preview-bar" style="background:transparent">
376
371
  <span class="set-preview-lbl">Inbox preview</span>
377
372
  <span class="set-preview-dot">How readers see the sender</span>
378
373
  </div>
379
374
  <div class="set-inbox">
380
- <div class="set-inbox-avatar">${Rn(n,n)}</div>
375
+ <div class="set-inbox-avatar">${On(n,n)}</div>
381
376
  <div class="set-inbox-body">
382
377
  <div class="set-inbox-top"><span class="set-inbox-from">${n}</span><span class="set-inbox-time">9:02 AM</span></div>
383
378
  <div class="set-inbox-subj">Your latest post: a sample subject line</div>
384
379
  <div class="set-inbox-snip">The opening lines of your post show here as the inbox preview…</div>
385
- <div class="set-inbox-addr">${Vu(t.from_address)}</div>
380
+ <div class="set-inbox-addr">${Bp(t.from_address)}</div>
386
381
  </div>
387
382
  </div>
388
383
  <div class="set-kv" style="border-top:1px solid var(--line)">
389
- <div class="set-kv-k">From address</div><div class="set-kv-v set-kv-stack"><span class="mono">${t.from_address}</span><span class="muted" id="replyNote">Readers’ replies go to this address. <a class="set-link" href="${Wu}">Forward it to your inbox</a>.</span></div>
384
+ <div class="set-kv-k">From address</div><div class="set-kv-v set-kv-stack"><span class="mono">${t.from_address}</span><span class="muted" id="replyNote">Readers’ replies go to this address. <a class="set-link" href="${Dp}">Forward it to your inbox</a>.</span></div>
390
385
  <div class="set-kv-k">Sending domain</div><div class="set-kv-v"><span class="mono">${t.sending_domain}</span></div>
391
- <div class="set-kv-k">Email provider</div><div class="set-kv-v" id="providerValue">${qu(t)}</div>
386
+ <div class="set-kv-k">Email provider</div><div class="set-kv-v set-kv-stack" id="providerValue">${Np(t,s)}${s?.warnings.map(r=>o`<span class="${xn(r)?"set-error":"set-warn"}">${Ps(r)}</span>`)}</div>
387
+ ${i?o`<div class="set-kv-k">Send rate</div><div class="set-kv-v" id="sendRate">${i}</div>`:null}
392
388
  </div>
393
389
  </div>
394
- </section>`}function sl(e){let t=e.data.deployment,n=`${t.archive_origin||""}${t.archive_base_path||""}`,s=t.archive_origin===t.app_origin;return o`
390
+ </section>`}function Nl(e){let t=e.data.deployment,n=`${t.archive_origin||""}${t.archive_base_path||""}`,s=t.archive_origin===t.app_origin;return o`
395
391
  <section class="set-sec">
396
- ${we("Instance",ye("readonly","Read-only \xB7 set at deploy"))}
392
+ ${Se("Instance",we("readonly","Read-only \xB7 set at deploy"))}
397
393
  <div class="set-card sunken">
398
- <div class="set-ro-note">${N("info")}<span>Deploy-time infrastructure, shown for reference. These live in your Worker config and never pass through the API. See the <a class="set-link" href="#/docs/configuration">setup guide</a> to change them.</span></div>
394
+ <div class="set-ro-note">${O("info")}<span>Deploy-time infrastructure, shown for reference. These live in your Worker config and never pass through the API. See the <a class="set-link" href="#/docs/configuration">setup guide</a> to change them.</span></div>
399
395
  <div class="set-kv">
400
396
  <div class="set-kv-k">App origin</div><div class="set-kv-v"><span class="mono">${t.app_origin}</span></div>
401
397
  <div class="set-kv-k">Archive URL base</div><div class="set-kv-v"><span class="mono">${n}</span>${s?o`<span class="set-pill">default: app origin</span>`:null}</div>
402
398
  <div class="set-kv-k">Image URL base</div><div class="set-kv-v"><span class="mono">${t.media_public_base}</span></div>
403
399
  <div class="set-kv-k">Auth mode</div><div class="set-kv-v">${t.auth_mode==="access"?"Cloudflare Access":"Local dev token"}</div>
404
- <div class="set-kv-k">Cloudflare Access</div><div class="set-kv-v">${t.access_configured?o`<span class="set-pill ok">${N("check")}Configured</span>`:o`<span class="set-pill">Not configured</span>`}</div>
405
- <div class="set-kv-k">Minimum lead</div><div class="set-kv-v">${It(t.min_lead_ms)}${t.min_lead_ms===es?o`<span class="set-pill">default</span>`:null}</div>
400
+ <div class="set-kv-k">Cloudflare Access</div><div class="set-kv-v">${t.access_configured?o`<span class="set-pill ok">${O("check")}Configured</span>`:o`<span class="set-pill">Not configured</span>`}</div>
401
+ <div class="set-kv-k">Minimum lead</div><div class="set-kv-v">${Dt(t.min_lead_ms)}${t.min_lead_ms===cs?o`<span class="set-pill">default</span>`:null}</div>
406
402
  </div>
407
403
  </div>
408
- </section>`}function Ku(e){return e instanceof te&&e.status===409&&e.data?.error==="remake_required"?e.data:null}var Gu="Not saved: the change needed your confirmation";async function _t(e,t,n){let s=null;for(;;)try{return await e(s)}catch(i){let a=Ku(i);if(!a)throw i;let r=a.sends||[];if(!await zu(r,t,n))return n.aborted&&O(Gu),null;s=r.map(d=>d.id)}}function zu(e,t,n){let s=e.length,i=s===1,a=`${s} scheduled email${i?"":"s"}`;return new Promise(r=>{let l=pe(o`<h3>Apply this change to ${a}?</h3>
404
+ </section>`}function Zs(e){return o`
405
+ <div class="set-chips" id="${e.chips}"></div>
406
+ <div class="set-recip-add">
407
+ <input type="email" id="${e.input}" placeholder="you@example.com" autocomplete="off">
408
+ <button type="button" id="${e.add}">Add inbox</button>
409
+ </div>`}function Js(e,t,n){let s=c(`#${n.ids.chips}`,e),i=c(`#${n.ids.input}`,e),r=()=>{let l=n.list();if(!l.length){h(s,o`<span class="set-recip-empty">${n.empty}</span>`);return}h(s,o`${l.map((d,u)=>o`<span class="set-recip-chip">${d}<button type="button" data-rm="${u}" aria-label="Remove ${d}">${O("x")}</button></span>`)}`)};s.addEventListener("click",l=>{let d=l.target instanceof Element?l.target.closest("[data-rm]"):null;d&&(n.list().splice(Number(d.dataset.rm),1),r(),t.changed())});let a=()=>{let l=wt(i.value);if(!l)return;let d=n.list(),u=St(l)?d.includes(l)?"That inbox is already in the list.":n.max&&d.length>=n.max.count?n.max.full:"":"That doesn\u2019t look like an email address.";if(u){qe(i,u),i.focus();return}d.push(l),i.value="",r(),t.changed()};return c(`#${n.ids.add}`,e).onclick=a,i.addEventListener("keydown",l=>{l.key==="Enter"&&(l.preventDefault(),a())}),r(),{reset:r}}function Up(e){return e instanceof te&&e.status===409&&e.data?.error==="remake_required"?e.data:null}var Fp="Not saved: the change needed your confirmation";async function Ct(e,t,n){let s=null;for(;;)try{return await e(s)}catch(i){let r=Up(i);if(!r)throw i;let a=r.sends||[];if(!await qp(a,t,n))return n.aborted&&U(Fp),null;s=a.map(d=>d.id)}}function qp(e,t,n){let s=e.length,i=s===1,r=`${s} scheduled email${i?"":"s"}`;return new Promise(a=>{let l=fe(o`<h3>Apply this change to ${r}?</h3>
409
410
  <p class="hint">${t.lead(s)} ${t.gerund} applies the change to ${i?"its email":"their emails"} too.</p>
410
- <ul class="remake-list">${e.map(p=>o`<li><span>${p.subject||o`<em>untitled</em>`}</span><span>sends ${W(p.fire_at)}</span></li>`)}</ul>
411
+ <ul class="remake-list">${e.map(p=>o`<li><span>${p.subject||o`<em>untitled</em>`}</span><span>sends ${j(p.fire_at)}</span></li>`)}</ul>
411
412
  <dl class="remake-facts">
412
413
  <div><dt>Changes</dt><dd>the look of ${i?"its email":"their emails"}</dd></div>
413
414
  <div><dt>Stays</dt><dd>${i?"its content and fire time":"their content and fire times"}</dd></div>
414
415
  <div><dt>Next</dt><dd>send yourself a fresh test${i?"":" of each"}</dd></div>
415
416
  </dl>
416
417
  <p class="hint">To leave scheduled emails as they are while future posts change, you’d need a second template, which Kestrel doesn’t offer yet.</p>
417
- <div class="actions"><button type="button" id="rmCancel">Cancel</button><button type="button" class="primary" id="rmGo">${t.action} and apply</button></div>`,n);if(!l.el.isConnected){r(!1);return}let d=!1,u=p=>{d||(d=!0,r(p))},f=l.el.querySelector("#rmCancel"),S=l.el.querySelector("#rmGo");f&&(f.onclick=()=>{l.close(),u(!1)}),S&&(S.onclick=()=>{l.close(),u(!0)});let b=new MutationObserver(()=>{l.el.isConnected||(b.disconnect(),u(!1))});b.observe(document.body,{childList:!0}),S?.focus()})}var ol={action:"Save",gerund:"Saving",lead:e=>`This template is used by ${e} post${e===1?" that\u2019s":"s that are"} already scheduled.`},Cn=(e,t)=>({action:e,gerund:t,lead:n=>`Your name, tagline, address, and logo ride inside every email, including ${n} post${n===1?" that\u2019s":"s that are"} already scheduled.`});function Ds(e){let t=e?.sends||[];if(!t.length)return o`<span class="set-chip">${N("info")}No posts scheduled</span>`;let n=t.length;return o`<span class="set-chip inuse"><span class="set-chip-dot"></span>In use by ${n} scheduled post${n===1?"":"s"}</span>`}function Yu(e,t=Date.now()){let n=e?.retry_after;if(!e||!n||t>=n)return"";let s=Math.max(1,e.sends.filter(i=>i.fire_at<=n).length);return s===1?`A scheduled post sends at ${W(n)}. You can save once it has sent.`:`${s} scheduled posts send by ${W(n)}. You can save once they have sent.`}function Xt(e){let t=Yu(e);return t?o`<span data-remake-wait> ${t}</span>`:null}function Us(e,t,n){let s=t?.retry_after;s&&ft(s,()=>{for(let i of e.querySelectorAll("[data-remake-wait]"))i.remove()},n)}function en(e,t){let n=(t||[]).length;return n?`${e} and applied to ${n} scheduled email${n===1?"":"s"}. Send yourself a test of each.`:e}var il=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");function rl(e,t){return e?`<img class="logo" src="${il(e)}" alt="${il(t)}" width="44" height="44" />`:""}var al="You\u2019ve added a mailing address in Settings, but this template doesn\u2019t include the {{ .Publication.Address }} field. If you send promotional email, add it to the footer. If you\u2019ve written your address into the template yourself, or don\u2019t need to provide one, you can ignore this or remove the address in Settings.";function Zu(e,t){let n=Math.min(e,t);return{x:Math.floor((e-n)/2),y:Math.floor((t-n)/2),side:n}}var Qo=class extends Error{constructor(){super("Couldn\u2019t read that image. Pick a PNG, JPEG, WebP, or GIF.")}};async function ll(e,t){let n=await createImageBitmap(e,{imageOrientation:"from-image"}).catch(()=>{throw new Qo});try{let{x:s,y:i,side:a}=Zu(n.width,n.height),r=document.createElement("canvas");r.width=t,r.height=t;let l=r.getContext("2d");if(!l)throw new Error("This browser can\u2019t prepare the image.");return l.imageSmoothingQuality="high",l.drawImage(n,s,i,a,a,0,0,t,t),{png:await new Promise((u,f)=>r.toBlob(S=>S?u(S):f(new Error("This browser can\u2019t prepare the image.")),"image/png")),width:n.width,height:n.height}}finally{n.close()}}function Ju(e){if(!(e.identity_fields||[]).length)return o`Your email template doesn’t show any of these.`;let t="Shown in every email.",n=e.sends.length;if(!n)return o`${t}`;let s=`Saving a change updates ${n} scheduled email${n===1?"":"s"} too; you\u2019ll confirm first.`;return o`${t} ${s}${Xt(e)}`}var Qu="#/docs/name-your-publication/when-to-provide-a-mailing-address";function An(){return o`<a class="set-link" href="${Qu}" target="_blank" rel="noopener">When to provide a mailing address <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a>`}var Xo=256;function cl(e){let{state:t,fromDisplay:n,fromName:s}=e,i=!!t.address;return o`
418
+ <div class="actions"><button type="button" id="rmCancel">Cancel</button><button type="button" class="primary" id="rmGo">${t.action} and apply</button></div>`,n);if(!l.el.isConnected){a(!1);return}let d=!1,u=p=>{d||(d=!0,a(p))},m=l.el.querySelector("#rmCancel"),v=l.el.querySelector("#rmGo");m&&(m.onclick=()=>{l.close(),u(!1)}),v&&(v.onclick=()=>{l.close(),u(!0)});let f=new MutationObserver(()=>{l.el.isConnected||(f.disconnect(),u(!1))});f.observe(document.body,{childList:!0}),v?.focus()})}var Ol={action:"Save",gerund:"Saving",lead:e=>`This template is used by ${e} post${e===1?" that\u2019s":"s that are"} already scheduled.`},Dn=(e,t)=>({action:e,gerund:t,lead:n=>`Your name, tagline, address, and logo ride inside every email, including ${n} post${n===1?" that\u2019s":"s that are"} already scheduled.`});function Qs(e){let t=e?.sends||[];if(!t.length)return o`<span class="set-chip">${O("info")}No posts scheduled</span>`;let n=t.length;return o`<span class="set-chip inuse"><span class="set-chip-dot"></span>In use by ${n} scheduled post${n===1?"":"s"}</span>`}function jp(e,t=Date.now()){let n=e?.retry_after;if(!e||!n||t>=n)return"";let s=Math.max(1,e.sends.filter(i=>i.fire_at<=n).length);return s===1?`A scheduled post sends at ${j(n)}. You can save once it has sent.`:`${s} scheduled posts send by ${j(n)}. You can save once they have sent.`}function nn(e){let t=jp(e);return t?o`<span data-remake-wait> ${t}</span>`:null}function Xs(e,t,n){let s=t?.retry_after;s&&gt(s,()=>{for(let i of e.querySelectorAll("[data-remake-wait]"))i.remove()},n)}function sn(e,t){let n=(t||[]).length;return n?`${e} and applied to ${n} scheduled email${n===1?"":"s"}. Send yourself a test of each.`:e}var Dl=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");function Bl(e,t){return e?`<img class="logo" src="${Dl(e)}" alt="${Dl(t)}" width="44" height="44" />`:""}var Ul="You\u2019ve added a mailing address in Settings, but this template doesn\u2019t include the {{ .Publication.Address }} field. If you send promotional email, add it to the footer. If you\u2019ve written your address into the template yourself, or don\u2019t need to provide one, you can ignore this or remove the address in Settings.";function Fl(e,t){return e.length===1&&t.length===1?t[0]?.error??"":t.map(n=>`${n.email}: ${n.error}`).join("; ")}function Wp(e,t){let n=Math.min(e,t);return{x:Math.floor((e-n)/2),y:Math.floor((t-n)/2),side:n}}var bi=class extends Error{constructor(){super("Couldn\u2019t read that image. Pick a PNG, JPEG, WebP, or GIF.")}};async function ql(e,t){let n=await createImageBitmap(e,{imageOrientation:"from-image"}).catch(()=>{throw new bi});try{let{x:s,y:i,side:r}=Wp(n.width,n.height),a=document.createElement("canvas");a.width=t,a.height=t;let l=a.getContext("2d");if(!l)throw new Error("This browser can\u2019t prepare the image.");return l.imageSmoothingQuality="high",l.drawImage(n,s,i,r,r,0,0,t,t),{png:await new Promise((u,m)=>a.toBlob(v=>v?u(v):m(new Error("This browser can\u2019t prepare the image.")),"image/png")),width:n.width,height:n.height}}finally{n.close()}}function Vp(e){if(!(e.identity_fields||[]).length)return o`Your email template doesn’t show any of these.`;let t="Shown in every email.",n=e.sends.length;if(!n)return o`${t}`;let s=`Saving a change updates ${n} scheduled email${n===1?"":"s"} too; you\u2019ll confirm first.`;return o`${t} ${s}${nn(e)}`}var Kp="#/docs/name-your-publication/when-to-provide-a-mailing-address";function Bn(){return o`<a class="set-link" href="${Kp}" target="_blank" rel="noopener">When to provide a mailing address <span aria-hidden="true">↗</span><span class="visually-hidden"> (opens in a new tab)</span></a>`}var gi=256;function jl(e){let{state:t,fromDisplay:n,fromName:s}=e,i=!!t.address;return o`
418
419
  <section class="set-sec">
419
- ${we("Publication identity",ye("editable","Editable"))}
420
+ ${Se("Publication identity",we("editable","Editable"))}
420
421
  <div class="set-card">
421
422
  <div class="set-id-grid">
422
423
  <div class="set-logo-slot">
423
424
  <div class="set-logo-tile${t.logoUrl?" has-img":""}" id="logoTile" role="button" tabindex="0" aria-label="Upload logo">
424
- <span class="set-logo-ph" id="logoPh"${t.logoUrl?Ln:null}>${N("upload")}Upload</span>
425
+ <span class="set-logo-ph" id="logoPh"${t.logoUrl?Nn:null}>${O("upload")}Upload</span>
425
426
  </div>
426
427
  <input type="file" id="logoInput" accept="image/png,image/jpeg,image/webp,image/gif" hidden>
427
428
  <div class="set-logo-actions">
428
429
  <button type="button" id="logoReplace">${t.logoUrl?"Replace":"Upload"}</button>
429
- <button type="button" class="danger-subtle" id="logoRemove"${t.logoUrl?null:Ln}>Remove</button>
430
+ <button type="button" class="danger-subtle" id="logoRemove"${t.logoUrl?null:Nn}>Remove</button>
430
431
  </div>
431
432
  <div class="set-logo-notes">
432
- <p class="field-hint">Shown as a square. Pick an image at least ${String(Xo)}&nbsp;×&nbsp;${String(Xo)}&nbsp;px; a wider or taller one is cropped to its center square.</p>
433
+ <p class="field-hint">Shown as a square. Pick an image at least ${String(gi)}&nbsp;×&nbsp;${String(gi)}&nbsp;px; a wider or taller one is cropped to its center square.</p>
433
434
  <p class="set-field-warn" id="logoShape" hidden>Your logo isn’t square, so emails show it stretched. Replace it to have it cropped square.</p>
434
435
  <div class="field-error" id="logoError" role="alert" hidden><span class="field-error-ico" aria-hidden="true">!</span><span></span></div>
435
436
  </div>
@@ -445,24 +446,24 @@
445
446
  <input id="setTagline" value="${t.tagline}" placeholder="A one-line description" maxlength="200" autocomplete="off">
446
447
  <p class="field-hint">A short line under the name on your public pages.</p>
447
448
  </div>
448
- <div class="set-field set-addr-add" id="addrAdd"${i?Ln:null}>
449
- <button type="button" class="ghost" id="addrAddBtn" aria-describedby="addrAddHint">${N("plus")}Add a mailing address</button>
450
- <p class="field-hint" id="addrAddHint">For promotional email, US law (CAN-SPAM) requires a postal address in the footer. A P.O. box works. ${An()}</p>
449
+ <div class="set-field set-addr-add" id="addrAdd"${i?Nn:null}>
450
+ <button type="button" class="ghost" id="addrAddBtn" aria-describedby="addrAddHint">${O("plus")}Add a mailing address</button>
451
+ <p class="field-hint" id="addrAddHint">For promotional email, US law (CAN-SPAM) requires a postal address in the footer. A P.O. box works. ${Bn()}</p>
451
452
  </div>
452
- <div class="set-field" id="addrField"${i?null:Ln}>
453
+ <div class="set-field" id="addrField"${i?null:Nn}>
453
454
  <div class="set-field-head">
454
455
  <label for="setAddress">Mailing address</label>
455
456
  <button type="button" class="danger-subtle set-field-remove" id="addrRemove">Remove</button>
456
457
  </div>
457
458
  <input id="setAddress" value="${t.address}" placeholder="PO Box 123, City, ST 00000" maxlength="300" autocomplete="off">
458
- <p class="field-hint">${An()}</p>
459
- <p class="set-field-warn" id="addrWarn" hidden>Your email template currently doesn’t include this field. If you send promotional email, add it to the template. ${An()}</p>
459
+ <p class="field-hint">${Bn()}</p>
460
+ <p class="set-field-warn" id="addrWarn" hidden>Your email template currently doesn’t include this field. If you send promotional email, add it to the template. ${Bn()}</p>
460
461
  </div>
461
462
  </div>
462
463
  </div>
463
- <div class="set-note">${N("info")}<span>${Ju(e.data.in_use)}</span></div>
464
+ <div class="set-note">${O("info")}<span>${Vp(e.data.in_use)}</span></div>
464
465
  </div>
465
- </section>`}function dl(e,t,n){let{state:s}=t,i=c("#setName",e),a=c("#setTagline",e),r=c("#setAddress",e),l=()=>{s.name=i.value.trim(),s.tagline=a.value.trim(),s.address=r.value.trim(),t.changed()};i.addEventListener("input",l),a.addEventListener("input",l),r.addEventListener("input",l);let d=!!s.address,u=(t.data.in_use.identity_fields||[]).includes("address"),f=c("#addrAdd",e),S=c("#addrField",e),b=c("#addrWarn",e),p=()=>{f.hidden=d,S.hidden=!d,b.hidden=!(d&&s.address&&!u),b.hidden?r.removeAttribute("aria-describedby"):r.setAttribute("aria-describedby","addrWarn")};r.addEventListener("input",p),c("#addrAddBtn",e).onclick=()=>{d=!0,p(),r.focus()},c("#addrRemove",e).onclick=()=>{r.value="",d=!1,l(),p(),c("#addrAddBtn",e).focus()};let v=c("#logoInput",e),x=c("#logoTile",e),M=c("#logoPh",e),A=c("#logoReplace",e),H=c("#logoRemove",e),T=c("#logoShape",e),m=g=>{if(T.hidden=!0,!g)return;let E=new Image;E.onload=()=>{T.hidden=s.logoUrl!==g||E.naturalWidth===E.naturalHeight},E.src=g},y=()=>{let g=!!s.logoUrl;m(s.logoUrl),x.classList.toggle("has-img",g),x.style.backgroundImage=g?`url('${s.logoUrl}')`:"",M.hidden=g,H.hidden=!g,A.textContent=g?"Replace":"Upload"};A.onclick=()=>v.click(),x.addEventListener("click",()=>v.click()),x.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),v.click())});let C=c("#logoError",e),U=c("span:last-of-type",C),J=g=>{U.textContent=g,C.hidden=!g},z=(g,E)=>{s.logoUrl=g.settings.publication.logo_url||"",t.applySaved(g.settings),y(),t.changed(),O(en(E,g.remade))},q=g=>J(at(g));return v.onchange=async()=>{let g=v.files?.[0];if(v.value="",!!g){J("");try{let E=await ll(g,Xo),L=E.width!==E.height,$=await _t(_=>{let K=new FormData;K.append("file",new File([E.png],"logo.png",{type:"image/png"}));let D=_?`?remake=${encodeURIComponent(_.join(","))}`:"";return R(`/api/settings/logo${D}`,{method:"POST",body:K})},Cn("Upload","Uploading"),n);$&&z($,L?"Logo updated, cropped to its center square":"Logo updated")}catch(E){q(E)}}},H.onclick=()=>G(H,"Removing\u2026",async()=>{J("");try{let g=await _t(E=>{let L=E?`?remake=${encodeURIComponent(E.join(","))}`:"";return R(`/api/settings/logo${L}`,{method:"DELETE"})},Cn("Remove","Removing"),n);g&&z(g,"Logo removed")}catch(g){q(g)}}),y(),p(),{reset(){i.value=s.name,a.value=s.tagline,r.value=s.address,d=!!s.address,p()}}}var Fs=F,Xu=[{group:"Post",vars:[{token:"{{ .Post.Body }}",desc:"Your post\u2019s Markdown, rendered to HTML."},{token:"{{ .Post.Subject }}",desc:"The post\u2019s subject line."}]},{group:"Publication",vars:[{token:"{{ .Publication.Name }}",desc:"Publication name (from Identity, above)."},{token:"{{ .Publication.Tagline }}",desc:"Your tagline."},{token:"{{ .Publication.Logo }}",desc:"Your logo as an image, or nothing when no logo is set."},{token:"{{ .Publication.LogoURL }}",desc:"Absolute URL of your logo, or empty."},{token:"{{ .Publication.Address }}",desc:"Your mailing address, if you\u2019ve added one in Settings; empty otherwise. Keep it in the footer if you send promotional email."}]},{group:"Email",vars:[{token:"{{ .Email.SentTo }}",desc:"The recipient\u2019s address (filled per send)."},{token:"{{ .Email.UnsubscribeURL }}",desc:"Their one-click unsubscribe link."},{token:"{{ .Email.ViewInBrowserURL }}",desc:"The web version\u2019s permanent URL."}]},{group:"Email only",vars:[{token:"{{ if .IsEmail }} \u2026 {{ end }}",desc:"Reports whether this is the email or the web version. Put your unsubscribe link and address inside; the web version leaves them out."}]}],ei={signed:{label:"Signed",description:"Your post, then your logo, name, and tagline as a sign-off. Your mailing address sits in the footer once you add one.",html:`<style>
466
+ </section>`}function Wl(e,t,n){let{state:s}=t,i=c("#setName",e),r=c("#setTagline",e),a=c("#setAddress",e),l=()=>{s.name=i.value.trim(),s.tagline=r.value.trim(),s.address=a.value.trim(),t.changed()};i.addEventListener("input",l),r.addEventListener("input",l),a.addEventListener("input",l);let d=!!s.address,u=(t.data.in_use.identity_fields||[]).includes("address"),m=c("#addrAdd",e),v=c("#addrField",e),f=c("#addrWarn",e),p=()=>{m.hidden=d,v.hidden=!d,f.hidden=!(d&&s.address&&!u),f.hidden?a.removeAttribute("aria-describedby"):a.setAttribute("aria-describedby","addrWarn")};a.addEventListener("input",p),c("#addrAddBtn",e).onclick=()=>{d=!0,p(),a.focus()},c("#addrRemove",e).onclick=()=>{a.value="",d=!1,l(),p(),c("#addrAddBtn",e).focus()};let S=c("#logoInput",e),$=c("#logoTile",e),M=c("#logoPh",e),P=c("#logoReplace",e),A=c("#logoRemove",e),H=c("#logoShape",e),y=b=>{if(H.hidden=!0,!b)return;let E=new Image;E.onload=()=>{H.hidden=s.logoUrl!==b||E.naturalWidth===E.naturalHeight},E.src=b},w=()=>{let b=!!s.logoUrl;y(s.logoUrl),$.classList.toggle("has-img",b),$.style.backgroundImage=b?`url('${s.logoUrl}')`:"",M.hidden=b,A.hidden=!b,P.textContent=b?"Replace":"Upload"};P.onclick=()=>S.click(),$.addEventListener("click",()=>S.click()),$.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),S.click())});let T=c("#logoError",e),D=c("span:last-of-type",T),R=b=>{D.textContent=b,T.hidden=!b},F=(b,E)=>{s.logoUrl=b.settings.publication.logo_url||"",t.applySaved(b.settings),w(),t.changed(),U(sn(E,b.remade))},K=b=>R(ut(b));return S.onchange=async()=>{let b=S.files?.[0];if(S.value="",!!b){R("");try{let E=await ql(b,gi),C=E.width!==E.height,x=await Ct(W=>{let oe=new FormData;oe.append("file",new File([E.png],"logo.png",{type:"image/png"}));let k=W?`?remake=${encodeURIComponent(W.join(","))}`:"";return L(`/api/settings/logo${k}`,{method:"POST",body:oe})},Dn("Upload","Uploading"),n);x&&F(x,C?"Logo updated, cropped to its center square":"Logo updated")}catch(E){K(E)}}},A.onclick=()=>Z(A,"Removing\u2026",async()=>{R("");try{let b=await Ct(E=>{let C=E?`?remake=${encodeURIComponent(E.join(","))}`:"";return L(`/api/settings/logo${C}`,{method:"DELETE"})},Dn("Remove","Removing"),n);b&&F(b,"Logo removed")}catch(b){K(b)}}),w(),p(),{reset(){i.value=s.name,r.value=s.tagline,a.value=s.address,d=!!s.address,p()}}}var eo=V,Gp=[{group:"Post",vars:[{token:"{{ .Post.Body }}",desc:"Your post\u2019s Markdown, rendered to HTML."},{token:"{{ .Post.Subject }}",desc:"The post\u2019s subject line."}]},{group:"Publication",vars:[{token:"{{ .Publication.Name }}",desc:"Publication name (from Identity, above)."},{token:"{{ .Publication.Tagline }}",desc:"Your tagline."},{token:"{{ .Publication.Logo }}",desc:"Your logo as an image, or nothing when no logo is set."},{token:"{{ .Publication.LogoURL }}",desc:"Absolute URL of your logo, or empty."},{token:"{{ .Publication.Address }}",desc:"Your mailing address, if you\u2019ve added one in Settings; empty otherwise. Keep it in the footer if you send promotional email."}]},{group:"Email",vars:[{token:"{{ .Email.SentTo }}",desc:"The recipient\u2019s address (filled per send)."},{token:"{{ .Email.UnsubscribeURL }}",desc:"Their one-click unsubscribe link."},{token:"{{ .Email.ViewInBrowserURL }}",desc:"The web version\u2019s permanent URL."}]},{group:"Email only",vars:[{token:"{{ if .IsEmail }} \u2026 {{ end }}",desc:"Reports whether this is the email or the web version. Put your unsubscribe link and address inside; the web version leaves them out."}]}],vi={signed:{label:"Signed",description:"Your post, then your logo, name, and tagline as a sign-off. Your mailing address sits in the footer once you add one.",html:`<style>
466
467
  .email {
467
468
  font: 16px/1.6 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
468
469
  color: #18181b;
@@ -617,7 +618,7 @@
617
618
  <a href="{{ .Email.ViewInBrowserURL }}">View in browser</a>
618
619
  <div class="address">{{ .Publication.Address }}</div>{{ end }}
619
620
  </div>
620
- </div>`}},ep=e=>Object.hasOwn(ei,e),tp=`<div style="position:relative;border:1px dashed #93a7e6;border-radius:8px;padding:20px 14px 8px;margin:0 0 6px"><span style="position:absolute;top:-8px;left:10px;font:650 10px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;letter-spacing:.04em;text-transform:uppercase;color:#3355cc;background:#fff;padding:0 6px">Your post\u2019s Markdown renders here</span><h2 style="margin:0 0 10px">Lorem ipsum,</h2><p style="margin:0">Dolor sit amet, consectetur adipiscing elit. Proin sed ex ipsum. Suspendisse vulputate nisi et odio dapibus, quis pellentesque felis sollicitudin. Proin vel cursus enim. Phasellus sollicitudin malesuada elementum. Suspendisse euismod eros turpis, ut mollis est imperdiet ut. Sed luctus accumsan erat, at eleifend purus eleifend quis.</p></div>`,np=new Set([".Post.Body",".Publication.Logo"]);function sp(e,t){return String(e).replace(/\{\{\s*(?:if\b[^}]*|end)\s*\}\}/g,"").replace(/\{\{\s*([\w.]+)\s*\}\}/g,(s,i)=>np.has(i)?t[i]||"":X(t[i]??""))}function op(e){let t=e.name||"Your publication";return{".Post.Body":tp,".Post.Subject":"The starlings are back",".Publication.Name":t,".Publication.Tagline":e.tagline||"Your tagline",".Publication.LogoURL":e.logoUrl,".Publication.Logo":rl(e.logoUrl,t),".Publication.Address":e.address,".Email.SentTo":"you@example.com",".Email.UnsubscribeURL":"#unsubscribe",".Email.ViewInBrowserURL":"#view-in-browser"}}function ip(e,t){return sp(e,op(t))}var rp='<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0}body{background:#fff}@media (prefers-color-scheme:dark){body{background:#18181b}}.kestrel-email{max-width:640px;margin:0 auto;padding:26px 20px;box-sizing:border-box}.kestrel-email img{max-width:100%}</style></head><body><div class="kestrel-email"></div></body></html>';function ti(e,t,n){e.setAttribute("sandbox",Yt);let s=!1,i=()=>{try{let r=e.contentDocument?.body?.scrollHeight;r&&(e.style.height=`${Math.max(200,r)}px`)}catch{}},a=()=>{let r=e.contentDocument,l=s&&r?r.querySelector(".kestrel-email"):null;l&&(h(l,j(ip(t(),n()))),Zt(l.ownerDocument),i())};return e.addEventListener("load",()=>{s=!0,a();try{let r=e.contentDocument;r?.body&&typeof ResizeObserver<"u"&&new ResizeObserver(i).observe(r.body)}catch{}}),e.srcdoc=rp,{repaint:a}}function ap(){return o`${Xu.map(e=>o`<div class="set-tpl-vargroup"><h4>${e.group}</h4>${e.vars.map(t=>o`<div class="set-tpl-var"><code>${t.token}</code><span class="set-tpl-var-desc">${t.desc}</span></div>`)}</div>`)}`}async function ni(e,t){se(t,"Template"),h(e,o`<div class="tpl-page"><div class="page-head"><div class="page-head-row"><h1>Email template</h1><span id="tplInUse"></span></div><p class="set-lede set-page-lede">The template controls the look and feel of the emails you send. You write it as HTML with a <code>&lt;style&gt;</code> block and <code>{{ variables }}</code> Kestrel fills in; your post’s Markdown is rendered into <code>{{ .Post.Body }}</code>.<span id="tplWait"></span></p></div><div id="tplBody" class="muted">Loading…</div></div>`);let n=c("#tplBody",e),s;try{s=await R("/api/settings",{signal:t})}catch(Y){oe(n,Fs(Y),()=>ee(ni));return}let i=s.settings,a=s.deployment,r=i.publication,l={name:cn(r.name||"",a.from_address),tagline:r.tagline||"",logoUrl:r.logo_url||"",address:r.address||""},d=i.email_template||"",u=Array.isArray(i.test_recipients)?i.test_recipients:[];h(c("#tplInUse"),Ds(s.in_use)),h(c("#tplWait"),o`${Xt(s.in_use)}`),Us(e,s.in_use,t),h(n,o`
621
+ </div>`}},zp=e=>Object.hasOwn(vi,e),Yp=`<div style="position:relative;border:1px dashed #93a7e6;border-radius:8px;padding:20px 14px 8px;margin:0 0 6px"><span style="position:absolute;top:-8px;left:10px;font:650 10px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;letter-spacing:.04em;text-transform:uppercase;color:#3355cc;background:#fff;padding:0 6px">Your post\u2019s Markdown renders here</span><h2 style="margin:0 0 10px">Lorem ipsum,</h2><p style="margin:0">Dolor sit amet, consectetur adipiscing elit. Proin sed ex ipsum. Suspendisse vulputate nisi et odio dapibus, quis pellentesque felis sollicitudin. Proin vel cursus enim. Phasellus sollicitudin malesuada elementum. Suspendisse euismod eros turpis, ut mollis est imperdiet ut. Sed luctus accumsan erat, at eleifend purus eleifend quis.</p></div>`,Zp=new Set([".Post.Body",".Publication.Logo"]);function Jp(e,t){return String(e).replace(/\{\{\s*(?:if\b[^}]*|end)\s*\}\}/g,"").replace(/\{\{\s*([\w.]+)\s*\}\}/g,(s,i)=>Zp.has(i)?t[i]||"":X(t[i]??""))}function Qp(e){let t=e.name||"Your publication";return{".Post.Body":Yp,".Post.Subject":"The starlings are back",".Publication.Name":t,".Publication.Tagline":e.tagline||"Your tagline",".Publication.LogoURL":e.logoUrl,".Publication.Logo":Bl(e.logoUrl,t),".Publication.Address":e.address,".Email.SentTo":"you@example.com",".Email.UnsubscribeURL":"#unsubscribe",".Email.ViewInBrowserURL":"#view-in-browser"}}function Xp(e,t){return Jp(e,Qp(t))}var em='<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0}body{background:#fff}@media (prefers-color-scheme:dark){body{background:#18181b}}.kestrel-email{max-width:640px;margin:0 auto;padding:26px 20px;box-sizing:border-box}.kestrel-email img{max-width:100%}</style></head><body><div class="kestrel-email"></div></body></html>';function yi(e,t,n){e.setAttribute("sandbox",Qt);let s=!1,i=()=>{try{let a=e.contentDocument?.body?.scrollHeight;a&&(e.style.height=`${Math.max(200,a)}px`)}catch{}},r=()=>{let a=e.contentDocument,l=s&&a?a.querySelector(".kestrel-email"):null;l&&(h(l,z(Xp(t(),n()))),Xt(l.ownerDocument),i())};return e.addEventListener("load",()=>{s=!0,r();try{let a=e.contentDocument;a?.body&&typeof ResizeObserver<"u"&&new ResizeObserver(i).observe(a.body)}catch{}}),e.srcdoc=em,{repaint:r}}function tm(){return o`${Gp.map(e=>o`<div class="set-tpl-vargroup"><h4>${e.group}</h4>${e.vars.map(t=>o`<div class="set-tpl-var"><code>${t.token}</code><span class="set-tpl-var-desc">${t.desc}</span></div>`)}</div>`)}`}async function wi(e,t){ie(t,"Template"),h(e,o`<div class="tpl-page"><div class="page-head"><div class="page-head-row"><h1>Email template</h1><span id="tplInUse"></span></div><p class="set-lede set-page-lede">The template controls the look and feel of the emails you send. You write it as HTML with a <code>&lt;style&gt;</code> block and <code>{{ variables }}</code> Kestrel fills in; your post’s Markdown is rendered into <code>{{ .Post.Body }}</code>.<span id="tplWait"></span></p></div><div id="tplBody" class="muted">Loading…</div></div>`);let n=c("#tplBody",e),s;try{s=await L("/api/settings",{signal:t})}catch(Q){re(n,eo(Q),()=>ee(wi));return}let i=s.settings,r=s.deployment,a=i.publication,l={name:mn(a.name||"",r.from_address),tagline:a.tagline||"",logoUrl:a.logo_url||"",address:a.address||""},d=i.email_template||"",u=Array.isArray(i.test_recipients)?i.test_recipients:[];h(c("#tplInUse"),Qs(s.in_use)),h(c("#tplWait"),o`${nn(s.in_use)}`),Xs(e,s.in_use,t),h(n,o`
621
622
  <div class="set-preview set-tpl-sample">
622
623
  <div class="set-preview-bar">
623
624
  <span class="set-preview-titles">
@@ -629,7 +630,7 @@
629
630
  <button type="button" class="wtog-btn" data-w="640" aria-pressed="true">640</button>
630
631
  <button type="button" class="wtog-btn" data-w="375" aria-pressed="false">375</button>
631
632
  </span>
632
- <button type="button" class="secondary" id="tplTest">${N("send")}<span id="tplTestLbl">Send test email</span></button>
633
+ <button type="button" class="secondary" id="tplTest">${O("send")}<span id="tplTestLbl">Send test email</span></button>
633
634
  </span>
634
635
  </div>
635
636
  <div class="set-email-stage" id="tplStage">
@@ -644,7 +645,7 @@
644
645
  <div class="set-tpl-editor-head">
645
646
  <div class="set-tpl-tools">
646
647
  <button type="button" class="ghost set-menu-btn" id="tplExamplesBtn" aria-haspopup="menu" aria-expanded="false"><span>Start from example</span><span class="set-menu-caret"></span></button>
647
- <button type="button" class="set-icon-btn" id="tplLineNums" aria-pressed="false" title="Show line numbers" aria-label="Show line numbers">${N("lines")}</button>
648
+ <button type="button" class="set-icon-btn" id="tplLineNums" aria-pressed="false" title="Show line numbers" aria-label="Show line numbers">${O("lines")}</button>
648
649
  <button type="button" class="ghost" id="tplCopyAll" title="Copy the whole template to the clipboard" aria-label="Copy the whole template">${Te()}</button>
649
650
  </div>
650
651
  <div class="set-tpl-required" aria-label="Required variables">
@@ -661,7 +662,7 @@
661
662
  <div class="set-tpl-msgs" id="tplMsgs" hidden></div>
662
663
  </div>
663
664
  </div>
664
- <div class="set-note">${N("info")}<span>Kestrel uses this one template for every post, starting from a sensible default. Saving a change while posts are scheduled applies it to their emails too, after you confirm, so nothing scheduled goes out on an older look; their content stays as it was. Sent emails are archived exactly as they went out and never change. Save and Discard are in the bar at the bottom of the page.</span></div>
665
+ <div class="set-note">${O("info")}<span>Kestrel uses this one template for every post, starting from a sensible default. Saving a change while posts are scheduled applies it to their emails too, after you confirm, so nothing scheduled goes out on an older look; their content stays as it was. Sent emails are archived exactly as they went out and never change. Save and Discard are in the bar at the bottom of the page.</span></div>
665
666
  </div>
666
667
 
667
668
  <div class="set-card set-tpl-varcard">
@@ -670,16 +671,16 @@
670
671
  <h3 class="set-tpl-vartitle">Variables</h3>
671
672
  <p class="field-hint">Kestrel replaces these variables with real values when you send an email. Type a variable exactly as shown, or it renders as empty.</p>
672
673
  </div>
673
- <div class="set-tpl-vars-body">${ap()}</div>
674
+ <div class="set-tpl-vars-body">${tm()}</div>
674
675
  </div>
675
- </div>`);let f=c("#tplEditor"),S=ti(c("#tplPreview"),()=>f.value,()=>l),b=c("#tplMsgs"),p=c("#tplTest"),v=c("#tplTestLbl"),x=()=>f.value!==d,M=c("#tplHl"),A=c("code",M),H=c("#tplGutter"),T=()=>{let Y=f.value;h(A,o`${ba(Y)}\n`);let le="",de=Y.split(`
676
- `).length;for(let He=1;He<=de;He++)le+=`${He}
677
- `;H.textContent=le},m=()=>{M.scrollTop=f.scrollTop,M.scrollLeft=f.scrollLeft,H.scrollTop=f.scrollTop};f.addEventListener("scroll",m);let y=c("#reqBody"),C=c("#reqUnsub"),U=()=>{y.className=`set-req-pill ${/\{\{\s*\.Post\.Body\s*\}\}/.test(f.value)?"ok":"bad"}`,C.className=`set-req-pill ${/\{\{\s*\.Email\.UnsubscribeURL\s*\}\}/.test(f.value)?"ok":"bad"}`},J=Bs.attach({onSave:L,onDiscard:g},t);function z(){T(),U(),m(),J.setDirty(x()),v.textContent=x()?"Save & send test":"Send test email",p.title=x()?"Saves your changes first, then sends: a test always reflects the saved template that will ship.":"Sends a sample post through the saved template so you can see it in a real inbox."}function q(Y){if(!Y.length){b.hidden=!0,h(b,o``);return}b.hidden=!1,b.className="set-tpl-msgs warn",h(b,o`${Y.map(le=>o`<div>${le}${le===al?o` ${An()}`:null}</div>`)}`)}function g(){f.value=d,q([]),S.repaint(),z()}async function E(){let Y=f.value,le=await _t(de=>R("/api/settings",{method:"PUT",json:de?{email_template:Y,remake:de}:{email_template:Y}}),ol,t);return le?(d=le.settings.email_template,f.value=d,Q.appConfig={...s,settings:le.settings},S.repaint(),z(),{warnings:Array.isArray(le.warnings)?le.warnings:[],remade:le.remade||[]}):null}async function L(){try{let Y=await E();if(!Y)return;q(Y.warnings),O(en(Y.warnings.length?"Template saved with warnings":"Template saved",Y.remade))}catch(Y){J.showError(Fs(Y))}}let $=Y=>{let le=ei[ep(Y)?Y:"signed"];f.value=le.html,q([]),S.repaint(),z()};f.addEventListener("input",()=>{S.repaint(),z()});let _=c("#tplExamplesBtn");_.onclick=()=>Kt(_,Object.entries(ei).map(([Y,le])=>({label:le.label,description:le.description,onClick:()=>$(Y)})),t,{align:"start"});let K=c("#tplPreview");for(let Y of I(".wtog-btn",n))Y.onclick=()=>{for(let le of I(".wtog-btn",n))le.setAttribute("aria-pressed",String(le===Y));K.style.maxWidth=`${Y.dataset.w}px`,S.repaint()};let D=c("#tplEditorWrap"),ae=c("#tplLineNums"),V=Y=>{D.classList.toggle("show-lines",Y),ae.setAttribute("aria-pressed",String(Y)),m()},re=!1;try{re=localStorage.getItem("kestrel.tpl.lineNums")==="1"}catch{}V(re),ae.onclick=()=>{re=!re,V(re);try{localStorage.setItem("kestrel.tpl.lineNums",re?"1":"0")}catch{}};let lt=c("#tplCopyAll");lt.onclick=()=>wn(lt,f.value),p.onclick=()=>{let Y=ve(),le=!Y&&x(),de=pe(o`<h3>Send a test email</h3><p class="hint">Delivers a sample post rendered through your <strong>saved</strong> template, so you can see it in a real inbox. One address per line.</p>${cs()}${le?o`<p class="hint" style="color:var(--warn-fg)"><strong>Unsaved changes:</strong> sending will save your template first, so the test reflects what will actually ship.</p>`:null}${Y?null:o`<label for="tplTestTo">Recipients</label><textarea id="tplTestTo" rows="3" placeholder="you@example.com"></textarea><p class="hint" id="tplTestHint" hidden></p>`}<div class="actions"><button type="button" id="ttCancel">Cancel</button><button type="button" class="primary" id="ttGo">${le?"Save & send test":"Send test"}</button></div>`,t),He=c("#ttGo",de.el);if(c("#ttCancel",de.el).onclick=de.close,He.disabled=Y,Y){c("#ttCancel",de.el).focus();return}let Re=c("#tplTestTo",de.el);if(Re.focus(),u.length&&!Re.value.trim()){Re.value=u.join(`
678
- `);let Pe=c("#tplTestHint",de.el);Pe.textContent="Pre-filled from your default test recipients (Settings).",Pe.hidden=!1}He.onclick=()=>G(He,x()?"Saving\u2026":"Sending\u2026",async()=>{de.clearError();let{valid:Pe,invalid:ct}=fs(Re.value),dt=hs(ct);if(dt){de.error(dt,Re);return}if(!Pe.length){de.error("Enter at least one email address",Re);return}if(x())try{let ue=await E();if(!ue){de.close();return}q(ue.warnings)}catch(ue){J.showError(Fs(ue)),de.close();return}try{let ue=await R("/api/settings/template/test",{method:"POST",json:{to:Pe}});if(ue.failed.length){Re.value=ue.failed.join(`
679
- `),de.error(bs(ue.sent,ue.total,ue.not_sent));return}de.close(),O(Nt(`Test sent to ${ue.sent} address${ue.sent===1?"":"es"}`))}catch(ue){de.error(Fs(ue))}})},f.value=d,S.repaint(),z()}function ul(e){return o`
676
+ </div>`);let m=c("#tplEditor"),v=yi(c("#tplPreview"),()=>m.value,()=>l),f=c("#tplMsgs"),p=c("#tplTest"),S=c("#tplTestLbl"),$=()=>m.value!==d,M=c("#tplHl"),P=c("code",M),A=c("#tplGutter"),H=()=>{let Q=m.value;h(P,o`${Ya(Q)}\n`);let le="",de=Q.split(`
677
+ `).length;for(let Pe=1;Pe<=de;Pe++)le+=`${Pe}
678
+ `;A.textContent=le},y=()=>{M.scrollTop=m.scrollTop,M.scrollLeft=m.scrollLeft,A.scrollTop=m.scrollTop};m.addEventListener("scroll",y);let w=c("#reqBody"),T=c("#reqUnsub"),D=()=>{w.className=`set-req-pill ${/\{\{\s*\.Post\.Body\s*\}\}/.test(m.value)?"ok":"bad"}`,T.className=`set-req-pill ${/\{\{\s*\.Email\.UnsubscribeURL\s*\}\}/.test(m.value)?"ok":"bad"}`},R=zs.attach({onSave:C,onDiscard:b},t);function F(){H(),D(),y(),R.setDirty($()),S.textContent=$()?"Save & send test":"Send test email",p.title=$()?"Saves your changes first, then sends: a test always reflects the saved template that will ship.":"Sends a sample post through the saved template so you can see it in a real inbox."}function K(Q){if(!Q.length){f.hidden=!0,h(f,o``);return}f.hidden=!1,f.className="set-tpl-msgs warn",h(f,o`${Q.map(le=>o`<div>${le}${le===Ul?o` ${Bn()}`:null}</div>`)}`)}function b(){m.value=d,K([]),v.repaint(),F()}async function E(){let Q=m.value,le=await Ct(de=>L("/api/settings",{method:"PUT",json:de?{email_template:Q,remake:de}:{email_template:Q}}),Ol,t);return le?(d=le.settings.email_template,m.value=d,Y.appConfig={...s,settings:le.settings},v.repaint(),F(),{warnings:Array.isArray(le.warnings)?le.warnings:[],remade:le.remade||[]}):null}async function C(){try{let Q=await E();if(!Q)return;K(Q.warnings),U(sn(Q.warnings.length?"Template saved with warnings":"Template saved",Q.remade))}catch(Q){R.showError(eo(Q))}}let x=Q=>{let le=vi[zp(Q)?Q:"signed"];m.value=le.html,K([]),v.repaint(),F()};m.addEventListener("input",()=>{v.repaint(),F()});let W=c("#tplExamplesBtn");W.onclick=()=>Yt(W,Object.entries(vi).map(([Q,le])=>({label:le.label,description:le.description,onClick:()=>x(Q)})),t,{align:"start"});let oe=c("#tplPreview");for(let Q of N(".wtog-btn",n))Q.onclick=()=>{for(let le of N(".wtog-btn",n))le.setAttribute("aria-pressed",String(le===Q));oe.style.maxWidth=`${Q.dataset.w}px`,v.repaint()};let k=c("#tplEditorWrap"),G=c("#tplLineNums"),q=Q=>{k.classList.toggle("show-lines",Q),G.setAttribute("aria-pressed",String(Q)),y()},ne=!1;try{ne=localStorage.getItem("kestrel.tpl.lineNums")==="1"}catch{}q(ne),G.onclick=()=>{ne=!ne,q(ne);try{localStorage.setItem("kestrel.tpl.lineNums",ne?"1":"0")}catch{}};let He=c("#tplCopyAll");He.onclick=()=>Tn(He,m.value),p.onclick=()=>{let Q=ge(),le=!Q&&$(),de=fe(o`<h3>Send a test email</h3><p class="hint">Delivers a sample post rendered through your <strong>saved</strong> template, so you can see it in a real inbox. One address per line.</p>${vs()}${le?o`<p class="hint" style="color:var(--warn-fg)"><strong>Unsaved changes:</strong> sending will save your template first, so the test reflects what will actually ship.</p>`:null}${Q?null:o`<label for="tplTestTo">Recipients</label><textarea id="tplTestTo" rows="3" placeholder="you@example.com"></textarea><p class="hint" id="tplTestHint" hidden></p>`}<div class="actions"><button type="button" id="ttCancel">Cancel</button><button type="button" class="primary" id="ttGo">${le?"Save & send test":"Send test"}</button></div>`,t),Pe=c("#ttGo",de.el);if(c("#ttCancel",de.el).onclick=de.close,Pe.disabled=Q,Q){c("#ttCancel",de.el).focus();return}let Ce=c("#tplTestTo",de.el);if(Ce.focus(),u.length&&!Ce.value.trim()){Ce.value=u.join(`
679
+ `);let Me=c("#tplTestHint",de.el);Me.textContent="Pre-filled from your default test recipients (Settings).",Me.hidden=!1}Pe.onclick=()=>Z(Pe,$()?"Saving\u2026":"Sending\u2026",async()=>{de.clearError();let{valid:Me,invalid:pt}=xs(Ce.value),mt=Es(pt);if(mt){de.error(mt,Ce);return}if(!Me.length){de.error("Enter at least one email address",Ce);return}if($())try{let me=await E();if(!me){de.close();return}K(me.warnings)}catch(me){R.showError(eo(me)),de.close();return}try{let me=await L("/api/settings/template/test",{method:"POST",json:{to:Me}});if(me.failed.length){Ce.value=me.failed.join(`
680
+ `),de.error(ks(me.sent,me.total,me.not_sent));return}de.close(),U(Bt(`Test sent to ${me.sent} address${me.sent===1?"":"es"}`))}catch(me){de.error(eo(me))}})},m.value=d,v.repaint(),F()}function Vl(e){return o`
680
681
  <section class="set-sec">
681
- ${we("Email template",ye("editable","Editable"),Ds(e.data.in_use))}
682
- <p class="set-lede">The template controls the look and feel of the emails you send. Edit it on the Template page.${Xt(e.data.in_use)}</p>
682
+ ${Se("Email template",we("editable","Editable"),Qs(e.data.in_use))}
683
+ <p class="set-lede">The template controls the look and feel of the emails you send. Edit it on the Template page.${nn(e.data.in_use)}</p>
683
684
  <div class="set-preview set-tpl-sample">
684
685
  <div class="set-preview-bar">
685
686
  <span class="set-preview-lbl">Sample email</span>
@@ -688,54 +689,52 @@
688
689
  <iframe class="set-email-frame" id="tplPreview" title="Sample email preview" scrolling="no"></iframe>
689
690
  </div>
690
691
  <div class="row" style="margin-top:12px"><button type="button" id="tplEditLink">Edit template →</button></div>
691
- </section>`}function pl(e,t){let n=t.data.settings.email_template||"",s=ti(c("#tplPreview",e),()=>n,()=>({name:t.state.name||t.fromDisplay,tagline:t.state.tagline,logoUrl:t.state.logoUrl,address:t.state.address}));return c("#tplEditLink",e).onclick=()=>{location.hash="#/template"},{repaint:()=>s.repaint()}}function ml(){return o`
692
+ </section>`}function Kl(e,t){let n=t.data.settings.email_template||"",s=yi(c("#tplPreview",e),()=>n,()=>({name:t.state.name||t.fromDisplay,tagline:t.state.tagline,logoUrl:t.state.logoUrl,address:t.state.address}));return c("#tplEditLink",e).onclick=()=>{location.hash="#/template"},{repaint:()=>s.repaint()}}var Gl={chips:"recipChips",input:"recipInput",add:"recipAdd"};function zl(){return o`
692
693
  <section class="set-sec">
693
- ${we("Default test recipients",ye("editable","Editable"))}
694
+ ${Se("Default test recipients",we("editable","Editable"))}
694
695
  <div class="set-card">
695
696
  <div class="set-recip">
696
697
  <p class="field-hint" style="margin:0">Pre-filled into <strong>Send test email</strong> so you can proof a post against your own inboxes before scheduling. These are your addresses, and they don’t go through the subscribe-and-confirm flow.</p>
697
- <div class="set-chips" id="recipChips"></div>
698
- <div class="set-recip-add">
699
- <input type="email" id="recipInput" placeholder="you@example.com" autocomplete="off">
700
- <button type="button" id="recipAdd">Add inbox</button>
701
- </div>
698
+ ${Zs(Gl)}
702
699
  </div>
703
700
  </div>
704
- </section>`}function fl(e,t){let{state:n}=t,s=c("#recipChips",e),i=c("#recipInput",e),a=()=>{if(!n.recipients.length){h(s,o`<span class="set-recip-empty">No default recipients yet. Add one below.</span>`);return}h(s,o`${n.recipients.map((l,d)=>o`<span class="set-recip-chip">${l}<button type="button" data-rm="${d}" aria-label="Remove ${l}">${N("x")}</button></span>`)}`)};s.addEventListener("click",l=>{let d=l.target instanceof Element?l.target.closest("[data-rm]"):null;d&&(n.recipients.splice(Number(d.dataset.rm),1),a(),t.changed())});let r=()=>{let l=gt(i.value);if(l){if(!vt(l)){Ne(i,"That doesn\u2019t look like an email address."),i.focus();return}if(n.recipients.includes(l)){Ne(i,"That inbox is already in the list."),i.focus();return}n.recipients.push(l),i.value="",a(),t.changed()}};return c("#recipAdd",e).onclick=r,i.addEventListener("keydown",l=>{l.key==="Enter"&&(l.preventDefault(),r())}),a(),{reset:a}}function lp(e,t){switch(e){case"cloudflare":return"Cloudflare Email, separate from your newsletter\u2019s provider";case"provider":return t==="none"?"Your email provider, once one is connected":`Your email provider (${Os(t)})`;default:return"Local stand-in: nothing is delivered"}}var hl={finished:"went out",refused:"provider refusing",stuck:"in flight too long",wedged:"waiting to be resolved",missed:"missed fire time",import:"list imported",sandbox:"signup refused by the SES sandbox",test:"test"};function bl(e){return e.kind==="test"?"test notification":e.subject?`${e.subject} (${hl[e.kind]})`:hl[e.kind]}function si(e){let{last_sent:t,last_failure:n}=e;return n?o`<span class="set-pill danger">Not delivered</span> <span class="muted">${W(n.at)}, ${bl(n)}: ${n.error}</span>`:t?o`<span class="set-pill ok">${N("check")}Delivered</span> <span class="muted">${W(t.at)}, ${bl(t)}</span>`:o`<span class="muted">None yet</span>`}function gl(e){let t=e.data.deployment;return o`
701
+ </section>`}function Yl(e,t){return Js(e,t,{ids:Gl,list:()=>t.state.recipients,empty:"No default recipients yet. Add one below."})}function nm(e,t){switch(e){case"cloudflare":return"Cloudflare Email, separate from your newsletter\u2019s provider";case"provider":return t==="none"?"Your email provider, once one is connected":`Your email provider (${Ys(t)})`;default:return"Local stand-in: nothing is delivered"}}var Zl={finished:"went out",refused:"provider refusing",stuck:"in flight too long",wedged:"waiting to be resolved",missed:"missed fire time",import:"list imported",sandbox:"signup refused by the SES sandbox",not_sending:"email not going out",test:"test"};function Jl(e){return e.kind==="test"?"test notification":e.subject?`${e.subject} (${Zl[e.kind]})`:Zl[e.kind]}function $i(e){let{last_sent:t,last_failure:n}=e;return n?o`<span class="set-pill danger">Not delivered</span> <span class="muted">${j(n.at)}, ${Jl(n)}: ${n.error}</span>`:t?o`<span class="set-pill ok">${O("check")}Delivered</span> <span class="muted">${j(t.at)}, ${Jl(t)}</span>`:o`<span class="muted">None yet</span>`}var Ql={chips:"notifyChips",input:"notifyTo",add:"notifyAdd"};function Xl(e){let t=e.data.deployment;return o`
705
702
  <section class="set-sec">
706
- ${we("Notifications",ye("editable","Editable"))}
703
+ ${Se("Notifications",we("editable","Editable"))}
707
704
  <p class="set-lede">Kestrel emails you when a send goes out, and right away if a send runs into a problem.</p>
708
705
  <div class="set-card">
709
706
  <div class="set-recip">
710
- <div class="set-field" style="margin:0">
707
+ <div class="set-field">
711
708
  <label for="notifyTo">Send notifications to</label>
712
- <input type="email" id="notifyTo" value="${e.state.notifyTo}" placeholder="you@example.com" autocomplete="off">
713
- <p class="field-hint">One address. Leave blank for no notifications.</p>
709
+ <p class="field-hint" style="margin:0">Each address gets every notification. Add whoever runs Kestrel for you, so they’re told too. Up to ${5}.</p>
714
710
  </div>
711
+ ${Zs(Ql)}
715
712
  <div class="row"><button type="button" class="ghost" id="notifyTest">Send a test notification</button><span class="field-hint" id="notifyTestHint"></span></div>
716
713
  </div>
717
714
  <div class="set-kv" style="border-top:1px solid var(--line)">
718
- <div class="set-kv-k">Sent through</div><div class="set-kv-v">${lp(t.notify_channel,t.provider)}</div>
715
+ <div class="set-kv-k">Sent through</div><div class="set-kv-v">${nm(t.notify_channel,t.provider)}</div>
719
716
  <div class="set-kv-k">From address</div><div class="set-kv-v"><span class="mono">${t.notify_from}</span></div>
720
- <div class="set-kv-k">Last notification</div><div class="set-kv-v" id="notifyStatus">${si(e.data.notification_status)}</div>
717
+ <div class="set-kv-k">Last notification</div><div class="set-kv-v" id="notifyStatus">${$i(e.data.notification_status)}</div>
721
718
  </div>
722
- <div class="set-note">${N("readonly")}<span>The channel and its sender are set at deploy. ${t.notify_channel==="provider"?"Notifications go through your newsletter\u2019s own provider, so one about the provider refusing your account cannot reach you; Cloudflare\u2019s email avoids that. ":""}See the <a class="set-link" href="#/docs/notifications">setup guide</a>.</span></div>
719
+ <div class="set-note">${O("readonly")}<span>The channel and its sender are set at deploy. ${t.notify_channel==="provider"?"Notifications go through your newsletter\u2019s own provider, so one about the provider refusing your account cannot reach you; Cloudflare\u2019s email avoids that. ":""}See the <a class="set-link" href="#/docs/notifications">setup guide</a>.</span></div>
723
720
  </div>
724
- </section>`}function vl(e,t){let n=c("#notifyTo",e),s=c("#notifyTest",e),i=c("#notifyTestHint",e),a=c("#notifyStatus",e);n.addEventListener("input",()=>{t.state.notifyTo=n.value.trim().toLowerCase(),t.changed()});let r=()=>{let l=t.saved().notifyTo,d=l?t.state.notifyTo!==l?"Save first: the test goes to the saved address.":"":"Save an address to send a test.";s.disabled=!!d,i.textContent=d};return s.onclick=()=>G(s,"Sending\u2026",async()=>{try{let l=await R("/api/settings/notifications/test",{method:"POST"});O(l.channel==="fake"?`Test notification recorded for ${l.to} (local stand-in: nothing is delivered)`:`Test notification sent to ${l.to}`),h(a,si({last_sent:{kind:"test",subject:"",at:Date.now()},last_failure:null}))}catch(l){h(a,si({last_sent:null,last_failure:{kind:"test",subject:"",at:Date.now(),error:at(l)}}))}}),r(),{repaint:r,reset(){n.value=t.state.notifyTo,r()}}}var oi={base:"app",path:"/subscribe"},qs={base:"app",path:"/confirm?token=\u2026"},ii={base:"app",path:"/unsubscribe?token=\u2026"},Hn=[{id:"subscribe",label:"Subscribe",flow:"steps",states:[{id:"form",label:"Form",at:oi},{id:"check-inbox",label:"Check your inbox",at:oi},{id:"not-an-email",label:"Not an email",offPath:!0,at:oi}]},{id:"confirm",label:"Confirm",flow:"steps",states:[{id:"ready",label:"Ready",at:qs},{id:"confirmed",label:"Confirmed",at:qs},{id:"expired",label:"Expired",offPath:!0,at:qs},{id:"invalid",label:"Invalid link",offPath:!0,at:qs}]},{id:"unsubscribe",label:"Unsubscribe",flow:"steps",states:[{id:"ask",label:"Ask",at:ii},{id:"done",label:"Unsubscribed",at:ii},{id:"invalid",label:"Invalid link",offPath:!0,at:ii}]},{id:"reading",label:"Reading",flow:"peers",states:[{id:"landing",label:"Landing page",at:{base:"app",path:"/"}},{id:"archive",label:"Archive",at:{base:"archive",path:""}},{id:"post",label:"Post page",at:{base:"archive",path:"/sample-post"}},{id:"landing-empty",label:"Landing, no posts yet",offPath:!0,at:{base:"app",path:"/"}},{id:"archive-empty",label:"Archive, no posts yet",offPath:!0,at:{base:"archive",path:""}},{id:"not-found",label:"Nothing here yet",offPath:!0,at:{base:"archive",path:"/\u2026"}}]}];function yl(e,t){return`/api/reader-pages/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}var cp={subscribe:o`Your name, tagline, and logo head each page; the words are Kestrel’s. The embeddable form in Ways to subscribe posts to these pages too.`,confirm:o`Your identity heads each page. You word the email that links here, under Confirmation email; these pages’ words are fixed, so what a reader agrees to can’t be edited away.`,unsubscribe:o`Your identity heads each page; the words are fixed, so leaving always reads the same. A mail client’s own Unsubscribe button leaves without a page.`,reading:o`Your identity heads each page, and a post page is your <a class="set-link" href="#/template">email template</a> around the post, as its web version shows it. Where a page lists posts, they are samples.`},dp={subscribe:"mail",confirm:"circle-check",unsubscribe:"circle-minus",reading:"book"},up=o`<span class="set-rp-dot"></span>`;function wl(e,t,n){return o`<li><button type="button" class="set-rp-item${t.offPath?" off":""}" data-journey="${e.id}" data-state="${t.id}" aria-current="false"><span class="set-rp-mark" aria-hidden="true">${n}</span>${t.label}</button></li>`}function pp(){return o`${Hn.map(e=>{let t=e.states,n=e.flow==="steps";return o`<div class="set-rp-journey" data-journey="${e.id}">
725
- <h3 class="set-rp-jhead" id="rpJourney-${e.id}">${N(dp[e.id])}${e.label}</h3>
721
+ </section>`}function ec(e,t){let n=c("#notifyTest",e),s=c("#notifyTestHint",e),i=c("#notifyStatus",e),r=Js(e,t,{ids:Ql,list:()=>t.state.notifyTo,empty:"No addresses yet, so Kestrel emails no one. Add yours below.",max:{count:5,full:`Notifications go to at most ${5} addresses. Remove one to add another.`}}),a=()=>{let l=t.saved().notifyTo,d=l.length===0?"Save an address to send a test.":t.state.notifyTo.join(`
722
+ `)!==l.join(`
723
+ `)?"Save first: the test goes to the saved addresses.":"";n.disabled=!!d,s.textContent=d};return n.onclick=()=>Z(n,"Sending\u2026",async()=>{try{let l=await L("/api/settings/notifications/test",{method:"POST"}),d=l.to.filter(m=>!l.failed.some(v=>v.email===m));U(l.channel==="fake"?`Test notification recorded for ${d.join(", ")} (local stand-in: nothing is delivered)`:`Test notification sent to ${d.join(", ")}`);let u=Fl(l.to,l.failed);h(i,$i({last_sent:{kind:"test",subject:"",at:Date.now()},last_failure:u?{kind:"test",subject:"",at:Date.now(),error:u}:null}))}catch(l){h(i,$i({last_sent:null,last_failure:{kind:"test",subject:"",at:Date.now(),error:ut(l)}}))}}),a(),{repaint:a,reset(){r.reset?.(),a()}}}var Un={base:"app",path:"/subscribe"},to={base:"app",path:"/confirm?token=\u2026"},xi={base:"app",path:"/unsubscribe?token=\u2026"},Fn=[{id:"subscribe",label:"Subscribe",flow:"steps",states:[{id:"form",label:"Form",at:Un},{id:"check-inbox",label:"Check your inbox",at:Un},{id:"not-an-email",label:"Not an email",offPath:!0,at:Un},{id:"not-open",label:"Not open yet",offPath:!0,at:Un},{id:"paused",label:"Paused",offPath:!0,at:Un}]},{id:"confirm",label:"Confirm",flow:"steps",states:[{id:"ready",label:"Ready",at:to},{id:"confirmed",label:"Confirmed",at:to},{id:"expired",label:"Expired",offPath:!0,at:to},{id:"invalid",label:"Invalid link",offPath:!0,at:to}]},{id:"unsubscribe",label:"Unsubscribe",flow:"steps",states:[{id:"ask",label:"Ask",at:xi},{id:"done",label:"Unsubscribed",at:xi},{id:"invalid",label:"Invalid link",offPath:!0,at:xi}]},{id:"reading",label:"Reading",flow:"peers",states:[{id:"landing",label:"Landing page",at:{base:"app",path:"/"}},{id:"archive",label:"Archive",at:{base:"archive",path:""}},{id:"post",label:"Post page",at:{base:"archive",path:"/sample-post"}},{id:"landing-empty",label:"Landing, no posts yet",offPath:!0,at:{base:"app",path:"/"}},{id:"archive-empty",label:"Archive, no posts yet",offPath:!0,at:{base:"archive",path:""}},{id:"not-found",label:"Nothing here yet",offPath:!0,at:{base:"archive",path:"/\u2026"}}]}];function tc(e,t){return`/api/reader-pages/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}var no="Shown with signups open; until they are, readers get no Subscribe link or form here.",sm={subscribe:{form:"Your subscribe page, where a reader enters their email address.","check-inbox":"What the reader is shown after pressing Subscribe, here, on your website before your first post, or on a form embedded on your site.","not-an-email":"When the email address a reader sent isn\u2019t one that can be mailed. The browser catches most mistakes first.","not-open":"Shown in place of the form until your email provider accepts your first email, such as a test.",paused:"Shown in place of the form while your email provider won\u2019t send for your account, as when SES pauses your sending."},confirm:{ready:"When a reader opens the link in your confirmation email.",confirmed:"After they confirm. They\u2019re on your list and get your next post.",expired:"When a reader opens a confirmation link that\u2019s too old. They can ask for a new one.",invalid:"When a confirmation link is broken, mistyped, or replaced by a newer one."},unsubscribe:{ask:"When a reader opens the unsubscribe link in one of your emails. A mail application with its own one-click Unsubscribe button skips this page and removes them right away.",done:"After they press Unsubscribe. They get no more of your emails.",invalid:"When an unsubscribe link is broken or mistyped."},reading:{landing:`What anyone sees when they visit your newsletter\u2019s website. The posts are samples. ${no}`,archive:`Every post in your archive. These are samples. ${no}`,post:"The web version of a post that went out. Readers reach it from View in browser in its email, or from your archive.","landing-empty":`Your newsletter\u2019s website before your first post goes out. ${no}`,"archive-empty":`Your archive before your first post goes out. ${no}`,"not-found":"When a reader follows a link to a page that isn\u2019t there."}};function sc(e,t){return sm[e.id][t.id]??""}var om={subscribe:"mail",confirm:"circle-check",unsubscribe:"circle-minus",reading:"book"},im=o`<span class="set-rp-dot"></span>`;function nc(e,t,n){return o`<li><button type="button" class="set-rp-item${t.offPath?" off":""}" data-journey="${e.id}" data-state="${t.id}" aria-current="false" title="${sc(e,t)}"><span class="set-rp-mark" aria-hidden="true">${n}</span>${t.label}</button></li>`}function rm(){return o`${Fn.map(e=>{let t=e.states,n=e.flow==="steps";return o`<div class="set-rp-journey" data-journey="${e.id}">
724
+ <h3 class="set-rp-jhead" id="rpJourney-${e.id}">${O(om[e.id])}${e.label}</h3>
726
725
  <ul class="set-rp-list${n?" steps":""}" aria-labelledby="rpJourney-${e.id}">
727
- ${t.filter(s=>!s.offPath).map((s,i)=>wl(e,s,n?String(i+1):up))}
726
+ ${t.filter(s=>!s.offPath).map((s,i)=>nc(e,s,n?String(i+1):im))}
728
727
  </ul>
729
728
  <ul class="set-rp-list" aria-label="${e.label}, off the main path">
730
- ${t.filter(s=>s.offPath).map(s=>wl(e,s,N("branch")))}
729
+ ${t.filter(s=>s.offPath).map(s=>nc(e,s,O("branch")))}
731
730
  </ul>
732
- </div>`})}`}function mp(){return o`<select id="rpSelect" aria-label="Reader page">${Hn.map(e=>{let t=e.states,n=0;return o`<optgroup label="${e.label}">${t.map(s=>{let i=e.flow==="steps"&&!s.offPath?`${++n}. `:"";return o`<option value="${e.id}/${s.id}">${i}${s.label}</option>`})}</optgroup>`})}</select>`}function Sl(e){return o`
731
+ </div>`})}`}function am(){return o`<select id="rpSelect" aria-label="Reader page">${Fn.map(e=>{let t=e.states,n=0;return o`<optgroup label="${e.label}">${t.map(s=>{let i=e.flow==="steps"&&!s.offPath?`${++n}. `:"";return o`<option value="${e.id}/${s.id}">${i}${s.label}</option>`})}</optgroup>`})}</select>`}function oc(e){return o`
733
732
  <section class="set-sec set-rp-sec" id="readerPages">
734
733
  ${e}
735
734
  <p class="set-lede">Every page a reader can land on, exactly as they see it, with your publication’s identity and sample values. Nothing here changes a page; it shows the ones that are hard to reach by hand.</p>
736
735
  <div class="set-card set-rp">
737
- <nav class="set-rp-nav" aria-label="Reader pages">${pp()}</nav>
738
- <div class="set-rp-pick">${mp()}</div>
736
+ <nav class="set-rp-nav" aria-label="Reader pages">${rm()}</nav>
737
+ <div class="set-rp-pick">${am()}</div>
739
738
  <div class="set-rp-main">
740
739
  <div class="set-rp-top">
741
740
  <div>
@@ -743,8 +742,8 @@
743
742
  <p class="set-rp-note" id="rpNote"></p>
744
743
  </div>
745
744
  <span class="set-wtog" id="rpWidth" role="group" aria-label="Preview width">
746
- <button type="button" class="wtog-btn" data-width="desktop" aria-pressed="true">${N("desktop")}Desktop</button>
747
- <button type="button" class="wtog-btn" data-width="phone" aria-pressed="false">${N("phone")}Phone</button>
745
+ <button type="button" class="wtog-btn" data-width="desktop" aria-pressed="true">${O("desktop")}Desktop</button>
746
+ <button type="button" class="wtog-btn" data-width="phone" aria-pressed="false">${O("phone")}Phone</button>
748
747
  </span>
749
748
  </div>
750
749
  <div class="set-rp-at"><span class="mono" id="rpAt"></span><span>Sample · links and forms do nothing</span></div>
@@ -754,7 +753,7 @@
754
753
  </div>
755
754
  </div>
756
755
  </div>
757
- </section>`}function fp(e,t){return`${e.base==="app"?t.app_origin:`${t.archive_origin}${t.archive_base_path}`}${e.path}`.replace(/^https?:\/\//,"")}function $l(e,t,n){let s=c(".set-rp-nav",e),i=c("#rpSelect",e),a=c("#rpWidth",e),r=c("#rpStage",e),l=c("#rpFrame",e),d=c("#rpError",e),u=Hn[0],f=u.states[0],S="desktop",b=0,p=null;Pt(n,()=>p?.disconnect());let v=()=>{for(let H of I(".set-rp-item",s)){let T=H.dataset.journey===u.id&&H.dataset.state===f.id;H.setAttribute("aria-current",T?"true":"false")}for(let H of I(".set-rp-journey",s))H.classList.toggle("current",H.dataset.journey===u.id);i.value=`${u.id}/${f.id}`,c("#rpJourney",e).textContent=u.label,c("#rpState",e).textContent=f.label,h(c("#rpNote",e),cp[u.id]),c("#rpAt",e).textContent=fp(f.at,t)},x=()=>{let H=l.contentDocument?.body?.scrollHeight;H&&(l.style.height=`${H}px`)},M=async()=>{let H=++b;try{let T=await Mt(yl(u.id,f.id),{signal:n});if(H!==b||n.aborted)return;d.hidden=!0,r.hidden=!1,l.srcdoc=Ls(T)}catch(T){if(H!==b||n.aborted)return;l.srcdoc="",r.hidden=!0,d.textContent=`Couldn\u2019t load this page: ${F(T)}`,d.hidden=!1}},A=(H,T)=>{let m=Hn.find(U=>U.id===H),C=(m?.states??[]).find(U=>U.id===T);!m||!C||m===u&&C===f||(u=m,f=C,v(),M())};return l.onload=()=>{let H=l.contentDocument;!H||n.aborted||(H.addEventListener("click",T=>{T.target?.closest?.("a[href], area[href]")&&T.preventDefault()}),p?.disconnect(),x(),H.body&&typeof ResizeObserver<"u"&&(p=new ResizeObserver(x),p.observe(H.body)))},s.addEventListener("click",H=>{let T=H.target.closest(".set-rp-item");A(T?.dataset.journey,T?.dataset.state)}),i.addEventListener("change",()=>{let[H,T]=i.value.split("/");A(H,T)}),a.addEventListener("click",H=>{let m=H.target.closest("button[data-width]")?.dataset.width;if(!(m!=="desktop"&&m!=="phone"||m===S)){S=m;for(let y of I("button",a))y.setAttribute("aria-pressed",String(y.dataset.width===m));r.classList.toggle("phone",m==="phone")}}),v(),M(),{refresh:()=>{M()}}}function xl(e){return e?`Subscribe to ${e}`:"Subscribe"}function hp(e,t,n){let s=X(xl(t)),i=`${X(n)}/subscribe`;return e==="styled"?`<form action="${i}" method="post" style="max-width:460px;font:16px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif">
756
+ </section>`}function lm(e,t){return`${e.base==="app"?t.app_origin:`${t.archive_origin}${t.archive_base_path}`}${e.path}`.replace(/^https?:\/\//,"")}function ic(e,t,n){let s=c(".set-rp-nav",e),i=c("#rpSelect",e),r=c("#rpWidth",e),a=c("#rpStage",e),l=c("#rpFrame",e),d=c("#rpError",e),u=Fn[0],m=u.states[0],v="desktop",f=0,p=null;Nt(n,()=>p?.disconnect());let S=()=>{for(let A of N(".set-rp-item",s)){let H=A.dataset.journey===u.id&&A.dataset.state===m.id;A.setAttribute("aria-current",H?"true":"false")}for(let A of N(".set-rp-journey",s))A.classList.toggle("current",A.dataset.journey===u.id);i.value=`${u.id}/${m.id}`,c("#rpJourney",e).textContent=u.label,c("#rpState",e).textContent=m.label,c("#rpNote",e).textContent=sc(u,m),c("#rpAt",e).textContent=lm(m.at,t)},$=()=>{let A=l.contentDocument?.body?.scrollHeight;A&&(l.style.height=`${A}px`)},M=async()=>{let A=++f;try{let H=await Ot(tc(u.id,m.id),{signal:n});if(A!==f||n.aborted)return;d.hidden=!0,a.hidden=!1,l.srcdoc=Bs(H)}catch(H){if(A!==f||n.aborted)return;l.srcdoc="",a.hidden=!0,d.textContent=`Couldn\u2019t load this page: ${V(H)}`,d.hidden=!1}},P=(A,H)=>{let y=Fn.find(D=>D.id===A),T=(y?.states??[]).find(D=>D.id===H);!y||!T||y===u&&T===m||(u=y,m=T,S(),M())};return l.onload=()=>{let A=l.contentDocument;!A||n.aborted||(A.addEventListener("click",H=>{H.target?.closest?.("a[href], area[href]")&&H.preventDefault()}),p?.disconnect(),$(),A.body&&typeof ResizeObserver<"u"&&(p=new ResizeObserver($),p.observe(A.body)))},s.addEventListener("click",A=>{let H=A.target.closest(".set-rp-item");P(H?.dataset.journey,H?.dataset.state)}),i.addEventListener("change",()=>{let[A,H]=i.value.split("/");P(A,H)}),r.addEventListener("click",A=>{let y=A.target.closest("button[data-width]")?.dataset.width;if(!(y!=="desktop"&&y!=="phone"||y===v)){v=y;for(let w of N("button",r))w.setAttribute("aria-pressed",String(w.dataset.width===y));a.classList.toggle("phone",y==="phone")}}),S(),M(),{refresh:()=>{M()}}}function ac(e){return e?`Subscribe to ${e}`:"Subscribe"}function cm(e,t,n){let s=X(ac(t)),i=`${X(n)}/subscribe`;return e==="styled"?`<form action="${i}" method="post" style="max-width:460px;font:16px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif">
758
757
  <div style="font:600 22px/1.2 Georgia,'Times New Roman',serif;letter-spacing:-0.01em;margin-bottom:12px">${s}</div>
759
758
  <div style="display:flex;gap:10px;flex-wrap:wrap">
760
759
  <input type="email" name="email" required placeholder="you@example.com" aria-label="Email address" style="flex:1 1 220px;padding:11px 13px;border:1px solid #d6d3cc;border-radius:9px;background:#fff;color:#1b1a17;font:inherit">
@@ -767,14 +766,14 @@
767
766
  <input type="email" name="email" placeholder="you@example.com" required>
768
767
  </label>
769
768
  <button type="submit">Subscribe</button>
770
- </form>`}function bp(e,t){let n=xl(t);return e==="styled"?o`<form class="set-pf-styled"><span class="l">${n}</span><div class="rowf"><input type="email" placeholder="you@example.com" disabled><button type="button" class="sub-btn" tabindex="-1">Subscribe</button></div><p class="set-pf-fine">We’ll email you a link to confirm. Unsubscribe anytime.</p></form>`:o`<form class="set-pf-plain"><label>${n} <input type="email" placeholder="you@example.com" disabled></label> <button type="button" tabindex="-1">Subscribe</button></form>`}function kl(e){return e.data.deployment.app_origin||location.origin}function gp(e){return e?"A public page with your publication\u2019s name and a sign-up form ready to go.":"A public page with a sign-up form ready to go."}function El(e,t,n,s,i=null){return o`<div class="set-way"><div class="set-way-head"><div class="set-way-name"><h3 class="set-way-title">${N(e)}${t}</h3><p class="set-way-line">${n}</p></div>${i}</div>${s}</div>`}function _l(e){let t=`${kl(e)}/subscribe`;return o`
769
+ </form>`}function dm(e,t){let n=ac(t);return e==="styled"?o`<form class="set-pf-styled"><span class="l">${n}</span><div class="rowf"><input type="email" placeholder="you@example.com" disabled><button type="button" class="sub-btn" tabindex="-1">Subscribe</button></div><p class="set-pf-fine">We’ll email you a link to confirm. Unsubscribe anytime.</p></form>`:o`<form class="set-pf-plain"><label>${n} <input type="email" placeholder="you@example.com" disabled></label> <button type="button" tabindex="-1">Subscribe</button></form>`}function lc(e){return e.data.deployment.app_origin||location.origin}function um(e){return e?"A public page with your publication\u2019s name and a sign-up form ready to go.":"A public page with a sign-up form ready to go."}function rc(e,t,n,s,i=null){return o`<div class="set-way"><div class="set-way-head"><div class="set-way-name"><h3 class="set-way-title">${O(e)}${t}</h3><p class="set-way-line">${n}</p></div>${i}</div>${s}</div>`}function cc(e){let t=`${lc(e)}/subscribe`;return o`
771
770
  <section class="set-sec set-sec-subscribe">
772
- ${we("Ways to subscribe",ye("copyout","Copy-out"))}
771
+ ${Se("Ways to subscribe",we("copyout","Copy-out"))}
773
772
  <p class="set-lede">Two ways for readers to join your list. Either way, a reader is added only once they confirm by email.</p>
774
773
  ${e.data.deployment.provider==="none"?o`<div class="health amber set-sub-not-connected" role="status"><span class="health-dot">⚠️</span><div><span>No email provider connected, so signups aren’t open yet: the page below says so, and the form takes no address. ${Ae()} to open signups.</span></div></div>`:null}
775
774
  <div class="set-card">
776
- ${El("link","Share the page",o`<span id="subscribePageLine"></span>`,o`<div class="set-way-body set-way-addr"><code class="set-addr">${t}</code>${yn(t,"Copy the subscribe page\u2019s address")}<a class="ghost-link" href="${t}" target="_blank" rel="noopener">Open&nbsp;↗</a></div>`)}
777
- ${El("code","Embed a form",o`Put a sign-up form on another site you own.`,o`<div class="set-embed">
775
+ ${rc("link","Share the page",o`<span id="subscribePageLine"></span>`,o`<div class="set-way-body set-way-addr"><code class="set-addr">${t}</code>${_n(t,"Copy the subscribe page\u2019s address")}<a class="ghost-link" href="${t}" target="_blank" rel="noopener">Open&nbsp;↗</a></div>`)}
776
+ ${rc("code","Embed a form",o`Put a sign-up form on another site you own.`,o`<div class="set-embed">
778
777
  <div class="set-embed-preview" id="embedPreview"></div>
779
778
  <pre class="set-embed-code"><code id="embedCode"></code></pre>
780
779
  </div>
@@ -783,30 +782,30 @@
783
782
  <button type="button" class="wtog-btn" data-embed="plain" aria-pressed="false">Plain</button>
784
783
  </span>`)}
785
784
  </div>
786
- </section>`}function vp(e,t){return o`<button type="button" class="secondary set-embed-copy" data-copy="${t}" data-copy-word="Copy HTML" aria-label="Copy HTML, ${e==="styled"?"Styled":"Plain"} form">${Te(!1,"Copy HTML")}</button>`}function Tl(e,t){let n=kl(t),s=c("#embedCode",e),i=c("#embedCopy",e),a=c("#embedPreview",e),r=c("#subscribePageLine",e),l="styled",d=()=>t.state.name||t.fromDisplay,u=()=>{let b=hp(l,d(),n);s.textContent=b,h(i,vp(l,b)),h(a,bp(l,d())),r.textContent=gp(d())},f=I("[data-embed]",e);for(let b of f)b.onclick=()=>{l=b.dataset.embed==="styled"?"styled":"plain";for(let p of f)p.setAttribute("aria-pressed",String(p.dataset.embed===l));u()};je(c(".set-sec-subscribe",e)),u();let S=d();return{repaint(){d()!==S&&(S=d(),u())}}}function Pn(e,t){return o`<div class="set-group" data-group="${e}">${t}</div>`}function ri(e){return{name:e.name,tagline:e.tagline,address:e.address,recipients:[...e.recipients],confirmation:{...e.confirmation},notifyTo:e.notifyTo}}var yp=(e,t)=>e.length===t.length&&e.every((n,s)=>n===t[s]),wp=(e,t)=>e.subject===t.subject&&e.body===t.body&&e.button_label===t.button_label&&e.reassurance===t.reassurance;async function ai(e,t){se(t,"Settings"),h(e,o`<div class="settings"><div class="page-head"><h1>Settings</h1><p class="set-lede set-page-lede">Your publication’s identity, the ways readers subscribe and the pages they land on, the email each post is sent inside, and where Kestrel tells you about your sends. Facts set when Kestrel was deployed come last, read-only.</p></div><div id="settingsBody" class="muted">Loading…</div></div>`);let n=c("#settingsBody",e),s;try{s=await R("/api/settings",{signal:t})}catch(m){oe(n,at(m),()=>ee(ai));return}let i=s.settings,a=i.publication,r=i.confirmation_email,l={name:a.name||"",tagline:a.tagline||"",address:a.address||"",logoUrl:a.logo_url||"",recipients:[...i.test_recipients||[]],confirmation:{subject:r.subject||"",body:r.body||"",button_label:r.button_label||"",reassurance:r.reassurance||""},notifyTo:i.notifications.to||""},d=ri(l),u=po(s.deployment.from_address),f=()=>l.name!==d.name||l.tagline!==d.tagline||l.address!==d.address||!yp(l.recipients,d.recipients)||!wp(l.confirmation,d.confirmation)||l.notifyTo!==d.notifyTo,S=[],b=Bs.attach({onSave:H,onDiscard:T},t),p=()=>{},v={data:s,state:l,saved:()=>d,fromDisplay:u,fromName:u||"Your publication",changed(){for(let m of S)m.repaint?.();b.setDirty(f())},applySaved(m){Q.appConfig={...s,settings:m},Xn(),p()}};h(n,o`
787
- ${Pn("publication",[cl(v)])}
788
- ${Pn("readers",[_l(v),el(v),Sl(we("Reader pages",ye("preview","Preview")))])}
789
- ${Pn("emails",[ul(v),ml()])}
790
- ${Pn("you",[gl(v)])}
791
- ${Pn("deploy",[nl(v),sl(v)])}
792
- `),S.push(dl(n,v,t),Tl(n,v),tl(n,v),pl(n,v),fl(n,v),vl(n,v)),Us(n,s.in_use,t),p=$l(n,s.deployment,t).refresh;let M=null,A=()=>{M?.(),M=null};async function H(){A();try{let m={publication:{name:l.name,tagline:l.tagline,address:l.address},test_recipients:l.recipients,confirmation_email:l.confirmation,notifications:{to:l.notifyTo}},y=await _t(U=>R("/api/settings",{method:"PUT",json:U?{...m,remake:U}:m}),Cn("Save","Saving"),t);if(!y)return;let C=y.settings;l.name=C.publication.name,l.tagline=C.publication.tagline,l.address=C.publication.address,l.recipients=[...C.test_recipients],l.confirmation={...C.confirmation_email},l.notifyTo=C.notifications.to,d=ri(l);for(let U of S)U.reset?.();v.applySaved(C),v.changed(),O(en("Settings saved",y.remade))}catch(m){let y=m instanceof te?$p(e,m.field):null;y&&m instanceof te?(M=Ne(y,at(m)),y.focus(),b.showError("Not saved: fix the field marked above.")):b.showError(at(m))}}function T(){A(),Object.assign(l,ri(d));for(let m of S)m.reset?.();v.changed()}v.changed()}var Sp={"publication.name":"#setName","publication.tagline":"#setTagline","publication.address":"#setAddress",test_recipients:"#recipInput","notifications.to":"#notifyTo","confirmation_email.subject":"#ceSubject","confirmation_email.body":"#ceMessage","confirmation_email.button_label":"#ceButton","confirmation_email.reassurance":"#ceFooter"};function $p(e,t){let n=t?Sp[t]:void 0,s=n?e.querySelector(n):null;return(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement)&&!s.closest("[hidden]")?s:null}var Ep="kestrel-subscribers/1",Mn="kestrel-subscribers/2",xp=[Ep,Mn],kp=["subscribed","pending","unsubscribed","none"],li=["double","single","unknown"],_p=["bounce","manual"];var Tp=["reader","publisher","complaint","erased"],Ll=["subscribed","unsubscribed","bounced"],Lp={maxRows:1e4,maxRowsFree:1e3,maxBodyBytes:10*1024*1024,maxEvidenceBytes:500};var Rl=[{name:"email",required:!0,values:null,takes:"an email address; trimmed and lowercased before it is matched",meaning:"The address. An invalid one is still a row, counted as invalid and reported, never dropped."},{name:"status",required:!0,values:kp,takes:"one of the values",meaning:"The consent claim. `none` is a known address with no consent claim, present only to carry a suppression."},{name:"opt_in",required:!0,values:li,takes:"one of the values",meaning:"How consent was collected. `unknown` unless the source states it."},{name:"origin",required:!0,values:null,takes:"a short lowercase name (letters, digits, `.`, `_`, `-`, up to 40): `sendy`, `mailchimp`, `kestrel`, `unknown`",meaning:"Where consent was first collected, as the file claims it."},{name:"unsubscribe_cause",required:!1,values:Tp,takes:"one of the values, or empty; only on an `unsubscribed` row",meaning:"Why the person left: their own unsubscribe (`reader`), the publisher on their request (`publisher`), a complaint about the mail (`complaint`), or an erasure at their request (`erased`), which is recorded with the address alone. Empty when the source doesn\u2019t say, recorded as having left elsewhere. Version 2 only."},{name:"suppression",required:!1,values:_p,takes:"one of the values, or empty",meaning:"A suppression on top of `status`, the sender\u2019s side: the address bounced, or was blocked by hand. In version 1 it also took `complaint`, read as an `unsubscribed` row whose cause is `complaint`, and `erased`, read as one whose cause is `erased`."},{name:"subscribed_at",required:!1,values:null,takes:"a UTC ISO-8601 instant with its zone (`2024-03-01T09:30:00Z`), or empty",meaning:"When the person subscribed, if the source states it."},{name:"confirmed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the person confirmed, if the source states it."},{name:"unsubscribed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the person left, if the source states it. A reader who confirmed here after it stays confirmed."},{name:"suppressed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the address was suppressed, if the source states it."},{name:"evidence",required:!1,values:null,takes:`a JSON object of at most ${Lp.maxEvidenceBytes} bytes, or empty`,meaning:"The source\u2019s consent-relevant columns, verbatim (a signup IP, a form name, a confirmation time). Nothing reads it to decide anything: it is the proof of consent and the audit trail of a conversion."},{name:"format",required:!1,values:xp,takes:"the format\u2019s name and version, or empty",meaning:"The version the row is written in. A row without it may use either version\u2019s values, which every version reads alike; a version this release doesn\u2019t know is refused by name."}],eS=new Set(Rl.map(e=>e.name));var Rp=/^[=+\-@\t\r]/;function Cp(e){return Rp.test(e)?`'${e}`:e}function Ap(e){let t=Cp(e);return/[",\r\n]/.test(t)||t!==t.trim()?`"${t.replace(/"/g,'""')}"`:t}function ci(e){return`${e.map(t=>t.map(Ap).join(",")).join(`\r
785
+ </section>`}function pm(e,t){return o`<button type="button" class="secondary set-embed-copy" data-copy="${t}" data-copy-word="Copy HTML" aria-label="Copy HTML, ${e==="styled"?"Styled":"Plain"} form">${Te(!1,"Copy HTML")}</button>`}function dc(e,t){let n=lc(t),s=c("#embedCode",e),i=c("#embedCopy",e),r=c("#embedPreview",e),a=c("#subscribePageLine",e),l="styled",d=()=>t.state.name||t.fromDisplay,u=()=>{let f=cm(l,d(),n);s.textContent=f,h(i,pm(l,f)),h(r,dm(l,d())),a.textContent=um(d())},m=N("[data-embed]",e);for(let f of m)f.onclick=()=>{l=f.dataset.embed==="styled"?"styled":"plain";for(let p of m)p.setAttribute("aria-pressed",String(p.dataset.embed===l));u()};We(c(".set-sec-subscribe",e)),u();let v=d();return{repaint(){d()!==v&&(v=d(),u())}}}function qn(e,t){return o`<div class="set-group" data-group="${e}">${t}</div>`}function Ei(e){return{name:e.name,tagline:e.tagline,address:e.address,recipients:[...e.recipients],confirmation:{...e.confirmation},notifyTo:[...e.notifyTo]}}var uc=(e,t)=>e.length===t.length&&e.every((n,s)=>n===t[s]),mm=(e,t)=>e.subject===t.subject&&e.body===t.body&&e.button_label===t.button_label&&e.reassurance===t.reassurance;async function ki(e,t){ie(t,"Settings"),h(e,o`<div class="settings"><div class="page-head"><h1>Settings</h1><p class="set-lede set-page-lede">Your publication’s identity, the ways readers subscribe and the pages they land on, the email each post is sent inside, and where Kestrel tells you about your sends. Facts set when Kestrel was deployed come last, read-only.</p></div><div id="settingsBody" class="muted">Loading…</div></div>`);let n=c("#settingsBody",e),s;try{s=await L("/api/settings",{signal:t})}catch(w){re(n,ut(w),()=>ee(ki));return}let i=await at(s.deployment,t),r=s.settings,a=r.publication,l=r.confirmation_email,d={name:a.name||"",tagline:a.tagline||"",address:a.address||"",logoUrl:a.logo_url||"",recipients:[...r.test_recipients||[]],confirmation:{subject:l.subject||"",body:l.body||"",button_label:l.button_label||"",reassurance:l.reassurance||""},notifyTo:[...r.notifications.to]},u=Ei(d),m=ko(s.deployment.from_address),v=()=>d.name!==u.name||d.tagline!==u.tagline||d.address!==u.address||!uc(d.recipients,u.recipients)||!mm(d.confirmation,u.confirmation)||!uc(d.notifyTo,u.notifyTo),f=[],p=zs.attach({onSave:H,onDiscard:y},t),S=()=>{},$={data:s,provider:i,state:d,saved:()=>u,fromDisplay:m,fromName:m||"Your publication",changed(){for(let w of f)w.repaint?.();p.setDirty(v())},applySaved(w){Y.appConfig={...s,settings:w},ls(),S()}};h(n,o`
786
+ ${qn("publication",[jl($)])}
787
+ ${qn("readers",[cc($),Pl($),oc(Se("Reader pages",we("preview","Preview")))])}
788
+ ${qn("emails",[Vl($),zl()])}
789
+ ${qn("you",[Xl($)])}
790
+ ${qn("deploy",[Il($),Nl($)])}
791
+ `),f.push(Wl(n,$,t),dc(n,$),Ml(n,$),Kl(n,$),Yl(n,$),ec(n,$)),Xs(n,s.in_use,t),S=ic(n,s.deployment,t).refresh;let P=null,A=()=>{P?.(),P=null};async function H(){A();try{let w={publication:{name:d.name,tagline:d.tagline,address:d.address},test_recipients:d.recipients,confirmation_email:d.confirmation,notifications:{to:d.notifyTo}},T=await Ct(R=>L("/api/settings",{method:"PUT",json:R?{...w,remake:R}:w}),Dn("Save","Saving"),t);if(!T)return;let D=T.settings;d.name=D.publication.name,d.tagline=D.publication.tagline,d.address=D.publication.address,d.recipients=[...D.test_recipients],d.confirmation={...D.confirmation_email},d.notifyTo=[...D.notifications.to],u=Ei(d);for(let R of f)R.reset?.();$.applySaved(D),$.changed(),U(sn("Settings saved",T.remade))}catch(w){let T=w instanceof te?hm(e,w.field):null;T&&w instanceof te?(P=qe(T,ut(w)),T.focus(),p.showError("Not saved: fix the field marked above.")):p.showError(ut(w))}}function y(){A(),Object.assign(d,Ei(u));for(let w of f)w.reset?.();$.changed()}$.changed()}var fm={"publication.name":"#setName","publication.tagline":"#setTagline","publication.address":"#setAddress",test_recipients:"#recipInput","notifications.to":"#notifyTo","confirmation_email.subject":"#ceSubject","confirmation_email.body":"#ceMessage","confirmation_email.button_label":"#ceButton","confirmation_email.reassurance":"#ceFooter"};function hm(e,t){let n=t?fm[t]:void 0,s=n?e.querySelector(n):null;return(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement)&&!s.closest("[hidden]")?s:null}var bm="kestrel-subscribers/1",jn="kestrel-subscribers/2",gm=[bm,jn],vm=["subscribed","pending","unsubscribed","none"],_i=["double","single","unknown"],ym=["bounce","manual"];var wm=["reader","publisher","complaint","erased"],pc=["subscribed","unsubscribed","bounced"],Sm={maxRows:1e4,maxRowsFree:1e3,maxBodyBytes:10*1024*1024,maxEvidenceBytes:500};var mc=[{name:"email",required:!0,values:null,takes:"an email address; trimmed and lowercased before it is matched",meaning:"The address. An invalid one is still a row, counted as invalid and reported, never dropped."},{name:"status",required:!0,values:vm,takes:"one of the values",meaning:"The consent claim. `none` is a known address with no consent claim, present only to carry a suppression."},{name:"opt_in",required:!0,values:_i,takes:"one of the values",meaning:"How consent was collected. `unknown` unless the source states it."},{name:"origin",required:!0,values:null,takes:"a short lowercase name (letters, digits, `.`, `_`, `-`, up to 40): `sendy`, `mailchimp`, `kestrel`, `unknown`",meaning:"Where consent was first collected, as the file claims it."},{name:"unsubscribe_cause",required:!1,values:wm,takes:"one of the values, or empty; only on an `unsubscribed` row",meaning:"Why the person left: their own unsubscribe (`reader`), the publisher on their request (`publisher`), a complaint about the mail (`complaint`), or an erasure at their request (`erased`), which is recorded with the address alone. Empty when the source doesn\u2019t say, recorded as having left elsewhere. Version 2 only."},{name:"suppression",required:!1,values:ym,takes:"one of the values, or empty",meaning:"A suppression on top of `status`, the sender\u2019s side: the address bounced, or was blocked by hand. In version 1 it also took `complaint`, read as an `unsubscribed` row whose cause is `complaint`, and `erased`, read as one whose cause is `erased`."},{name:"subscribed_at",required:!1,values:null,takes:"a UTC ISO-8601 instant with its zone (`2024-03-01T09:30:00Z`), or empty",meaning:"When the person subscribed, if the source states it."},{name:"confirmed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the person confirmed, if the source states it."},{name:"unsubscribed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the person left, if the source states it. A reader who confirmed here after it stays confirmed."},{name:"suppressed_at",required:!1,values:null,takes:"an instant with its zone, or empty",meaning:"When the address was suppressed, if the source states it."},{name:"evidence",required:!1,values:null,takes:`a JSON object of at most ${Sm.maxEvidenceBytes} bytes, or empty`,meaning:"The source\u2019s consent-relevant columns, verbatim (a signup IP, a form name, a confirmation time). Nothing reads it to decide anything: it is the proof of consent and the audit trail of a conversion."},{name:"format",required:!1,values:gm,takes:"the format\u2019s name and version, or empty",meaning:"The version the row is written in. A row without it may use either version\u2019s values, which every version reads alike; a version this release doesn\u2019t know is refused by name."}],h$=new Set(mc.map(e=>e.name));var $m=/^[=+\-@\t\r]/;function xm(e){return $m.test(e)?`'${e}`:e}function Em(e){let t=xm(e);return/[",\r\n]/.test(t)||t!==t.trim()?`"${t.replace(/"/g,'""')}"`:t}function Ti(e){return`${e.map(t=>t.map(Em).join(",")).join(`\r
793
792
  `)}\r
794
- `}function di(e){let t=Rl.map(n=>n.name);return ci([t,...e.map(n=>t.map(s=>n[s]??""))])}var ui=[{email:"ada@example.com",status:"subscribed",opt_in:"double",origin:"sendy",unsubscribe_cause:null,suppression:null,subscribed_at:"2024-03-01T09:30:00Z",confirmed_at:"2024-03-01T09:42:00Z",unsubscribed_at:null,suppressed_at:null,evidence:'{"signup_ip":"203.0.113.7","list":"Field Notes"}',format:Mn},{email:"grace@example.com",status:"subscribed",opt_in:"single",origin:"mailchimp",unsubscribe_cause:null,suppression:null,subscribed_at:"2023-11-12T16:05:00Z",confirmed_at:null,unsubscribed_at:null,suppressed_at:null,evidence:null,format:Mn},{email:"edsger@example.com",status:"unsubscribed",opt_in:"unknown",origin:"unknown",unsubscribe_cause:"reader",suppression:null,subscribed_at:null,confirmed_at:null,unsubscribed_at:"2025-01-20T08:00:00Z",suppressed_at:null,evidence:null,format:Mn},{email:"bounced@example.com",status:"none",opt_in:"unknown",origin:"unknown",unsubscribe_cause:null,suppression:"bounce",subscribed_at:null,confirmed_at:null,unsubscribed_at:null,suppressed_at:"2025-02-02T12:00:00Z",evidence:null,format:Mn}],tS=di(ui),pi=`ada@example.com\r
793
+ `}function Li(e){let t=mc.map(n=>n.name);return Ti([t,...e.map(n=>t.map(s=>n[s]??""))])}var Ri=[{email:"ada@example.com",status:"subscribed",opt_in:"double",origin:"sendy",unsubscribe_cause:null,suppression:null,subscribed_at:"2024-03-01T09:30:00Z",confirmed_at:"2024-03-01T09:42:00Z",unsubscribed_at:null,suppressed_at:null,evidence:'{"signup_ip":"203.0.113.7","list":"Field Notes"}',format:jn},{email:"grace@example.com",status:"subscribed",opt_in:"single",origin:"mailchimp",unsubscribe_cause:null,suppression:null,subscribed_at:"2023-11-12T16:05:00Z",confirmed_at:null,unsubscribed_at:null,suppressed_at:null,evidence:null,format:jn},{email:"edsger@example.com",status:"unsubscribed",opt_in:"unknown",origin:"unknown",unsubscribe_cause:"reader",suppression:null,subscribed_at:null,confirmed_at:null,unsubscribed_at:"2025-01-20T08:00:00Z",suppressed_at:null,evidence:null,format:jn},{email:"bounced@example.com",status:"none",opt_in:"unknown",origin:"unknown",unsubscribe_cause:null,suppression:"bounce",subscribed_at:null,confirmed_at:null,unsubscribed_at:null,suppressed_at:"2025-02-02T12:00:00Z",evidence:null,format:jn}],b$=Li(Ri),Ci=`ada@example.com\r
795
794
  grace@example.com\r
796
795
  linus@example.com\r
797
- `,Cl="kestrel-import-example.csv",mi="kestrel-import-example.txt";var Hp={buttondown:"Buttondown",convertkit:"ConvertKit",kit:"Kit",kestrel:"Kestrel",mailchimp:"Mailchimp",mailerlite:"MailerLite",sendy:"Sendy",substack:"Substack",beehiiv:"beehiiv",ghost:"Ghost"};function In(e){return e===null||e===""||e==="unknown"?null:Hp[e]??e.charAt(0).toUpperCase()+e.slice(1)}function Nn(e){return e===null||e==="unknown"?"opt-in unknown":`${e} opt-in`}function Al(e){return e.import_id!==null?`Imported \xB7 ${[In(e.origin),Nn(e.opt_in)].filter(Boolean).join(", ")}`:e.confirmed_at!==null?"Double opt-in":null}function Hl(e){if(!e)return null;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function js(e){return e.principal.kind==="service"?"a service token":Jt(e.principal.email,e.principal.client)??"you"}var Pl=(e,t,n)=>`${e.toLocaleString("en-US")} ${e===1?t:n}`,Pp=[{outcome:"added_confirmed",one:"address added as a confirmed subscriber",many:"addresses added as confirmed subscribers"},{outcome:"confirmed_pending",one:"pending subscriber here confirmed",many:"pending subscribers here confirmed"},{outcome:"unsubscribed",one:"subscriber here unsubscribed",many:"subscribers here unsubscribed"},{outcome:"erased",one:"subscriber here erased, as the file says: only the address is kept, and past sends show an erased recipient",many:"subscribers here erased, as the file says: only their addresses are kept, and past sends show an erased recipient"},{outcome:"added_unsubscribed",one:"address recorded as having left (unsubscribed), so the list remembers them",many:"addresses recorded as having left (unsubscribed), so the list remembers them"},{outcome:"suppressed",one:"address suppressed as the file says (bounced or blocked), so it\u2019s never mailed",many:"addresses suppressed as the file says (bounced or blocked), so they\u2019re never mailed"},{outcome:"unchanged",one:"address already here as the file says, so it\u2019s unchanged",many:"addresses already here as the file says, so they\u2019re unchanged"},{outcome:"left_out",one:"row still pending, or with no status, left out, since an import sends no email",many:"rows still pending, or with no status, left out, since an import sends no email"},{outcome:"invalid",one:"row isn\u2019t a valid address",many:"rows aren\u2019t valid addresses"},{outcome:"merged",one:"row repeats an address earlier in the file, and is folded into it",many:"rows repeat an address earlier in the file, and are folded into it"},{outcome:"kept_suppressed",one:"address is suppressed here, so it isn\u2019t imported",many:"addresses are suppressed here, so they aren\u2019t imported",kept:!0},{outcome:"kept_unsubscribed",one:"reader unsubscribed here, and stays unsubscribed",many:"readers unsubscribed here, and stay unsubscribed",kept:!0},{outcome:"kept_confirmed_newer",one:"reader confirmed here after the file says they left, and stays confirmed",many:"readers confirmed here after the file says they left, and stay confirmed",kept:!0}];function fi(e){return Pp.filter(t=>e[t.outcome]>0).map(t=>({outcome:t.outcome,count:e[t.outcome],text:Pl(e[t.outcome],t.one,t.many),kept:t.kept===!0}))}function Ml(e){return e.added_confirmed+e.confirmed_pending}function hi(e,t){let n=t-e.suppressed;return n>0?`${Pl(n,"of the addresses above also gains","of the addresses above also gain")} a suppression, so ${n===1?"it\u2019s":"they\u2019re"} never mailed.`:null}function Il(e){let t=li.filter(s=>(e.opt_in[s]??0)>0).map(s=>`${e.opt_in[s].toLocaleString("en-US")} ${Nn(s)}`).join(", "),n=Object.entries(e.origin).filter(([,s])=>s>0).sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s,i])=>`${In(s)??"unknown"} ${i.toLocaleString("en-US")}`).join(", ");return{optIn:t,origin:n}}var tn={added_confirmed:"Imported as subscribed",confirmed_pending:"Imported as subscribed",unsubscribed:"Unsubscribed",erased:"Erased",added_unsubscribed:"Recorded as having left",suppressed:"Suppressed",unchanged:"Unchanged",left_out:"Left out",invalid:"Invalid",merged:"Folded into an earlier row",kept_suppressed:"Already suppressed here",kept_unsubscribed:"Kept unsubscribed",kept_confirmed_newer:"Kept confirmed"};function Nl(e,t,n){let s=new Map(e.map(r=>[r.row,r])),i=new Map(t.map(r=>[r.row,r])),a=new Map;for(let r of new Set([...s.keys(),...i.keys()])){let l=s.get(r),d=i.get(r),u=l?tn[l.outcome]:tn.added_confirmed,f=d?tn[d.outcome]:tn.added_confirmed;u!==f&&a.set(r,{row:r,email:(d??l)?.email??"",planned:u,applied:f})}for(let r of n){let l=tn[r.planned],d=tn[r.applied];!a.has(r.row)&&l!==d&&a.set(r.row,{row:r.row,email:r.email,planned:l,applied:d})}return[...a.values()].sort((r,l)=>r.row-l.row)}function Bl(e){return ci([["row","email","outcome","suppression_added"],...e.map(t=>[String(t.row),t.email,t.outcome,t.suppression_added?"yes":"no"])])}var Ol="Please import my Sendy subscribers from ~/Downloads/sendy-export.csv into the newsletter.",Mp="Your list or its scheduled posts changed since this plan, so here is the plan again as things stand now. Review it, then import.",bi=["email","status","opt_in","origin","subscribed_at"],Ip={subscribed:"Subscribed",unsubscribed:"Unsubscribed",bounced:"Bounced"};async function vi(e,t){se(t,"Import subscribers"),h(e,o`<div class="imp">
796
+ `,fc="kestrel-import-example.csv",Ai="kestrel-import-example.txt";var km={buttondown:"Buttondown",convertkit:"ConvertKit",kit:"Kit",kestrel:"Kestrel",mailchimp:"Mailchimp",mailerlite:"MailerLite",sendy:"Sendy",substack:"Substack",beehiiv:"beehiiv",ghost:"Ghost"};function Wn(e){return e===null||e===""||e==="unknown"?null:km[e]??e.charAt(0).toUpperCase()+e.slice(1)}function Vn(e){return e===null||e==="unknown"?"opt-in unknown":`${e} opt-in`}function hc(e){return e.import_id!==null?`Imported \xB7 ${[Wn(e.origin),Vn(e.opt_in)].filter(Boolean).join(", ")}`:e.confirmed_at!==null?"Double opt-in":null}function bc(e){if(!e)return null;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function so(e){return e.principal.kind==="service"?"a service token":en(e.principal.email,e.principal.client)??"you"}var gc=(e,t,n)=>`${e.toLocaleString("en-US")} ${e===1?t:n}`,_m=[{outcome:"added_confirmed",one:"address added as a confirmed subscriber",many:"addresses added as confirmed subscribers"},{outcome:"confirmed_pending",one:"pending subscriber here confirmed",many:"pending subscribers here confirmed"},{outcome:"unsubscribed",one:"subscriber here unsubscribed",many:"subscribers here unsubscribed"},{outcome:"erased",one:"subscriber here erased, as the file says: only the address is kept, and past sends show an erased recipient",many:"subscribers here erased, as the file says: only their addresses are kept, and past sends show an erased recipient"},{outcome:"added_unsubscribed",one:"address recorded as having left (unsubscribed), so the list remembers them",many:"addresses recorded as having left (unsubscribed), so the list remembers them"},{outcome:"suppressed",one:"address suppressed as the file says (bounced or blocked), so it\u2019s never mailed",many:"addresses suppressed as the file says (bounced or blocked), so they\u2019re never mailed"},{outcome:"unchanged",one:"address already here as the file says, so it\u2019s unchanged",many:"addresses already here as the file says, so they\u2019re unchanged"},{outcome:"left_out",one:"row still pending, or with no status, left out, since an import sends no email",many:"rows still pending, or with no status, left out, since an import sends no email"},{outcome:"invalid",one:"row isn\u2019t a valid address",many:"rows aren\u2019t valid addresses"},{outcome:"merged",one:"row repeats an address earlier in the file, and is folded into it",many:"rows repeat an address earlier in the file, and are folded into it"},{outcome:"kept_suppressed",one:"address is suppressed here, so it isn\u2019t imported",many:"addresses are suppressed here, so they aren\u2019t imported",kept:!0},{outcome:"kept_unsubscribed",one:"reader unsubscribed here, and stays unsubscribed",many:"readers unsubscribed here, and stay unsubscribed",kept:!0},{outcome:"kept_confirmed_newer",one:"reader confirmed here after the file says they left, and stays confirmed",many:"readers confirmed here after the file says they left, and stay confirmed",kept:!0}];function Hi(e){return _m.filter(t=>e[t.outcome]>0).map(t=>({outcome:t.outcome,count:e[t.outcome],text:gc(e[t.outcome],t.one,t.many),kept:t.kept===!0}))}function vc(e){return e.added_confirmed+e.confirmed_pending}function Pi(e,t){let n=t-e.suppressed;return n>0?`${gc(n,"of the addresses above also gains","of the addresses above also gain")} a suppression, so ${n===1?"it\u2019s":"they\u2019re"} never mailed.`:null}function yc(e){let t=_i.filter(s=>(e.opt_in[s]??0)>0).map(s=>`${e.opt_in[s].toLocaleString("en-US")} ${Vn(s)}`).join(", "),n=Object.entries(e.origin).filter(([,s])=>s>0).sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s,i])=>`${Wn(s)??"unknown"} ${i.toLocaleString("en-US")}`).join(", ");return{optIn:t,origin:n}}var on={added_confirmed:"Imported as subscribed",confirmed_pending:"Imported as subscribed",unsubscribed:"Unsubscribed",erased:"Erased",added_unsubscribed:"Recorded as having left",suppressed:"Suppressed",unchanged:"Unchanged",left_out:"Left out",invalid:"Invalid",merged:"Folded into an earlier row",kept_suppressed:"Already suppressed here",kept_unsubscribed:"Kept unsubscribed",kept_confirmed_newer:"Kept confirmed"};function wc(e,t,n){let s=new Map(e.map(a=>[a.row,a])),i=new Map(t.map(a=>[a.row,a])),r=new Map;for(let a of new Set([...s.keys(),...i.keys()])){let l=s.get(a),d=i.get(a),u=l?on[l.outcome]:on.added_confirmed,m=d?on[d.outcome]:on.added_confirmed;u!==m&&r.set(a,{row:a,email:(d??l)?.email??"",planned:u,applied:m})}for(let a of n){let l=on[a.planned],d=on[a.applied];!r.has(a.row)&&l!==d&&r.set(a.row,{row:a.row,email:a.email,planned:l,applied:d})}return[...r.values()].sort((a,l)=>a.row-l.row)}function Sc(e){return Ti([["row","email","outcome","suppression_added"],...e.map(t=>[String(t.row),t.email,t.outcome,t.suppression_added?"yes":"no"])])}var $c="Please import my Sendy subscribers from ~/Downloads/sendy-export.csv into the newsletter.",Tm="Your list or its scheduled posts changed since this plan, so here is the plan again as things stand now. Review it, then import.",Mi=["email","status","opt_in","origin","subscribed_at"],Lm={subscribed:"Subscribed",unsubscribed:"Unsubscribed",bounced:"Bounced"};async function Ni(e,t){ie(t,"Import subscribers"),h(e,o`<div class="imp">
798
797
  <div class="editor-head"><a href="#/subscribers" class="back">← Subscribers</a></div>
799
798
  <div class="page-head"><h1>Import subscribers</h1><p class="set-lede" id="impLede">Nothing changes until you review what will happen and confirm.</p></div>
800
799
  <div id="impBody" class="muted">Loading…</div>
801
800
  <input type="file" id="impInput" accept=".csv,.txt,text/csv,text/plain" hidden>
802
- </div>`);let n=c("#impBody",e),s=c("#impInput",e);je(n);let i;try{i=await R("/api/imports/format",{signal:t})}catch(m){t.aborted||oe(n,F(m),()=>{ee(vi)});return}if(t.aborted)return;let a="full";function r(m){c("#impLede",e).hidden=!1;let y=i.limits.max_rows.toLocaleString("en-US");h(n,o`<section class="card imp-card">
801
+ </div>`);let n=c("#impBody",e),s=c("#impInput",e);We(n);let i;try{i=await L("/api/imports/format",{signal:t})}catch(y){t.aborted||re(n,V(y),()=>{ee(Ni)});return}if(t.aborted)return;let r="full";function a(y){c("#impLede",e).hidden=!1;let w=i.limits.max_rows.toLocaleString("en-US");h(n,o`<section class="card imp-card">
803
802
  <div class="imp-card-head"><h2>The file Kestrel reads</h2>
804
803
  <span class="set-wtog" role="group" aria-label="Which file">
805
- <button type="button" class="wtog-btn" data-sample="full" aria-pressed="${String(a==="full")}">Full list</button>
806
- <button type="button" class="wtog-btn" data-sample="plain" aria-pressed="${String(a==="plain")}">Plain list</button>
804
+ <button type="button" class="wtog-btn" data-sample="full" aria-pressed="${String(r==="full")}">Full list</button>
805
+ <button type="button" class="wtog-btn" data-sample="plain" aria-pressed="${String(r==="plain")}">Plain list</button>
807
806
  </span>
808
807
  </div>
809
- <div id="impSample">${a==="full"?l():d()}</div>
808
+ <div id="impSample">${r==="full"?l():d()}</div>
810
809
  </section>
811
810
  <section class="card imp-card imp-claude">
812
811
  <h2>Just ask Claude</h2>
@@ -814,119 +813,120 @@ linus@example.com\r
814
813
  ${u()}
815
814
  </section>
816
815
  <div class="imp-drop" id="impDrop">
817
- ${N("upload")}
816
+ ${O("upload")}
818
817
  <p class="imp-drop-line">Drop your file here, or</p>
819
- <button type="button" class="primary" id="impChoose" aria-describedby="impLimit${m?" impFileError":""}">Choose file</button>
820
- <p class="field-hint" id="impLimit">CSV or .txt, up to ${y} rows.${i.limits.max_rows_reason?o` ${i.limits.max_rows_reason}`:null}</p>
818
+ <button type="button" class="primary" id="impChoose" aria-describedby="impLimit${y?" impFileError":""}">Choose file</button>
819
+ <p class="field-hint" id="impLimit">CSV or .txt, up to ${w} rows.${i.limits.max_rows_reason?o` ${i.limits.max_rows_reason}`:null}</p>
821
820
  </div>
822
- ${m?o`<div class="imp-file-error"><div class="field-error" id="impFileError" role="alert"><span class="field-error-ico" aria-hidden="true">!</span><span>${m}</span></div>
823
- <p class="imp-text">Exported from another service? Claude can convert it for you. Ask Claude Code:</p>${u()}</div>`:null}`);for(let U of I("[data-sample]",n))U.onclick=()=>{a=U.dataset.sample==="plain"?"plain":"full";for(let J of I("[data-sample]",n))J.setAttribute("aria-pressed",String(J.dataset.sample===a));h(c("#impSample",n),a==="full"?l():d()),f()};f(),c("#impChoose",n).onclick=()=>s.click();let C=c("#impDrop",n);C.addEventListener("dragover",U=>{U.preventDefault(),C.classList.add("over")}),C.addEventListener("dragleave",()=>C.classList.remove("over")),C.addEventListener("drop",U=>{U.preventDefault(),C.classList.remove("over");let J=U.dataTransfer?.files[0];J&&S(J)})}function l(){let m=ui.slice(0,3),y=i.columns.filter(C=>!C.required&&!bi.includes(C.name)).map(C=>C.name);return o`<p class="imp-text">A CSV with a header row, one row per address. A row says what your old service recorded about each person; Kestrel decides what that means here.</p>
824
- <div class="table-wrap"><table class="imp-sample"><thead><tr>${bi.map(C=>o`<th><code>${C}</code></th>`)}</tr></thead>
825
- <tbody>${m.map(C=>o`<tr>${bi.map(U=>o`<td>${C[U]??""}</td>`)}</tr>`)}</tbody></table></div>
826
- <p class="field-hint">Optional columns: ${y.map((C,U)=>o`${U?", ":""}<code>${C}</code>`)}.</p>
821
+ ${y?o`<div class="imp-file-error"><div class="field-error" id="impFileError" role="alert"><span class="field-error-ico" aria-hidden="true">!</span><span>${y}</span></div>
822
+ <p class="imp-text">Exported from another service? Claude can convert it for you. Ask Claude Code:</p>${u()}</div>`:null}`);for(let D of N("[data-sample]",n))D.onclick=()=>{r=D.dataset.sample==="plain"?"plain":"full";for(let R of N("[data-sample]",n))R.setAttribute("aria-pressed",String(R.dataset.sample===r));h(c("#impSample",n),r==="full"?l():d()),m()};m(),c("#impChoose",n).onclick=()=>s.click();let T=c("#impDrop",n);T.addEventListener("dragover",D=>{D.preventDefault(),T.classList.add("over")}),T.addEventListener("dragleave",()=>T.classList.remove("over")),T.addEventListener("drop",D=>{D.preventDefault(),T.classList.remove("over");let R=D.dataTransfer?.files[0];R&&v(R)})}function l(){let y=Ri.slice(0,3),w=i.columns.filter(T=>!T.required&&!Mi.includes(T.name)).map(T=>T.name);return o`<p class="imp-text">A CSV with a header row, one row per address. A row says what your old service recorded about each person; Kestrel decides what that means here.</p>
823
+ <div class="table-wrap"><table class="imp-sample"><thead><tr>${Mi.map(T=>o`<th><code>${T}</code></th>`)}</tr></thead>
824
+ <tbody>${y.map(T=>o`<tr>${Mi.map(D=>o`<td>${T[D]??""}</td>`)}</tr>`)}</tbody></table></div>
825
+ <p class="field-hint">Optional columns: ${w.map((T,D)=>o`${D?", ":""}<code>${T}</code>`)}.</p>
827
826
  <div class="row imp-links"><button type="button" class="ghost" data-template="csv">Download example file (CSV)</button><a class="ghost-link" href="#/docs/your-list/the-file-format">Import format reference →</a></div>`}function d(){return o`<p class="imp-text">A <code>.txt</code> file with one address per line.</p>
828
- ${zt(mi,o`${pi.replace(/\r\n/g,`
829
- `).trim()}`,pi)}
827
+ ${Jt(Ai,o`${Ci.replace(/\r\n/g,`
828
+ `).trim()}`,Ci)}
830
829
  <p class="imp-text">Next you’ll say what they are: subscribed (the default), unsubscribed, or bounced.</p>
831
- <div class="row imp-links"><button type="button" class="ghost" data-template="txt">Download example file (.txt)</button></div>`}function u(){return zt("Prompt for Claude Code",o`${Ol}`,Ol)}function f(){for(let m of I("[data-template]",n))m.onclick=()=>G(m,null,async()=>{let y=m.dataset.template==="txt"?"txt":"csv";try{let C=await Qn(`/api/imports/template.${y}`);kt(C.text,C.filename??(y==="txt"?mi:Cl),y==="txt"?"text/plain":"text/csv")}catch(C){O(F(C))}})}s.onchange=()=>{let m=s.files?.[0];s.value="",m&&S(m)};async function S(m){let y=await m.text();if(t.aborted)return;let C={name:m.name,text:y},U=Np(C)?i.plain_list.default:null,J=n.querySelector("#impChoose, #impReplace"),z=await(J?G(J,"Reading\u2026",()=>b(C,U)):b(C,U));z!==null&&(p(z,C),c(".imp-file",n).focus())}async function b(m,y){try{return await R("/api/imports/plan",{method:"POST",json:y===null?{file:m}:{file:m,plain_list_status:y},signal:t})}catch(C){return t.aborted||(r(F(C)),c("#impChoose",n).focus()),null}}function p(m,y,C){let U=Ml(m.counts),J=fi(m.counts),z=Il(m.confirmed),q=hi(m.counts,m.suppressions_added),g=m.rows.length,E=m.file.kind==="txt"?"Plain list (.txt)":`CSV, ${i.format}`;h(n,o`<section class="card imp-card imp-file" tabindex="-1" aria-label="The file chosen and its plan">
830
+ <div class="row imp-links"><button type="button" class="ghost" data-template="txt">Download example file (.txt)</button></div>`}function u(){return Jt("Prompt for Claude Code",o`${$c}`,$c)}function m(){for(let y of N("[data-template]",n))y.onclick=()=>Z(y,null,async()=>{let w=y.dataset.template==="txt"?"txt":"csv";try{let T=await as(`/api/imports/template.${w}`);Rt(T.text,T.filename??(w==="txt"?Ai:fc),w==="txt"?"text/plain":"text/csv")}catch(T){U(V(T))}})}s.onchange=()=>{let y=s.files?.[0];s.value="",y&&v(y)};async function v(y){let w=await y.text();if(t.aborted)return;let T={name:y.name,text:w},D=Rm(T)?i.plain_list.default:null,R=n.querySelector("#impChoose, #impReplace"),F=await(R?Z(R,"Reading\u2026",()=>f(T,D)):f(T,D));F!==null&&(p(F,T),c(".imp-file",n).focus())}async function f(y,w){try{return await L("/api/imports/plan",{method:"POST",json:w===null?{file:y}:{file:y,plain_list_status:w},signal:t})}catch(T){return t.aborted||(a(V(T)),c("#impChoose",n).focus()),null}}function p(y,w,T){let D=vc(y.counts),R=Hi(y.counts),F=yc(y.confirmed),K=Pi(y.counts,y.suppressions_added),b=y.rows.length,E=y.file.kind==="txt"?"Plain list (.txt)":`CSV, ${i.format}`;h(n,o`<section class="card imp-card imp-file" tabindex="-1" aria-label="The file chosen and its plan">
832
831
  <div class="imp-file-row">
833
- <div><strong class="imp-file-name">${m.file.name}</strong><div class="muted">${E} · ${gi(m.file.rows)} · ${Bp(m.file.addresses)}</div></div>
832
+ <div><strong class="imp-file-name">${y.file.name}</strong><div class="muted">${E} · ${Ii(y.file.rows)} · ${Cm(y.file.addresses)}</div></div>
834
833
  <button type="button" class="ghost" id="impReplace">Replace file</button>
835
834
  </div>
836
- ${m.file.kind==="txt"?v(m.file.plain_list_status??i.plain_list.default):null}
835
+ ${y.file.kind==="txt"?S(y.file.plain_list_status??i.plain_list.default):null}
837
836
  </section>
838
837
  <section class="card imp-card">
839
838
  <h2>What will happen</h2>
840
- ${Ul(J,z,U)}
841
- ${q?o`<p class="imp-text">${q}</p>`:null}
842
- ${g>0?o`<div class="row imp-links"><button type="button" class="ghost" id="impNotImported">Download the ${gi(g)} not imported as subscribed (CSV)</button></div>`:null}
843
- ${m.workers_plan_advice?o`<p class="workers-plan" role="status">${m.workers_plan_advice}</p>`:null}
839
+ ${Ec(R,F,D)}
840
+ ${K?o`<p class="imp-text">${K}</p>`:null}
841
+ ${b>0?o`<div class="row imp-links"><button type="button" class="ghost" id="impNotImported">Download the ${Ii(b)} not imported as subscribed (CSV)</button></div>`:null}
842
+ ${y.workers_plan_advice?o`<p class="workers-plan" role="status">${y.workers_plan_advice}</p>`:null}
844
843
  </section>
845
844
  <section class="card imp-card imp-confirm">
846
845
  <h2>Confirm</h2>
847
- ${m.sends_growing.length>0?o`<p class="imp-text">A scheduled post goes to the list as it stands when it sends, so this import adds to its audience. Acknowledge each one.</p>
848
- ${m.sends_growing.map(D=>o`<label class="imp-check"><input type="checkbox" data-ack="${D.id}"><span>“${D.subject||"Untitled"}”, sending ${W(D.fire_at)}, goes to ${D.gains.toLocaleString("en-US")} more ${D.gains===1?"person":"people"}.</span></label>`)}`:null}
849
- ${m.attestation?o`<label class="imp-check"><input type="checkbox" id="impAttest"><span>${m.attestation.text}</span></label>
850
- <p class="field-hint imp-attest-hint">Only import people who asked to receive ${m.attestation.publication}. If you’re unsure about some, take them out of the file before importing.</p>`:null}
851
- ${m.attestation===null&&m.sends_growing.length===0?o`<p class="imp-text">Nobody is imported as a subscriber, so there’s nothing to attest.</p>`:null}
852
- ${C?Dl(C):null}
846
+ ${y.sends_growing.length>0?o`<p class="imp-text">A scheduled post goes to the list as it stands when it sends, so this import adds to its audience. Acknowledge each one.</p>
847
+ ${y.sends_growing.map(k=>o`<label class="imp-check"><input type="checkbox" data-ack="${k.id}"><span>“${k.subject||"Untitled"}”, sending ${j(k.fire_at)}, goes to ${k.gains.toLocaleString("en-US")} more ${k.gains===1?"person":"people"}.</span></label>`)}`:null}
848
+ ${y.attestation?o`<label class="imp-check"><input type="checkbox" id="impAttest"><span>${y.attestation.text}</span></label>
849
+ <p class="field-hint imp-attest-hint">Only import people who asked to receive ${y.attestation.publication}. If you’re unsure about some, take them out of the file before importing.</p>`:null}
850
+ ${y.attestation===null&&y.sends_growing.length===0?o`<p class="imp-text">Nobody is imported as a subscriber, so there’s nothing to attest.</p>`:null}
851
+ ${T?xc(T):null}
853
852
  <div class="actions imp-actions"><a class="ghost-link" href="#/subscribers">Cancel</a><button type="button" class="primary" id="impGo">Import</button></div>
854
- </section>`);let L=c("#impReplace",n);L.onclick=()=>s.click(),g>0&&(c("#impNotImported",n).onclick=()=>x(m.file.name,m.rows));let $=c("#impGo",n),_=I("[data-plain]",n),K=D=>{L.disabled=D;for(let ae of _)ae.disabled=D};for(let D of _)D.onclick=()=>{let ae=D.dataset.plain;ae!==m.file.plain_list_status&&($.disabled=!0,K(!0),(async()=>{let V=await b(y,ae);V&&!t.aborted&&(p(V,y),c(`[data-plain="${ae}"]`,n).focus())})())};$.onclick=()=>M(m,y,$,K)}function v(m){return o`<div class="imp-plain">
853
+ </section>`);let C=c("#impReplace",n);C.onclick=()=>s.click(),b>0&&(c("#impNotImported",n).onclick=()=>$(y.file.name,y.rows));let x=c("#impGo",n),W=N("[data-plain]",n),oe=k=>{C.disabled=k;for(let G of W)G.disabled=k};for(let k of W)k.onclick=()=>{let G=k.dataset.plain;G!==y.file.plain_list_status&&(x.disabled=!0,oe(!0),(async()=>{let q=await f(w,G);q&&!t.aborted&&(p(q,w),c(`[data-plain="${G}"]`,n).focus())})())};x.onclick=()=>M(y,w,x,oe)}function S(y){return o`<div class="imp-plain">
855
854
  <span class="imp-plain-label" id="impPlainLabel">These addresses are</span>
856
- <span class="set-wtog" role="group" aria-labelledby="impPlainLabel">${Ll.map(y=>o`<button type="button" class="wtog-btn" data-plain="${y}" aria-pressed="${String(y===m)}">${Ip[y]}</button>`)}</span>
855
+ <span class="set-wtog" role="group" aria-labelledby="impPlainLabel">${pc.map(w=>o`<button type="button" class="wtog-btn" data-plain="${w}" aria-pressed="${String(w===y)}">${Lm[w]}</button>`)}</span>
857
856
  <p class="field-hint">A plain list doesn’t say how each person joined, so it’s recorded as unknown.</p>
858
- </div>`}function x(m,y){let C=m.replace(/\.(csv|txt)$/i,"");kt(Bl(y),`${C}-not-imported.csv`,"text/csv")}async function M(m,y,C,U){n.querySelector(".imp-act-error")?.remove();let J=I("[data-ack]",n),z=n.querySelector("#impAttest");for(let q of J)if(!q.checked){A(q,"Tick this to acknowledge that this post will go to the people this import adds.");return}if(z&&!z.checked){A(z,"Tick this to attest that everyone you\u2019re importing as subscribed opted in.");return}U(!0),await G(C,"Importing\u2026",async()=>{try{let q=await R("/api/imports",{method:"POST",json:{file:y,plain_list_status:m.file.plain_list_status??void 0,plan_hash:m.plan_hash,...m.attestation?{attestation:{version:m.attestation.version,accepted:!0}}:{},acknowledge_sends:m.sends_growing.map(g=>g.id)}});t.aborted||T(q,m)}catch(q){if(t.aborted)return;if(q instanceof te&&q.code==="plan_stale"){let g=await b(y,m.file.plain_list_status);g&&!t.aborted&&(p(g,y,Mp),c(".imp-act-error",n).focus());return}H(F(q)),U(!1)}})}function A(m,y){Ne(m,y,{after:m.closest("label")??m}),m.focus()}function H(m){n.querySelector(".imp-act-error")?.remove();let y=document.createElement("div");h(y,Dl(m)),c(".imp-actions",n).before(...y.childNodes)}function T(m,y){c("#impLede",e).hidden=!0;let C=m.import,U=js(C),J=fi(m.counts),z=hi(m.counts,m.suppressions_added),q=m.replayed?[]:Nl(y.rows,m.rows,m.differed);h(n,o`<section class="card imp-card imp-done">
859
- <h2 id="impDoneHead" tabindex="-1">${m.replayed?"This import was already done":"Import done"}</h2>
860
- ${m.replayed?o`<p class="imp-text">This plan was already imported, so nothing was written again. Here is its record.</p>`:null}
861
- ${Ul(J,null,0)}
862
- ${z?o`<p class="imp-text">${z}</p>`:null}
857
+ </div>`}function $(y,w){let T=y.replace(/\.(csv|txt)$/i,"");Rt(Sc(w),`${T}-not-imported.csv`,"text/csv")}async function M(y,w,T,D){n.querySelector(".imp-act-error")?.remove();let R=N("[data-ack]",n),F=n.querySelector("#impAttest");for(let K of R)if(!K.checked){P(K,"Tick this to acknowledge that this post will go to the people this import adds.");return}if(F&&!F.checked){P(F,"Tick this to attest that everyone you\u2019re importing as subscribed opted in.");return}D(!0),await Z(T,"Importing\u2026",async()=>{try{let K=await L("/api/imports",{method:"POST",json:{file:w,plain_list_status:y.file.plain_list_status??void 0,plan_hash:y.plan_hash,...y.attestation?{attestation:{version:y.attestation.version,accepted:!0}}:{},acknowledge_sends:y.sends_growing.map(b=>b.id)}});t.aborted||H(K,y)}catch(K){if(t.aborted)return;if(K instanceof te&&K.code==="plan_stale"){let b=await f(w,y.file.plain_list_status);b&&!t.aborted&&(p(b,w,Tm),c(".imp-act-error",n).focus());return}A(V(K)),D(!1)}})}function P(y,w){qe(y,w,{after:y.closest("label")??y}),y.focus()}function A(y){n.querySelector(".imp-act-error")?.remove();let w=document.createElement("div");h(w,xc(y)),c(".imp-actions",n).before(...w.childNodes)}function H(y,w){c("#impLede",e).hidden=!0;let T=y.import,D=so(T),R=Hi(y.counts),F=Pi(y.counts,y.suppressions_added),K=y.replayed?[]:wc(w.rows,y.rows,y.differed);h(n,o`<section class="card imp-card imp-done">
858
+ <h2 id="impDoneHead" tabindex="-1">${y.replayed?"This import was already done":"Import done"}</h2>
859
+ ${y.replayed?o`<p class="imp-text">This plan was already imported, so nothing was written again. Here is its record.</p>`:null}
860
+ ${Ec(R,null,0)}
861
+ ${F?o`<p class="imp-text">${F}</p>`:null}
863
862
  <p class="imp-text imp-nobody">Nobody was emailed. To tell your readers about the move, write a post as usual.</p>
864
863
  </section>
865
- ${q.length>0?o`<section class="card imp-card imp-differed">
864
+ ${K.length>0?o`<section class="card imp-card imp-differed">
866
865
  <h2>Rows that turned out differently</h2>
867
- <p class="imp-text">Your list changed between the plan and the import, so ${gi(q.length)} had a different result. Each was applied to the list as it stood.</p>
868
- <div class="table-wrap"><table class="imp-ref"><thead><tr><th>Row</th><th>Email</th><th>Planned</th><th>Applied</th></tr></thead><tbody>${q.map(g=>o`<tr><td>${String(g.row)}</td><td>${g.email}</td><td>${g.planned}</td><td>${g.applied}</td></tr>`)}</tbody></table></div>
866
+ <p class="imp-text">Your list changed between the plan and the import, so ${Ii(K.length)} had a different result. Each was applied to the list as it stood.</p>
867
+ <div class="table-wrap"><table class="imp-ref"><thead><tr><th>Row</th><th>Email</th><th>Planned</th><th>Applied</th></tr></thead><tbody>${K.map(b=>o`<tr><td>${String(b.row)}</td><td>${b.email}</td><td>${b.planned}</td><td>${b.applied}</td></tr>`)}</tbody></table></div>
869
868
  </section>`:null}
870
869
  <section class="card imp-card imp-record">
871
870
  <h2>The import’s record</h2>
872
871
  <dl class="imp-dl">
873
- <dt>File</dt><dd>${C.file_name}</dd>
874
- <dt>Fingerprint</dt><dd><code>${C.file_sha256.slice(0,16)}</code></dd>
875
- <dt>Imported</dt><dd>${W(C.created_at)} by ${U}</dd>
876
- <dt>Attestation</dt><dd>${C.attestation_version===null?"None needed: nobody was imported as a subscriber.":y.attestation?o`“${y.attestation.text}” <span class="muted">(version ${String(C.attestation_version)})</span>`:`Version ${C.attestation_version}`}</dd>
872
+ <dt>File</dt><dd>${T.file_name}</dd>
873
+ <dt>Fingerprint</dt><dd><code>${T.file_sha256.slice(0,16)}</code></dd>
874
+ <dt>Imported</dt><dd>${j(T.created_at)} by ${D}</dd>
875
+ <dt>Attestation</dt><dd>${T.attestation_version===null?"None needed: nobody was imported as a subscriber.":w.attestation?o`“${w.attestation.text}” <span class="muted">(version ${String(T.attestation_version)})</span>`:`Version ${T.attestation_version}`}</dd>
877
876
  </dl>
878
877
  <div class="actions imp-actions"><button type="button" class="ghost" id="impAnother">Import another file</button><button type="button" class="primary" id="impToList">See your subscribers</button></div>
879
- </section>`),c("#impAnother",n).onclick=()=>{r(),c("#impChoose",n).focus()},c("#impToList",n).onclick=()=>{location.hash="#/subscribers"},c("#impDoneHead",n).focus()}r()}function Dl(e){return o`<div class="field-error imp-act-error" role="alert" tabindex="-1"><span class="field-error-ico" aria-hidden="true">!</span><span>${e}</span></div>`}function Np(e){return e.name.trim().toLowerCase().endsWith(".txt")}function gi(e){return`${e.toLocaleString("en-US")} ${e===1?"row":"rows"}`}function Bp(e){return`${e.toLocaleString("en-US")} ${e===1?"address":"addresses"}`}function Ul(e,t,n){let s=e.filter(r=>!r.kept),i=e.filter(r=>r.kept),a=s.find(r=>r.outcome==="added_confirmed"||r.outcome==="confirmed_pending")?.outcome;return o`<ul class="imp-outcomes">${s.map(r=>o`<li data-outcome="${r.outcome}"><span>${r.text}</span>${r.outcome===a&&t&&n>0?o`<div class="field-hint imp-breakdown">Of the ${n.toLocaleString("en-US")} confirmed, by opt-in: ${t.optIn}. From: ${t.origin}.</div>`:null}</li>`)}</ul>
880
- ${i.length>0?o`<p class="imp-kept-head">Kept as they are here</p><ul class="imp-outcomes imp-kept">${i.map(r=>o`<li data-outcome="${r.outcome}"><span>${r.text}</span></li>`)}</ul>`:null}`}function Op(e){return e.suppression&&qe[e.suppression.reason]||"suppressed"}function Ws(e){return e.suppression?o` <span class="badge suppressed row-flag">${Op(e)}</span>`:null}function Vs(e){return e.suppression?o`<span class="badge ${e.status} held">${e.status}</span>`:Je(e.status)}function Fl(e){let t=e.lastIndexOf("@");return t>0?o`${e.slice(0,t)}<wbr>${e.slice(t)}`:o`${e}`}function Bn(e){return e.status==="unsubscribed"&&e.unsubscribe_cause==="erased"}function Ks(e){return`#/subscribers/${e}`}function Gs(e,t,n){let s=[];return e.status!=="unsubscribed"&&s.push({label:it.unsubscribe.label,danger:!0,onClick:()=>Wr(e,t,n)}),e.suppression?e.suppression.reason==="manual"?s.push({label:it.unblock.label,onClick:()=>Kr(e,t,n)}):qe[e.suppression.reason]==="bounced"&&s.push({label:it.clear.label,danger:!0,onClick:()=>zr(e,t,n)}):s.push({label:it.block.label,danger:!0,onClick:()=>Vr(e,t,n)}),Bn(e)||s.push({label:it.erase.label,danger:!0,onClick:()=>Yr(e,t,n)}),s}async function Dp(){let e=[],t=null,n=Date.now();do{let s=t===null?"":`?after=${encodeURIComponent(t)}`,i=await R(`/api/subscribers/export${s}`);if(i.next!==null&&i.next===t)throw new Error("The export repeated a page. Try again.");e.push(...i.subscribers),n=i.exported_at,t=i.next}while(t!==null);return{rows:e,exportedAt:n}}async function ql(){let{rows:e,exportedAt:t}=await Dp();return{name:`kestrel-subscribers-${new Date(t).toISOString().slice(0,10)}.csv`,text:di(e)}}var jl=[{value:"confirmed",label:"Confirmed"},{value:"pending",label:"Pending"},{value:"unsubscribed",label:"Unsubscribed"}],Si=["confirmed","pending","unsubscribed","suppressed"];async function Wl(e,t,n){se(n,"Subscribers");let s={status:"",search:"",suppressed:"",sort:"created_at",dir:"desc",offset:0,limit:50};e==="suppressed"?s.suppressed="only":e&&Si.includes(e)&&(s.status=e),h(t,o`
878
+ </section>`),c("#impAnother",n).onclick=()=>{a(),c("#impChoose",n).focus()},c("#impToList",n).onclick=()=>{location.hash="#/subscribers"},c("#impDoneHead",n).focus()}a()}function xc(e){return o`<div class="field-error imp-act-error" role="alert" tabindex="-1"><span class="field-error-ico" aria-hidden="true">!</span><span>${e}</span></div>`}function Rm(e){return e.name.trim().toLowerCase().endsWith(".txt")}function Ii(e){return`${e.toLocaleString("en-US")} ${e===1?"row":"rows"}`}function Cm(e){return`${e.toLocaleString("en-US")} ${e===1?"address":"addresses"}`}function Ec(e,t,n){let s=e.filter(a=>!a.kept),i=e.filter(a=>a.kept),r=s.find(a=>a.outcome==="added_confirmed"||a.outcome==="confirmed_pending")?.outcome;return o`<ul class="imp-outcomes">${s.map(a=>o`<li data-outcome="${a.outcome}"><span>${a.text}</span>${a.outcome===r&&t&&n>0?o`<div class="field-hint imp-breakdown">Of the ${n.toLocaleString("en-US")} confirmed, by opt-in: ${t.optIn}. From: ${t.origin}.</div>`:null}</li>`)}</ul>
879
+ ${i.length>0?o`<p class="imp-kept-head">Kept as they are here</p><ul class="imp-outcomes imp-kept">${i.map(a=>o`<li data-outcome="${a.outcome}"><span>${a.text}</span></li>`)}</ul>`:null}`}function Am(e){return e.suppression&&je[e.suppression.reason]||"suppressed"}function oo(e){return e.suppression?o` <span class="badge suppressed row-flag">${Am(e)}</span>`:null}function io(e){return e.suppression?o`<span class="badge ${e.status} held">${e.status}</span>`:Xe(e.status)}function kc(e){let t=e.lastIndexOf("@");return t>0?o`${e.slice(0,t)}<wbr>${e.slice(t)}`:o`${e}`}function Kn(e){return e.status==="unsubscribed"&&e.unsubscribe_cause==="erased"}function ro(e){return`#/subscribers/${e}`}function ao(e,t,n){let s=[];return e.status!=="unsubscribed"&&s.push({label:ct.unsubscribe.label,danger:!0,onClick:()=>ya(e,t,n)}),e.suppression?e.suppression.reason==="manual"?s.push({label:ct.unblock.label,onClick:()=>Sa(e,t,n)}):je[e.suppression.reason]==="bounced"&&s.push({label:ct.clear.label,danger:!0,onClick:()=>xa(e,t,n)}):s.push({label:ct.block.label,danger:!0,onClick:()=>wa(e,t,n)}),Kn(e)||s.push({label:ct.erase.label,danger:!0,onClick:()=>Ea(e,t,n)}),s}async function Hm(){let e=[],t=null,n=Date.now();do{let s=t===null?"":`?after=${encodeURIComponent(t)}`,i=await L(`/api/subscribers/export${s}`);if(i.next!==null&&i.next===t)throw new Error("The export repeated a page. Try again.");e.push(...i.subscribers),n=i.exported_at,t=i.next}while(t!==null);return{rows:e,exportedAt:n}}async function _c(){let{rows:e,exportedAt:t}=await Hm();return{name:`kestrel-subscribers-${new Date(t).toISOString().slice(0,10)}.csv`,text:Li(e)}}var Tc=[{value:"confirmed",label:"Confirmed"},{value:"pending",label:"Pending"},{value:"unsubscribed",label:"Unsubscribed"}],Bi=["confirmed","pending","unsubscribed","suppressed"];async function Lc(e,t,n){ie(n,"Subscribers");let s={status:"",search:"",suppressed:"",sort:"created_at",dir:"desc",offset:0,limit:50};e==="suppressed"?s.suppressed="only":e&&Bi.includes(e)&&(s.status=e),h(t,o`
881
880
  <div class="spread page-head"><h1>Subscribers</h1><span class="row"><button type="button" class="ghost" id="importSubs">Import</button><button type="button" class="ghost" id="exportSubs">Export</button><button class="primary" id="addSub">Add subscriber</button></span></div>
882
- <div class="card sub-summary"><div class="sub-summary-head"><div id="subCounts" class="row muted" role="group" aria-label="Show">Loading…</div><button type="button" class="sub-legend-toggle" id="subLegendToggle" aria-expanded="false" aria-controls="subLegend">Legend</button></div><p class="workers-plan" id="subWorkersPlan" role="status" hidden></p>${jp()}</div>
883
- ${jt({statuses:jl,suppressible:!0,searchPlaceholder:"Search email\u2026"})}
881
+ <div class="health red" id="subSignupsPaused" role="status" hidden></div>
882
+ <div class="card sub-summary"><div class="sub-summary-head"><div id="subCounts" class="row muted" role="group" aria-label="Show">Loading…</div><button type="button" class="sub-legend-toggle" id="subLegendToggle" aria-expanded="false" aria-controls="subLegend">Legend</button></div><p class="workers-plan" id="subWorkersPlan" role="status" hidden></p>${Nm()}</div>
883
+ ${Kt({statuses:Tc,suppressible:!0,searchPlaceholder:"Search email\u2026"})}
884
884
  <div id="subList" class="muted">Loading…</div>
885
- <div id="subPager"></div>`);let i=c("#subList"),a=c("#subPager");async function r(){try{let u=await R(`/api/subscribers?${qt(s)}`,{signal:n}),f=u.counts;Fp(c("#subCounts"),f,s);let S=c("#subWorkersPlan");S.hidden=!u.workers_plan_advice,S.textContent=u.workers_plan_advice??"";let b=f.pending+f.confirmed+f.unsubscribed===0;Wp(i,u.subscribers,s,r,n,b),ot(a,s,u.page,r)}catch(u){oe(i,F(u),r)}}qp(t,s,r);let l=c("#subLegendToggle");l.onclick=()=>{let u=l.getAttribute("aria-expanded")!=="true";l.setAttribute("aria-expanded",String(u)),c("#subLegend").hidden=!u},c("#addSub").onclick=()=>xs(r,n),c("#importSubs").onclick=()=>{location.hash="#/subscribers/import"};let d=c("#exportSubs");d.onclick=()=>G(d,"Exporting\u2026",async()=>{try{let u=await ql();kt(u.text,u.name,"text/csv")}catch(u){O(F(u))}}),Wt(t,s,r),r()}var Up=["confirmed","pending","unsubscribed","suppressed"];function wi(e,t){return e.search?!1:t==="suppressed"?e.suppressed==="only"&&!e.status:e.status===t&&!e.suppressed}function Fp(e,t,n){e.querySelector("[data-filter]")||h(e,o`${Up.map(s=>o`<button type="button" class="sub-count" data-filter="${s}" aria-pressed="false"></button>`)}`);for(let s of I("[data-filter]",e)){let i=s.dataset.filter;h(s,o`${i==="confirmed"?o`<strong>${t[i]}</strong>`:t[i]} ${i}`),s.setAttribute("aria-pressed",String(wi(n,i)))}}function qp(e,t,n){let s=c("#subCounts",e);s.onclick=i=>{let a=i.target instanceof Element?i.target.closest("[data-filter]"):null;if(!a)return;let r=a.dataset.filter,l=!wi(t,r);t.status=l&&r!=="suppressed"?r:"",t.suppressed=l&&r==="suppressed"?"only":"",t.search="",t.offset=0,c(".lt-search",e).value="",c(".lt-status",e).value=t.status,c(".lt-suppressed",e).checked=t.suppressed==="only";for(let d of I("[data-filter]",s))d.setAttribute("aria-pressed",String(wi(t,d.dataset.filter)));n()}}function yi(e,t){return o`<dt>${e}</dt><dd>${t}</dd>`}function jp(){let e=Object.keys(vn);return o`<div class="sub-legend" id="subLegend" role="region" aria-labelledby="subLegendToggle" hidden><div class="sub-legend-body">
885
+ <div id="subPager"></div>`);let i=c("#subList"),r=c("#subPager"),a=at(Y.appConfig?.deployment,n);async function l(){try{let[m,v]=await Promise.all([L(`/api/subscribers?${Vt(s)}`,{signal:n}),a]),f=m.counts;Mm(c("#subCounts"),f,s);let p=c("#subWorkersPlan");p.hidden=!m.workers_plan_advice,p.textContent=m.workers_plan_advice??"";let S=f.pending+f.confirmed+f.unsubscribed===0;Om(i,m.subscribers,s,l,n,S,lt(v));let $=c("#subSignupsPaused");$.hidden=!En(v),h($,En(v)?o`<span class="health-dot">⚠️</span><div>${ha()}</div>`:o``),rt(r,s,m.page,l)}catch(m){re(i,V(m),l)}}Im(t,s,l);let d=c("#subLegendToggle");d.onclick=()=>{let m=d.getAttribute("aria-expanded")!=="true";d.setAttribute("aria-expanded",String(m)),c("#subLegend").hidden=!m},c("#addSub").onclick=()=>Ms(l,n),c("#importSubs").onclick=()=>{location.hash="#/subscribers/import"};let u=c("#exportSubs");u.onclick=()=>Z(u,"Exporting\u2026",async()=>{try{let m=await _c();Rt(m.text,m.name,"text/csv")}catch(m){U(V(m))}}),Gt(t,s,l),l()}var Pm=["confirmed","pending","unsubscribed","suppressed"];function Di(e,t){return e.search?!1:t==="suppressed"?e.suppressed==="only"&&!e.status:e.status===t&&!e.suppressed}function Mm(e,t,n){e.querySelector("[data-filter]")||h(e,o`${Pm.map(s=>o`<button type="button" class="sub-count" data-filter="${s}" aria-pressed="false"></button>`)}`);for(let s of N("[data-filter]",e)){let i=s.dataset.filter;h(s,o`${i==="confirmed"?o`<strong>${t[i]}</strong>`:t[i]} ${i}`),s.setAttribute("aria-pressed",String(Di(n,i)))}}function Im(e,t,n){let s=c("#subCounts",e);s.onclick=i=>{let r=i.target instanceof Element?i.target.closest("[data-filter]"):null;if(!r)return;let a=r.dataset.filter,l=!Di(t,a);t.status=l&&a!=="suppressed"?a:"",t.suppressed=l&&a==="suppressed"?"only":"",t.search="",t.offset=0,c(".lt-search",e).value="",c(".lt-status",e).value=t.status,c(".lt-suppressed",e).checked=t.suppressed==="only";for(let d of N("[data-filter]",s))d.setAttribute("aria-pressed",String(Di(t,d.dataset.filter)));n()}}function Oi(e,t){return o`<dt>${e}</dt><dd>${t}</dd>`}function Nm(){let e=Object.keys(kn);return o`<div class="sub-legend" id="subLegend" role="region" aria-labelledby="subLegendToggle" hidden><div class="sub-legend-body">
886
886
  <h2>Status</h2>
887
- <dl>${jl.map(({value:t})=>yi(Je(t),t==="unsubscribed"?`${Lo[t]} Why they left is on their page.`:Lo[t]))}</dl>
887
+ <dl>${Tc.map(({value:t})=>Oi(Xe(t),t==="unsubscribed"?`${Wo[t]} Why they left is on their page.`:Wo[t]))}</dl>
888
888
  <h2>Suppressed</h2>
889
- <p>${jr} The red flag beside the address says why:</p>
890
- <dl>${e.map(t=>yi(o`<span class="badge suppressed">${t}</span>`,vn[t]))}</dl>
889
+ <p>${va} The red flag beside the address says why:</p>
890
+ <dl>${e.map(t=>Oi(o`<span class="badge suppressed">${t}</span>`,kn[t]))}</dl>
891
891
  <h2>What you can do</h2>
892
- <dl>${Object.values(it).map(({label:t,when:n})=>yi(o`<strong class="sub-legend-act">${t}</strong>`,n))}</dl>
893
- </div></div>`}function Wp(e,t,n,s,i,a){if(!t.length){h(e,a?o`<p class="muted">No subscribers yet. <a href="#/subscribers/import">Import your list</a> from another service, or share your subscribe page.</p>`:o`<p class="muted">No subscribers match.</p>`);return}h(e,o`<div class="table-wrap subs-wrap"><table class="list-table subs-table stacks has-actions"><colgroup><col><col class="c-status"><col class="c-date"><col class="c-act"></colgroup><thead><tr>${$e("Email","email",n)}${$e("Status",null,n)}${$e("Joined","created_at",n)}<th></th></tr></thead><tbody>${t.map(r=>o`<tr class="clickable" data-id="${r.id}"><td><a class="sub-email" href="${Ks(r.id)}">${Fl(r.email)}</a>${Ws(r)}</td><td>${Vs(r)}</td><td class="muted joined">${W(r.created_at)}</td><td class="act"><button class="icon" data-menu="${r.id}" aria-label="Subscriber actions" aria-haspopup="menu">⋯</button></td></tr>`)}</tbody></table></div>`),st(e,n,s);for(let r of I("tr[data-id]",e))r.onclick=l=>{l.target instanceof Element&&l.target.closest("a, button")||(location.hash=Ks(r.dataset.id??""))};for(let r of I("[data-menu]",e))r.onclick=l=>{l.stopPropagation();let d=t.find(f=>f.id===r.dataset.menu);if(!d)return;let u=[{label:"View subscriber",onClick:()=>{location.hash=Ks(d.id)}},...Gs(d,s,i)];Kt(r,u,i)}}var zs=o`<div class="editor-head"><a href="#/subscribers" class="back">← Subscribers</a></div>`;async function Vl(e,t,n){se(n,"Subscriber"),h(t,o`${zs}<p class="muted">Loading…</p>`);let s=`/api/subscribers/${encodeURIComponent(e)}`;async function i(r){let l,d,u;try{let f=R(s,{signal:n}),S=f.then(({subscriber:x})=>x.import_id===null?null:R(`/api/imports/${encodeURIComponent(x.import_id)}`,{signal:n}).then(M=>M.import,()=>null)),[b,p,v]=await Promise.all([f,R(`${s}/deliveries`,{signal:n}),S]);l=b.subscriber,d=p,u=v}catch(f){let S=document.createElement("div");h(t,zs),t.append(S),oe(S,F(f),()=>{h(t,o`${zs}<p class="muted">Loading…</p>`),i(!1)});return}n.aborted||(a(l,d,u),r&&c("h1.sub-title",t).focus())}function a(r,l,d){let u=Gs(r,()=>{i(!0)},n),f=Bn(r);h(t,o`${zs}
892
+ <dl>${Object.values(ct).map(({label:t,when:n})=>Oi(o`<strong class="sub-legend-act">${t}</strong>`,n))}</dl>
893
+ </div></div>`}function Om(e,t,n,s,i,r,a){if(!t.length){let l=o`<a href="#/subscribers/import">Import your list</a>`;h(e,r?a?o`<p class="muted">No subscribers yet. ${l} from another service. Once AWS grants production access, share your subscribe page. <a class="set-link" href="${kt}">Request production access</a></p>`:o`<p class="muted">No subscribers yet. ${l} from another service, or share your subscribe page.</p>`:o`<p class="muted">No subscribers match.</p>`);return}h(e,o`<div class="table-wrap subs-wrap"><table class="list-table subs-table stacks has-actions"><colgroup><col><col class="c-status"><col class="c-date"><col class="c-act"></colgroup><thead><tr>${Ee("Email","email",n)}${Ee("Status",null,n)}${Ee("Joined","created_at",n)}<th></th></tr></thead><tbody>${t.map(l=>o`<tr class="clickable" data-id="${l.id}"><td><a class="sub-email" href="${ro(l.id)}">${kc(l.email)}</a>${oo(l)}</td><td>${io(l)}</td><td class="muted joined">${j(l.created_at)}</td><td class="act"><button class="icon" data-menu="${l.id}" aria-label="Subscriber actions" aria-haspopup="menu">⋯</button></td></tr>`)}</tbody></table></div>`),it(e,n,s);for(let l of N("tr[data-id]",e))l.onclick=d=>{d.target instanceof Element&&d.target.closest("a, button")||(location.hash=ro(l.dataset.id??""))};for(let l of N("[data-menu]",e))l.onclick=d=>{d.stopPropagation();let u=t.find(v=>v.id===l.dataset.menu);if(!u)return;let m=[{label:"View subscriber",onClick:()=>{location.hash=ro(u.id)}},...ao(u,s,i)];Yt(l,m,i)}}var lo=o`<div class="editor-head"><a href="#/subscribers" class="back">← Subscribers</a></div>`;async function Rc(e,t,n){ie(n,"Subscriber"),h(t,o`${lo}<p class="muted">Loading…</p>`);let s=`/api/subscribers/${encodeURIComponent(e)}`;async function i(a){let l,d,u;try{let m=L(s,{signal:n}),v=m.then(({subscriber:$})=>$.import_id===null?null:L(`/api/imports/${encodeURIComponent($.import_id)}`,{signal:n}).then(M=>M.import,()=>null)),[f,p,S]=await Promise.all([m,L(`${s}/deliveries`,{signal:n}),v]);l=f.subscriber,d=p,u=S}catch(m){let v=document.createElement("div");h(t,lo),t.append(v),re(v,V(m),()=>{h(t,o`${lo}<p class="muted">Loading…</p>`),i(!1)});return}n.aborted||(r(l,d,u),a&&c("h1.sub-title",t).focus())}function r(a,l,d){let u=ao(a,()=>{i(!0)},n),m=Kn(a);h(t,o`${lo}
894
894
  <div class="spread page-head sub-page-head">
895
- <div class="sub-page-title"><h1 class="sub-title" tabindex="-1">${r.email}</h1><span class="sub-pills">${Vs(r)}${Ws(r)}</span></div>
896
- <span class="row sub-acts">${u.map((p,v)=>o`<button type="button" class="${p.danger?"danger-subtle":""}" data-act="${v}">${p.label}…</button>`)}</span>
895
+ <div class="sub-page-title"><h1 class="sub-title" tabindex="-1">${a.email}</h1><span class="sub-pills">${io(a)}${oo(a)}</span></div>
896
+ <span class="row sub-acts">${u.map((p,S)=>o`<button type="button" class="${p.danger?"danger-subtle":""}" data-act="${S}">${p.label}…</button>`)}</span>
897
897
  </div>
898
- <p class="sub-receives${r.receives_posts?" yes":""}">${Vp(r)}</p>
899
- ${f?null:Kp(r,d)}
900
- ${Gp(r)}
901
- ${r.unsubscribe_cause?Zp(r):null}
898
+ <p class="sub-receives${a.receives_posts?" yes":""}">${Dm(a)}</p>
899
+ ${m?null:Bm(a,d)}
900
+ ${Um(a)}
901
+ ${a.unsubscribe_cause?jm(a):null}
902
902
  <section class="sub-sec sub-sends" aria-labelledby="subSendsTitle">
903
903
  <h2 class="rec-part-title" id="subSendsTitle">Sends</h2>
904
904
  <div id="subSends"></div>
905
905
  <div id="subMore"></div>
906
- </section>`);for(let p of I("[data-act]",t))p.onclick=()=>u[Number(p.dataset.act)]?.onClick();let S=t.querySelector("#subComplaint");Jp(t,s,l,f,n,p=>{let v=p.find(x=>x.delivery.event==="complained");S?.hidden&&v&&(h(S,o`The report was about <a href="#/sent/${v.send.id}">${v.send.subject||"an untitled post"}</a>.`),S.hidden=!1)})}await i(!1)}function Vp(e){if(e.receives_posts)return"Receives your posts.";let t=[];return e.status==="pending"?t.push("they haven\u2019t confirmed"):e.status==="unsubscribed"&&t.push(`they left the list on ${W(e.unsubscribed_at)}`),e.suppression&&t.push(qe[e.suppression.reason]==="bounced"?"the address bounced":"the address is blocked"),t.length>0?`Not sent your posts: ${t.join(", and ")}.`:"Not sent your posts."}function We(e,t){return o`<dt>${e}</dt><dd>${t}</dd>`}function Kp(e,t){let n=Hl(e.consent_evidence),s=Al(e)??(e.status==="pending"?"Signed up here, not confirmed yet":"Signed up here, never confirmed");return o`<section class="card sub-sec" aria-labelledby="subJoinedTitle">
906
+ </section>`);for(let p of N("[data-act]",t))p.onclick=()=>u[Number(p.dataset.act)]?.onClick();let v=t.querySelector("#subComplaint");Wm(t,s,l,m,n,p=>{let S=p.find($=>$.delivery.event==="complained");v?.hidden&&S&&(h(v,o`The report was about <a href="#/sent/${S.send.id}">${S.send.subject||"an untitled post"}</a>.`),v.hidden=!1)})}await i(!1)}function Dm(e){if(e.receives_posts)return"Receives your posts.";let t=[];return e.status==="pending"?t.push("they haven\u2019t confirmed"):e.status==="unsubscribed"&&t.push(`they left the list on ${j(e.unsubscribed_at)}`),e.suppression&&t.push(je[e.suppression.reason]==="bounced"?"the address bounced":"the address is blocked"),t.length>0?`Not sent your posts: ${t.join(", and ")}.`:"Not sent your posts."}function Ve(e,t){return o`<dt>${e}</dt><dd>${t}</dd>`}function Bm(e,t){let n=bc(e.consent_evidence),s=hc(e)??(e.status==="pending"?"Signed up here, not confirmed yet":"Signed up here, never confirmed");return o`<section class="card sub-sec" aria-labelledby="subJoinedTitle">
907
907
  <h2 class="rec-part-title" id="subJoinedTitle">How they joined</h2>
908
908
  <dl class="sub-dl">
909
- ${We("How they joined",s)}
910
- ${e.import_id!==null?o`${We("Origin",In(e.origin)??"Unknown")}
911
- ${We("Opt-in",Nn(e.opt_in))}
912
- ${t?o`${We("Import",o`<code>${t.file_name}</code>`)}
913
- ${We("Imported",`${W(t.created_at)}, by ${js(t)}`)}
914
- ${We("Attestation",t.attestation_version===null?"None: the import confirmed no one":`Version ${t.attestation_version}`)}`:null}`:null}
915
- ${We("Joined",W(e.created_at))}
916
- ${We("Confirmed",W(e.confirmed_at))}
917
- ${We("Evidence",n?o`<pre class="sub-evidence">${n}</pre>`:"None recorded")}
909
+ ${Ve("How they joined",s)}
910
+ ${e.import_id!==null?o`${Ve("Origin",Wn(e.origin)??"Unknown")}
911
+ ${Ve("Opt-in",Vn(e.opt_in))}
912
+ ${t?o`${Ve("Import",o`<code>${t.file_name}</code>`)}
913
+ ${Ve("Imported",`${j(t.created_at)}, by ${so(t)}`)}
914
+ ${Ve("Attestation",t.attestation_version===null?"None: the import confirmed no one":`Version ${t.attestation_version}`)}`:null}`:null}
915
+ ${Ve("Joined",j(e.created_at))}
916
+ ${Ve("Confirmed",j(e.confirmed_at))}
917
+ ${Ve("Evidence",n?o`<pre class="sub-evidence">${n}</pre>`:"None recorded")}
918
918
  </dl>
919
919
  ${e.import_id!==null?o`<p class="sub-note">The origin, opt-in, confirmation date, and evidence are what the imported file said, not something Kestrel recorded itself.</p>`:null}
920
- </section>`}function Gp(e){let t=e.suppression,n;if(!t)n=o`<p class="muted">None.</p>`;else{let s=qe[t.reason];n=o`<p class="sub-sup-line"><span class="badge suppressed">${s}</span> <span class="muted">since ${W(t.created_at)}</span></p>
921
- <p class="sub-meaning">${Yp(e,t.reason)}</p>
922
- ${t.detail?o`<dl class="sub-dl">${We("Detail",t.detail)}</dl>`:null}`}return o`<section class="card sub-sec" aria-labelledby="subSupTitle">
920
+ </section>`}function Um(e){let t=e.suppression,n;if(!t)n=o`<p class="muted">None.</p>`;else{let s=je[t.reason];n=o`<p class="sub-sup-line"><span class="badge suppressed">${s}</span> <span class="muted">since ${j(t.created_at)}</span></p>
921
+ <p class="sub-meaning">${qm(e,t.reason)}</p>
922
+ ${t.detail?o`<dl class="sub-dl">${Ve("Detail",t.detail)}</dl>`:null}`}return o`<section class="card sub-sec" aria-labelledby="subSupTitle">
923
923
  <h2 class="rec-part-title" id="subSupTitle">Suppression</h2>
924
924
  ${n}
925
- </section>`}var zp={reader:"They had unsubscribed themselves, from the link or the button in your email.",publisher:"You had unsubscribed them, when they asked you to.",complaint:"They had reported your email as spam.",erased:"You had erased them at their request.",import:"The list you imported said they had left."};function Yp(e,t){switch(t){case"bounce":return"Your email provider reported that mail to this address failed. You can clear it.";case"import_bounce":return"Mail to this address failed at the service your list was imported from. You can clear it.";default:return e.import_id===null&&!Bn(e)?"You blocked this address. You can unblock it.":vn[qe[t]]}}function Zp(e){let t=e.unsubscribe_cause;if(!t)return null;let n=e.status!=="unsubscribed";return o`<section class="card sub-sec" aria-labelledby="subLeftTitle">
925
+ </section>`}var Fm={reader:"They had unsubscribed themselves, from the link or the button in your email.",publisher:"You had unsubscribed them, when they asked you to.",complaint:"They had reported your email as spam.",erased:"You had erased them at their request.",import:"The list you imported said they had left."};function qm(e,t){switch(t){case"bounce":return"Your email provider reported that mail to this address failed. You can clear it.";case"import_bounce":return"Mail to this address failed at the service your list was imported from. You can clear it.";default:return e.import_id===null&&!Kn(e)?"You blocked this address. You can unblock it.":kn[je[t]]}}function jm(e){let t=e.unsubscribe_cause;if(!t)return null;let n=e.status!=="unsubscribed";return o`<section class="card sub-sec" aria-labelledby="subLeftTitle">
926
926
  <h2 class="rec-part-title" id="subLeftTitle">${n?"Left before":"Why they left"}</h2>
927
- <p class="sub-left-line"><span class="muted">Left ${W(e.unsubscribed_at)}</span></p>
928
- <p class="sub-meaning">${n?zp[t]:qr[t]}</p>
927
+ <p class="sub-left-line"><span class="muted">Left ${j(e.unsubscribed_at)}</span></p>
928
+ <p class="sub-meaning">${n?Fm[t]:ga[t]}</p>
929
929
  ${t==="complaint"?o`<p class="sub-meaning" id="subComplaint" hidden></p>`:null}
930
930
  ${e.status==="pending"?o`<p class="sub-meaning">They signed up again, and haven’t confirmed yet.</p>`:null}
931
- </section>`}function Jp(e,t,n,s,i,a){let r=c("#subSends",e),l=c("#subMore",e);if(n.deliveries.length===0){h(r,s?o`<p class="muted">Their past sends show an erased recipient in place of the address, so none is listed here.</p>`:o`<p class="muted">Not in any send yet.</p>`);return}h(r,o`<div class="table-wrap"><table class="list-table sub-sends-table"><colgroup><col><col class="c-out"><col><col class="c-date"></colgroup><thead><tr><th>Send</th><th class="c-out">Outcome</th><th>Detail</th><th class="c-date">When</th></tr></thead><tbody></tbody></table></div>`);let d=c("tbody",r),u=S=>{a(S.deliveries);let b=document.createElement("tbody");h(b,o`${S.deliveries.map(Xp)}`),d.append(...b.childNodes),f(S.next)},f=S=>{if(!S){h(l,o``);return}h(l,o`<button type="button" class="sub-more">Show more</button>`);let b=c(".sub-more",l);b.onclick=()=>G(b,"Loading\u2026",async()=>{try{u(await R(`${t}/deliveries?after=${encodeURIComponent(S)}`,{signal:i}))}catch(p){oe(l,F(p),()=>f(S))}})};u(n)}var Qp="Left out: unsubscribed or suppressed before it went";function Xp({send:e,delivery:t}){let n=Is(t),s=t.error||t.event_detail||(t.event===null&&t.status==="skipped"?Qp:"");return o`<tr><td class="sub-send"><a href="#/sent/${e.id}">${e.subject||o`<em>untitled</em>`}</a><div class="muted">${W(e.fire_at)}</div></td><td><span class="rec-out"><span class="rec-sw sw-${n.sw}"></span>${n.label}</span></td><td class="muted">${s||"\u2014"}</td><td class="muted">${t.event_at?W(t.event_at):"\u2014"}</td></tr>`}var em="You have unsaved changes. Leave without saving?",$i="";function Ei(){let e=location.hash||"#/dashboard";(e==="#/reference"||e.startsWith("#/reference/"))&&(e=`#/api-reference${e.slice(11)}`,history.replaceState(history.state,"",e)),$i=e;let[,t,n,s]=(yo(e.slice(1))?e:"#/dashboard").split("/");document.body.classList.toggle("editor-mode",t==="edit");let i=t==="web"?La(n,s):null;document.body.classList.toggle("web-mode",i!==null);let a=t==="docs"||t==="api-reference";document.body.classList.toggle("tool-mode",a);for(let r of document.querySelectorAll(".sidebar a[data-view]"))r.dataset.view===t?r.setAttribute("aria-current","page"):r.removeAttribute("aria-current");return an(!1),t==="edit"&&n?ee((r,l)=>Oo(n,r,l)):i!==null?ee((r,l)=>Bo(i,r,l)):t==="drafts"?ee(To):t==="subscribers"&&n==="import"?ee(vi):t==="subscribers"&&n&&!Si.includes(n)?ee((r,l)=>Vl(n,r,l)):t==="subscribers"?ee((r,l)=>Wl(n,r,l)):t==="sent"?n?ee((r,l)=>Zo(n,r,l)):ee(Yo):t==="template"?ee(ni):t==="settings"?ee(ai):t==="api-reference"?ee((r,l)=>zo(r,l,n)):t==="docs"?ee((r,l)=>Uo(n,r,l,s)):ee(Co)}function Kl(){let e=Rr(location.search);if(e){let t=new URL(location.href);t.search="",t.hash=e,history.replaceState(null,"",t)}}function Gl(){window.addEventListener("hashchange",()=>{if(location.hash!==$i){if(Vn()?.beforeLeave?.()==="confirm"&&!confirm(em)){location.hash=$i;return}Ei()}}),window.addEventListener("beforeunload",e=>{Vn()?.dirty?.()&&(e.preventDefault(),e.returnValue="")}),window.addEventListener("keydown",e=>{let t=Vn()?.manualSave;(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="s"&&t&&(e.preventDefault(),t())})}async function tm(){Ai(),Fr(),Lr(),Gl();let e=await Ui();if(e){Q.session=e,document.body.classList.remove("signed-out"),Di();try{Q.appConfig=await R("/api/settings")}catch{}return Xn(),Kl(),Ei()}}tm();})();
931
+ </section>`}function Wm(e,t,n,s,i,r){let a=c("#subSends",e),l=c("#subMore",e);if(n.deliveries.length===0){h(a,s?o`<p class="muted">Their past sends show an erased recipient in place of the address, so none is listed here.</p>`:o`<p class="muted">Not in any send yet.</p>`);return}h(a,o`<div class="table-wrap"><table class="list-table sub-sends-table"><colgroup><col><col class="c-out"><col><col class="c-date"></colgroup><thead><tr><th>Send</th><th class="c-out">Outcome</th><th>Detail</th><th class="c-date">When</th></tr></thead><tbody></tbody></table></div>`);let d=c("tbody",a),u=v=>{r(v.deliveries);let f=document.createElement("tbody");h(f,o`${v.deliveries.map(Km)}`),d.append(...f.childNodes),m(v.next)},m=v=>{if(!v){h(l,o``);return}h(l,o`<button type="button" class="sub-more">Show more</button>`);let f=c(".sub-more",l);f.onclick=()=>Z(f,"Loading\u2026",async()=>{try{u(await L(`${t}/deliveries?after=${encodeURIComponent(v)}`,{signal:i}))}catch(p){re(l,V(p),()=>m(v))}})};u(n)}var Vm="Left out: unsubscribed or suppressed before it went";function Km({send:e,delivery:t}){let n=Ks(t),s=t.error||t.event_detail||(t.event===null&&t.status==="skipped"?Vm:"");return o`<tr><td class="sub-send"><a href="#/sent/${e.id}">${e.subject||o`<em>untitled</em>`}</a><div class="muted">${j(e.fire_at)}</div></td><td><span class="rec-out"><span class="rec-sw sw-${n.sw}"></span>${n.label}</span></td><td class="muted">${s||"\u2014"}</td><td class="muted">${t.event_at?j(t.event_at):"\u2014"}</td></tr>`}var Gm="You have unsaved changes. Leave without saving?",Ui="";function Fi(){let e=location.hash||"#/dashboard";(e==="#/reference"||e.startsWith("#/reference/"))&&(e=`#/api-reference${e.slice(11)}`,history.replaceState(history.state,"",e)),Ui=e;let[,t,n,s]=(Po(e.slice(1))?e:"#/dashboard").split("/");document.body.classList.toggle("editor-mode",t==="edit");let i=t==="web"?al(n,s):null;document.body.classList.toggle("web-mode",i!==null);let r=t==="docs"||t==="api-reference";document.body.classList.toggle("tool-mode",r);for(let a of document.querySelectorAll(".sidebar a[data-view]"))a.dataset.view===t?a.setAttribute("aria-current","page"):a.removeAttribute("aria-current");return dn(!1),t==="edit"&&n?ee((a,l)=>ni(n,a,l)):i!==null?ee((a,l)=>ti(i,a,l)):t==="drafts"?ee(Fo):t==="subscribers"&&n==="import"?ee(Ni):t==="subscribers"&&n&&!Bi.includes(n)?ee((a,l)=>Rc(n,a,l)):t==="subscribers"?ee((a,l)=>Lc(n,a,l)):t==="sent"?n?ee((a,l)=>fi(n,a,l)):ee(mi):t==="template"?ee(wi):t==="settings"?ee(ki):t==="api-reference"?ee((a,l)=>pi(a,l,n)):t==="docs"?ee((a,l)=>oi(n,a,l,s)):ee(zo)}function Cc(){let e=Yr(location.search);if(e){let t=new URL(location.href);t.search="",t.hash=e,history.replaceState(null,"",t)}}function Ac(){window.addEventListener("hashchange",()=>{if(location.hash!==Ui){if(es()?.beforeLeave?.()==="confirm"&&!confirm(Gm)){location.hash=Ui;return}Fi()}}),window.addEventListener("beforeunload",e=>{es()?.dirty?.()&&(e.preventDefault(),e.returnValue="")}),window.addEventListener("keydown",e=>{let t=es()?.manualSave;(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="s"&&t&&(e.preventDefault(),t())})}async function zm(){Zi(),aa(),zr(),Ac();let e=await ir();if(e){Y.session=e,or();try{Y.appConfig=await L("/api/settings")}catch{}return ls(),document.body.classList.remove("signed-out"),Cc(),Fi()}}zm().catch(e=>{document.body.classList.contains("signed-out")&&!pe.querySelector(".auth-wall")&&pn(),reportError(e)});})();
932
932
  //# sourceMappingURL=app.js.map