1import type { Context, Hono } from "hono";2import { checkFormat, listRepos } from "../bucket/repo.ts";3import type { SyncTarget } from "../bucket/sync.ts";4import { type Html, html } from "../pages/html.ts";5import { type PageContext, page, plural } from "../pages/layout.ts";6import { backups, newestBackupTarball } from "../server/backup.ts";7import { formToken } from "../server/login.ts";89export type AdminContext = PageContext & { sync: SyncTarget; dataDir: string };1011const SECTIONS = [12 ["/admin", "status"],13 ["/admin/repos", "repos"],14 ["/admin/issues", "issues"],15 ["/admin/releases", "releases"],16 ["/admin/site", "site"],17] as const;181920export function formField(c: Context): Html {21 return html`<input type="hidden" name="form" value="${formToken(c)}">`;22}232425export async function textFields(c: Context): Promise<Record<string, string>> {26 const fields: Record<string, string> = {};27 for (const [name, value] of Object.entries(await c.req.parseBody())) {28 if (typeof value === "string") fields[name] = value;29 }30 return fields;31}3233export function notice(error: string): Html | "" {34 return error && html`<p class="issues-error mono" role="alert">${error}</p>`;35}363738export function adminPage(c: Context, ctx: AdminContext, title: string, body: Html): string {39 const tab = ([href, name]: (typeof SECTIONS)[number]) =>40 html`<a class="issues-tab${c.req.path === href ? " active" : ""}" href="${href}">${name}</a>`;41 return page(ctx, {42 title: `${title} · admin`,43 description: "",44 path: c.req.path,45 body: html`<form class="issues-bar mono" method="post" action="/admin/sign-out">${SECTIONS.map(tab)}${formField(c)}<button class="issues-tab issues-new" type="submit">sign out</button></form>46<h1 class="file-page-title">${title}</h1>47${body}`,48 });49}505152let runningLines: number | null = null;53async function sourceLines(): Promise<number> {54 if (runningLines !== null) return runningLines;55 let total = 0;56 const root = `${import.meta.dir}/../..`;57 for await (const path of new Bun.Glob("{src,scripts}/**/*.ts").scan(root)) {58 if (path.endsWith(".test.ts")) continue;59 const text = await Bun.file(`${root}/${path}`).text();60 total += text.split("\n").length - (text.endsWith("\n") ? 1 : 0);61 }62 runningLines = total;63 return total;64}656667export function registerStatus(app: Hono, ctx: AdminContext): void {68 app.get("/admin", async (c) => {69 let bucket: Html;70 try {71 const repos = await listRepos(ctx.sync.bucket);72 const formats = await Promise.all(73 repos.map(async (repo) => {74 try {75 await checkFormat(ctx.sync.bucket, repo);76 return html`<li><span class="mono">${repo}</span> <span class="muted">format ok</span></li>`;77 } catch (error) {78 return html`<li><span class="mono">${repo}</span> <span class="issues-error">${String(error)}</span></li>`;79 }80 }),81 );82 bucket = html`<p>Bucket reachable: ${plural(repos.length, "repo")}.</p><ul>${formats}</ul>`;83 } catch (error) {84 bucket = html`<p class="issues-error" role="alert">Bucket unreachable: ${String(error)}</p>`;85 }86 const { version } = (await Bun.file(`${import.meta.dir}/../../package.json`).json()) as {87 version: string;88 };89 const lines = (await sourceLines()).toLocaleString("en-US");90 const newest = backups(ctx.dataDir).at(-1);91 const backup = newest92 ? html`<p>Last backup: ${newest.replace(/^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/, "$1-$2-$3 $4:$5:$6 UTC")}. <a href="/admin/backup">download backup</a></p>`93 : html`<p>No backup yet.</p>`;94 return c.html(95 adminPage(96 c,97 ctx,98 "status",99 html`<section class="repo-section markdown">${bucket}100${backup}101<p>Running kepr ${version}: ${lines} lines of TypeScript.</p></section>`,102 ),103 );104 });105106 app.get("/admin/backup", (c) => {107 const backup = newestBackupTarball(ctx.dataDir);108 if (!backup) return c.notFound();109 return c.body(backup.bytes, 200, {110 "Content-Type": "application/gzip",111 "Content-Disposition": `attachment; filename="kepr-backup-${backup.name}.tar.gz"`,112 });113 });114}