Pages to read a repo in a browser
Misha Kaletsky, 2026-11-24 20:22 UTC · a0d6f5cc6423249a2feff83f2b8a64e82ae69b55 · parent 1251027
6 files changed
- A README.md
- M app.ts
- M tests/app.test.mjs
- A tests/local-mind.mjs
- A tests/pages.test.mjs
- A tests/serve.mjs
A README.md
@@ -0,0 +1,26 @@ +# git + +The mind's repos at `git.<domain>`: a git remote, and pages to read a repo in a browser. +`config/worker.ts` mounts it and says which repos anyone may read. + +``` +git clone https://git.<domain>/repos/<name> + +/ the repos +/repos/<name> the repo's files and its README +/repos/<name>/tree/main/<path> a folder, or a file +/repos/<name>/commits the newest commits +/repos/<name>/commit/<oid> one commit: what it changed +``` + +All of it is `app.ts`: the remote, the pages as plain HTML, and the script that draws the file +tree, a file's colours and a commit's diffs. There is no build. + +## Try a change + +```sh +node tests/serve.mjs # the pages over the repos cloned beside this one +node --test "tests/*.test.mjs" +``` + +A push to `main` is live a few seconds later.
M app.ts
@@ -1,30 +1,54 @@ -// app.ts — A GIT REMOTE AT git.<domain>/repos/<name>, as config/worker.ts mounts it. +// app.ts — THE MIND'S REPOS AT git.<domain>, as config/worker.ts mounts it: a git remote for git +// itself, and pages for a person who reads a repo in a browser. // -// It is a pass-through. git's smart HTTP has three requests, and each goes to the repo's -// Cloudflare Artifacts remote as it came, body streamed, answer streamed back: +// GET / the repos +// GET /repos/<name> the repo's files and its README +// GET /repos/<name>/tree/main/<path> a folder of it, or a file +// GET /repos/<name>/commits its newest commits +// GET /repos/<name>/commit/<oid> one commit: what it changed // // GET /repos/<name>/info/refs?service=git-upload-pack | git-receive-pack // POST /repos/<name>/git-upload-pack clone, fetch // POST /repos/<name>/git-receive-pack push // -// GET / the repos that anyone may clone, as text +// WHO MAY READ. A repo that worker.ts lists as public is for anyone: its pages, and a clone with +// no credential. Any other repo's pages are for a member of the mind, and git needs the caller's +// own Artifacts token for it. A push needs that token for every repo. // -// It adds two things. The address is the mind's own. And a repo that worker.ts lists as public is -// read with no credential: the app adds a read token of its own, minted once and kept while it -// lasts. Every other request needs the caller's own Artifacts token, as git's password (any -// username): Artifacts checks it, not this file. +// THE REMOTE IS A PASS-THROUGH. Each of git's three requests goes to the repo's Cloudflare +// Artifacts remote as it came, body streamed, answer streamed back. The app adds two things. The +// address is the mind's own. And for a public repo it adds a read token of its own, minted once +// and kept while it lasts. Artifacts checks every token, not this file. // // THE READ TOKEN IS KEPT IN THE MIND'S KV, not in memory: most connections get a new isolate, so // memory alone would mint a token for almost every clone. A kv read takes 12 to 32 ms, a mint 150 -// (measured on tthq.app, 24 Nov 2026). +// (measured on tthq.app, 24 Nov 2026). What stops a push is Artifacts' own limit of 64 MiB a +// push, with the same words through this app as straight to Artifacts. // -// What stops a push is Artifacts' own limit of 64 MiB a push, with the same words through this -// app as straight to Artifacts. +// THE PAGES ARE PLAIN HTML, written in this file with no build. Each one reads the repo through +// the mind's own `itx` and is whole with no script: the names, the lists, a file's text. The +// script at the foot of this file then draws three things in their places, with components that +// the browser loads from a CDN: the file tree, a file or a diff with its colours (@pierre/trees, +// @pierre/diffs), and a README as markdown (@iterate-com/ui). +// +// A COMMIT'S PAGE COSTS TWO READS OF A WHOLE TREE, the commit's and its parent's: a repo answers +// with files, never with changes. A commit never changes, so the app keeps what it worked out in +// the mind's kv, and the next reader of that commit costs one kv read. +// +// Only `main` is shown, and a file as text. A page shows the names of members to anyone, as a +// clone does, and no address. +import type { RepoLogEntry } from "iterate/api"; import type { IterateConfigEntrypoint } from "iterate/sdk"; import { z } from "zod"; +type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">; +type Itx = ReturnType<Host["getItx"]>; +type Repo = ReturnType<Itx["repos"]["get"]>; + const GIT_PATH = /^(\/repos\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*?)\/(info\/refs|git-upload-pack|git-receive-pack)$/; +/** A repo's pages: its name, then `tree/main/<path>`, `commits` or `commit/<oid>`. */ +const PAGE_PATH = /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|commits|commit)(?:\/(.*))?)?$/; /** What git sends that Artifacts needs. A cookie or a stamp of the mind's never leaves. */ const REQUEST_HEADERS = [ @@ -41,6 +65,13 @@ /** A mint is billed: one token serves every anonymous read of the repo for this long. */ const READ_TOKEN_SECONDS = 3600; +/** How many commits the list shows, and how far back a commit's page finds a commit. */ +const COMMITS_SHOWN = 100; +const COMMITS_SEARCHED = 300; +/** The most text a commit's page carries, both sides of every file together. The files past it + * are named with no diff. */ +const DIFF_CHARACTERS_SHOWN = 600_000; + /** What the app keeps of a repo, in the mind's kv under `git-app:<repo>`: where Artifacts serves * it, and for a public repo a read token and the moment that token ends. */ const Kept = z.object({ @@ -48,86 +79,700 @@ readToken: z.object({ authorization: z.string(), until: z.number() }).optional(), }); -/** `public`: the repos that anyone may clone and fetch, by path (`/repos/<name>`). */ -export function gitApp({ public: publicRepos }: { public: string[] }) { +/** What the app keeps of a commit, under `git-app:commit:<repo>:<oid>`: what its page shows. */ +const KeptCommit = z.object({ + oid: z.string(), + parents: z.array(z.string()), + message: z.string(), + author: z.string(), + timestamp: z.number(), + changes: z.array( + z.object({ + path: z.string(), + status: z.enum(["added", "deleted", "modified"]), + /** The file's text before and after; null when the page shows no diff, and `note` says why. */ + sides: z.object({ before: z.string(), after: z.string() }).nullable(), + note: z.string().nullable(), + }), + ), +}); +type KeptCommit = z.infer<typeof KeptCommit>; + +/** `public`: the repos that anyone may read, clone and fetch, by path (`/repos/<name>`). + * `icon`: the answer for the mind's icon, and `theme`: the stylesheet that every app of the + * mind shares (theme.css of /repos/stdlib). worker.ts hands both over. */ +export function gitApp({ + public: publicRepos, + icon, + theme, +}: { + public: string[]; + icon: () => Response; + theme: string; +}) { return { - /** Every request on the app's host. No guard stands before it: Artifacts checks the caller's - * token, and a public repo is for anyone. */ - async fetch( - request: Request, - host: Pick<IterateConfigEntrypoint, "getItx">, - ): Promise<Response> { + /** Every request on the app's host. No guard stands before it: the app says who may read. */ + async fetch(request: Request, host: Host): Promise<Response> { const url = new URL(request.url); - // The app's own address, in a browser: the repos that anyone may clone, each as a command. - if (url.pathname === "/") { - const lines = publicRepos.map((repo) => ` git clone ${url.origin}${repo}`); - return new Response( - ["The repos of this mind that anyone may clone:", "", ...lines, ""].join("\n"), - { headers: { "content-type": "text/plain; charset=utf-8" } }, - ); - } - const match = GIT_PATH.exec(url.pathname); - if (!match) return new Response("git: clone or push at /repos/<name>\n", { status: 404 }); - // `/repos/<name>.git` is the same repo: a person may write the address either way - const repo = match[1]!.replace(/\.git$/, ""); - const verb = match[2]!; - const service = verb === "info/refs" ? url.searchParams.get("service") : verb; - if (service !== "git-upload-pack" && service !== "git-receive-pack") - return new Response("git: only smart HTTP is served here\n", { status: 403 }); + const wire = GIT_PATH.exec(url.pathname); + if (wire) return remote(request, url, wire, host, publicRepos); - const headers = new Headers(); - for (const name of REQUEST_HEADERS) { - const value = request.headers.get(name); - if (value) headers.set(name, value); - } - const anonymousRead = - !headers.has("authorization") && - service === "git-upload-pack" && - publicRepos.includes(repo); + const pathname = url.pathname.replace(/\/+$/, "") || "/"; + if (pathname === "/theme.css") + return new Response(theme, { + headers: { "content-type": "text/css; charset=utf-8", "cache-control": "no-cache" }, + }); + if (pathname === "/icon.svg") return icon(); + // the mind's sign-in, then back to the list, which then shows the member every repo + if (pathname === "/sign-in") + return host.auth.require(request) || Response.redirect(`${url.origin}/`, 302); + if (pathname === "/") return reposPage(request, url, host, publicRepos); - const now = Date.now(); - let kept: z.infer<typeof Kept>; + const match = PAGE_PATH.exec(pathname); + if (!match) return new Response("git: clone or push at /repos/<name>\n", { status: 404 }); + const repo = `/repos/${match[1]}`; + const isPublic = publicRepos.includes(repo); + const refused = isPublic ? null : host.auth.require(request); + if (refused) return refused; + + const view = { url, repo, isPublic }; try { using itx = host.getItx(); - const text = await itx.kv.get(`git-app:${repo}`); - const found = text ? Kept.parse(JSON.parse(text)) : null; - // a token that ends within a minute could end in the middle of this clone - const tokenLasts = Boolean(found?.readToken && found.readToken.until > now + 60_000); - // a request with its own token needs the remote alone; an anonymous read needs the token too - const enough = anonymousRead ? tokenLasts : true; - if (found && enough) kept = found; - else { - const artifacts = await itx.cfArtifacts.get(repo); - kept = { remote: found ? found.remote : await artifacts.remote() }; - if (anonymousRead) { - const token = await artifacts.createToken("read", READ_TOKEN_SECONDS); - kept.readToken = { - authorization: `Basic ${btoa(`x:${token.plaintext}`)}`, - until: now + READ_TOKEN_SECONDS * 1000, - }; - } - await itx.kv.put(`git-app:${repo}`, JSON.stringify(kept)); - } + const handle = itx.repos.get(repo); + if (match[2] === "commits") return await commitsPage(view, handle); + if (match[2] === "commit") return await commitPage(view, handle, itx, match[3] || ""); + const [branch, ...segments] = match[2] === "tree" ? (match[3] || "").split("/") : ["main"]; + if (branch !== "main") + return page(view, 404, "code", "Not found", note("Only main is shown here."), null); + const path = segments.filter(Boolean).map(decodeURIComponent).join("/"); + return await codePage(view, handle, path, url.searchParams.has("plain")); } catch (error) { const message = error instanceof Error ? error.message : String(error); - return new Response(`git: no repo at ${repo} (${message})\n`, { - status: /not found|10200/i.test(message) ? 404 : 502, - }); + // the repo's own words for a path that holds no repo, or held one + if (/: (not created|deleted)/.test(message)) + return page(view, 404, null, "Not found", note(`The mind has no repo ${match[1]}.`), null); + return page(view, 502, null, "Not read", note(`The repo was not read: ${message}`), null); } - if (anonymousRead && kept.readToken) headers.set("authorization", kept.readToken.authorization); + }, + }; +} - const upstream = await fetch(`${kept.remote}/${verb}${url.search}`, { - method: request.method, - headers, - body: request.body, - redirect: "manual", - }); - const answerHeaders = new Headers(); - for (const name of ANSWER_HEADERS) { - const value = upstream.headers.get(name); - if (value) answerHeaders.set(name, value); +// ── THE REMOTE ── + +async function remote( + request: Request, + url: URL, + wire: RegExpExecArray, + host: Host, + publicRepos: string[], +): Promise<Response> { + // `/repos/<name>.git` is the same repo: a person may write the address either way + const repo = wire[1]!.replace(/\.git$/, ""); + const verb = wire[2]!; + const service = verb === "info/refs" ? url.searchParams.get("service") : verb; + if (service !== "git-upload-pack" && service !== "git-receive-pack") + return new Response("git: only smart HTTP is served here\n", { status: 403 }); + + const headers = new Headers(); + for (const name of REQUEST_HEADERS) { + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + const anonymousRead = + !headers.has("authorization") && service === "git-upload-pack" && publicRepos.includes(repo); + + const now = Date.now(); + let kept: z.infer<typeof Kept>; + try { + using itx = host.getItx(); + const text = await itx.kv.get(`git-app:${repo}`); + const found = text ? Kept.parse(JSON.parse(text)) : null; + // a token that ends within a minute could end in the middle of this clone + const tokenLasts = Boolean(found?.readToken && found.readToken.until > now + 60_000); + // a request with its own token needs the remote alone; an anonymous read needs the token too + const enough = anonymousRead ? tokenLasts : true; + if (found && enough) kept = found; + else { + const artifacts = await itx.cfArtifacts.get(repo); + kept = { remote: found ? found.remote : await artifacts.remote() }; + if (anonymousRead) { + const token = await artifacts.createToken("read", READ_TOKEN_SECONDS); + kept.readToken = { + authorization: `Basic ${btoa(`x:${token.plaintext}`)}`, + until: now + READ_TOKEN_SECONDS * 1000, + }; } - return new Response(upstream.body, { status: upstream.status, headers: answerHeaders }); - }, + await itx.kv.put(`git-app:${repo}`, JSON.stringify(kept)); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return new Response(`git: no repo at ${repo} (${message})\n`, { + status: /not found|10200/i.test(message) ? 404 : 502, + }); + } + if (anonymousRead && kept.readToken) headers.set("authorization", kept.readToken.authorization); + + const upstream = await fetch(`${kept.remote}/${verb}${url.search}`, { + method: request.method, + headers, + body: request.body, + redirect: "manual", + }); + const answerHeaders = new Headers(); + for (const name of ANSWER_HEADERS) { + const value = upstream.headers.get(name); + if (value) answerHeaders.set(name, value); + } + return new Response(upstream.body, { status: upstream.status, headers: answerHeaders }); +} + +// ── THE PAGES ── + +/** What every page of a repo is drawn with: the request's address, the repo's path, and whether + * anyone may read it. */ +type View = { url: URL; repo: string; isPublic: boolean }; + +/** `/`: the repos, each with the command that clones it. Anyone sees the public ones, with no + * question to the mind. A member sees every repo. */ +async function reposPage( + request: Request, + url: URL, + host: Host, + publicRepos: string[], +): Promise<Response> { + const isMember = host.auth.require(request) === null; + let repos = publicRepos; + if (isMember) { + using itx = host.getItx(); + const all = (await itx.repos.list()).map(({ path }) => path); + repos = all.filter((path) => PAGE_PATH.test(path)).sort(); + } + const rows = repos.map((repo) => { + const tag = publicRepos.includes(repo) ? "" : ` <span class="tag">private</span>`; + return `<li><a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>${tag} <code class="clone">git clone ${esc(url.origin + repo)}</code></li>`; + }); + const signIn = isMember + ? "" + : `<p class="note"><a href="/sign-in">Sign in</a> to see the repos that are not public.</p>`; + const zone = zoneOf(url); + const main = `<h1>The repos of ${esc(zone)}</h1><ul class="repos">${rows.join("")}</ul>${signIn}`; + return page({ url, repo: null, isPublic: true }, 200, null, `The repos of ${zone}`, main, null); +} + +/** A folder of the repo at `main`, with its README, or a file. The file tree stands beside it. */ +async function codePage(view: View, handle: Repo, path: string, plain: boolean) { + const { repo } = view; + const { commitOid, paths } = await handle.listFiles(); + if (!commitOid) + return page(view, 200, "code", nameOf(repo), note("This repo has no commit yet."), null); + const isFile = paths.includes(path); + const under = path ? `${path}/` : ""; + const within = paths.filter((file) => file.startsWith(under)); + if (!isFile && within.length === 0) { + const missing = note(`${nameOf(repo)} has no file or folder ${path} on main.`); + return page(view, 404, "code", "Not found", missing, null); + } + + // the way here: the repo, each folder above, then this file or folder + const segments = path ? path.split("/") : []; + const crumbs = segments.map((segment, index) => + index === segments.length - 1 + ? `<b>${esc(segment)}</b>` + : `<a href="${treeHref(repo, segments.slice(0, index + 1).join("/"))}">${esc(segment)}</a>`, + ); + const top = `<a href="${esc(repo)}">${esc(nameOf(repo))}</a>`; + const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`; + const way = `<p class="crumbs">${[top, ...crumbs].join(" / ")}${at}</p>`; + + const content = isFile + ? await fileContent(view, handle, path, plain) + : await folderContent(view, handle, under, within); + const main = `<div class="code"><nav id="tree" aria-label="Files"></nav><div id="content">${way}${content}</div></div>`; + const title = path ? `${path} · ${nameOf(repo)}` : nameOf(repo); + return page(view, 200, "code", title, main, { repo, paths, path }); +} + +/** The folder's own entries, folders first, and its README under them. */ +async function folderContent(view: View, handle: Repo, under: string, within: string[]) { + const folders = new Set<string>(); + const files: string[] = []; + for (const file of within) { + const rest = file.slice(under.length); + const slash = rest.indexOf("/"); + if (slash < 0) files.push(rest); + else folders.add(rest.slice(0, slash)); + } + const row = (name: string, shown: string) => + `<li><a href="${treeHref(view.repo, under + name)}">${esc(shown)}</a></li>`; + const entries = [ + ...[...folders].sort().map((name) => row(name, `${name}/`)), + ...files.sort().map((name) => row(name, name)), + ]; + const readme = files.find((name) => /^readme(\.(md|markdown|txt))?$/i.test(name)); + const text = readme ? await handle.readFile(under + readme) : null; + const shown = + readme && text !== null + ? `<article class="readme"><h2>${esc(readme)}</h2>${fileText(under + readme, text, false)}</article>` + : ""; + return `<ul class="entries">${entries.join("")}</ul>${shown}`; +} + +/** The file's text. A markdown file is shown as it reads, and `?plain` shows its source. */ +async function fileContent(view: View, handle: Repo, path: string, plain: boolean) { + let text: string | null; + try { + text = await handle.readFile(path); + } catch (error) { + // the repo's own refusal of a file that is not text (an image, a font) + if (/is not text/.test(error instanceof Error ? error.message : "")) text = null; + else throw error; + } + if (text === null) return note("This file is not text, so it is not shown. A clone has it."); + const here = treeHref(view.repo, path); + const other = isMarkdown(path) + ? plain + ? `<p class="note"><a href="${here}">As it reads</a></p>` + : `<p class="note"><a href="${here}?plain">Its source</a></p>` + : ""; + return other + fileText(path, text, plain); +} + +/** A file's text as a `<pre>`, marked for the script: `data-markdown` is drawn as markdown (its + * links are read against `data-dir`, the file's folder), `data-file` with the file's colours. */ +function fileText(path: string, text: string, plain: boolean) { + const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; + const mark = + isMarkdown(path) && !plain ? `data-markdown data-dir="${esc(dir)}"` : `data-file="${esc(path)}"`; + return `<pre ${mark}>${esc(text)}</pre>`; +} + +/** The newest commits on `main`: each one's oid, the first line of its message, who and when. */ +async function commitsPage(view: View, handle: Repo) { + const commits = await handle.log({ limit: COMMITS_SHOWN }); + const rows = commits.map( + (commit) => + `<li><a href="${esc(view.repo)}/commit/${commit.oid}"><code>${commit.oid.slice(0, 7)}</code></a> ${esc(subjectOf(commit.message))} <span class="by">${esc(commit.author.name)}, ${utcStamp(commit.timestamp)}</span></li>`, + ); + const more = commits.length === COMMITS_SHOWN ? note(`The newest ${COMMITS_SHOWN} commits.`) : ""; + const list = rows.length ? `<ul class="commits">${rows.join("")}</ul>` : note("No commit yet."); + const main = `<h1>Commits on main</h1>${list}${more}`; + return page(view, 200, "commits", `Commits · ${nameOf(view.repo)}`, main, null); +} + +/** One commit: its message, and each file it changed against its first parent, as a diff. */ +async function commitPage(view: View, handle: Repo, itx: Itx, wanted: string) { + const { repo } = view; + if (!/^[0-9a-f]{7,40}$/.test(wanted)) + return page(view, 404, "commits", "Not found", note("That is no commit's oid."), null); + const keptText = wanted.length === 40 ? await itx.kv.get(`git-app:commit:${repo}:${wanted}`) : null; + let commit: KeptCommit; + if (keptText) commit = KeptCommit.parse(JSON.parse(keptText)); + else { + const found = (await handle.log({ limit: COMMITS_SEARCHED })).find(({ oid }) => + oid.startsWith(wanted), + ); + if (!found) { + const missing = note( + `${nameOf(repo)} has no commit ${wanted} among its newest ${COMMITS_SEARCHED}.`, + ); + return page(view, 404, "commits", "Not found", missing, null); + } + commit = { + oid: found.oid, + parents: found.parents, + message: found.message, + author: found.author.name, + timestamp: found.timestamp, + changes: await changesOf(handle, found), + }; + await itx.kv.put(`git-app:commit:${repo}:${commit.oid}`, JSON.stringify(commit)); + } + + const [subject, ...rest] = commit.message.trim().split("\n"); + const body = rest.join("\n").trim(); + const parents = commit.parents.map( + (oid) => `<a href="${esc(repo)}/commit/${oid}"><code>${oid.slice(0, 7)}</code></a>`, + ); + const from = + parents.length === 0 + ? "the first commit" + : parents.length === 1 + ? `parent ${parents[0]}` + : `a merge of ${parents.join(" and ")}, shown against ${parents[0]}`; + const letter = { added: "A", deleted: "D", modified: "M" }; + const names = commit.changes.map( + (change, index) => + `<li><span class="status ${change.status}">${letter[change.status]}</span> <a href="#diff-${index}">${esc(change.path)}</a></li>`, + ); + const diffs = commit.changes.map((change, index) => { + const shown = change.sides + ? `<div class="diff" data-diff="${index}"></div>` + : note(change.note || ""); + return `<section id="diff-${index}"><h2><span class="status ${change.status}">${letter[change.status]}</span> ${esc(change.path)}</h2>${shown}</section>`; + }); + const count = `${commit.changes.length} file${commit.changes.length === 1 ? "" : "s"} changed`; + const main = [ + `<article class="commit"><h1>${esc(subject || "")}</h1>`, + body ? `<pre class="message">${esc(body)}</pre>` : "", + `<p class="by">${esc(commit.author)}, ${utcStamp(commit.timestamp)} · <code>${commit.oid}</code> · ${from}</p>`, + `<p>${count}</p><ul class="changes">${names.join("")}</ul>${diffs.join("")}</article>`, + ].join(""); + // the script draws each diff from the two texts + const data = { + diffs: commit.changes.map(({ path, sides }) => (sides ? { path, ...sides } : null)), }; + const title = `${subject} · ${nameOf(repo)}`; + return page(view, 200, "commits", title, main, data); } + +/** The files a commit changed against its first parent, each with both texts while the page has + * room for them. */ +async function changesOf( + handle: Repo, + commit: Pick<RepoLogEntry, "oid" | "parents">, +): Promise<KeptCommit["changes"]> { + const parent = commit.parents[0]; + // The parent first: a repo holds the files of the commit it read last, and the newer one is + // the likelier next read. + const before = parent ? await handle.files({ commitOid: parent }) : {}; + const after = await handle.files({ commitOid: commit.oid }); + let room = DIFF_CHARACTERS_SHOWN; + const changes: KeptCommit["changes"] = []; + for (const path of Object.keys({ ...before, ...after }).sort()) { + const was = Object.hasOwn(before, path) ? before[path]! : null; + const is = Object.hasOwn(after, path) ? after[path]! : null; + // a file that is not text comes as `{ base64 }`: the same bytes are the same file + const same = + typeof was === "string" || typeof is === "string" + ? was === is + : was !== null && is !== null && was.base64 === is.base64; + if (same) continue; + const status = was === null ? "added" : is === null ? "deleted" : "modified"; + if ((was !== null && typeof was !== "string") || (is !== null && typeof is !== "string")) { + changes.push({ path, status, sides: null, note: "Not text, so no diff is shown." }); + continue; + } + const sides = { before: was || "", after: is || "" }; + const characters = sides.before.length + sides.after.length; + if (characters > room) { + const large = "Not shown: the commit is larger than this page shows. A clone has it."; + changes.push({ path, status, sides: null, note: large }); + continue; + } + room -= characters; + changes.push({ path, status, sides, note: null }); + } + return changes; +} + +// ── WHAT EVERY PAGE IS MADE OF ── + +/** One page: the head, the row that says where the reader is, `main`, and the script with + * `data`, what it draws from. `tab` is the row's link that is marked as the one shown. */ +function page( + view: { url: URL; repo: string | null; isPublic: boolean }, + status: number, + tab: "code" | "commits" | null, + title: string, + main: string, + data: unknown, +): Response { + const { url, repo } = view; + const zone = zoneOf(url); + const current = (name: string) => (tab === name ? ` aria-current="page"` : ""); + const where = repo + ? [ + `<p><a href="/">${esc(zone)}</a> / <a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>`, + view.isPublic ? "" : ` <span class="tag">private</span>`, + `</p><nav><a href="${esc(repo)}"${current("code")}>Code</a>`, + `<a href="${esc(repo)}/commits"${current("commits")}>Commits</a></nav>`, + `<code class="clone">git clone ${esc(url.origin + repo)}</code>`, + ].join("") + : `<p><a href="/">${esc(zone)}</a></p>`; + const html = `<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>${esc(title)} · ${esc(zone)}</title> + <link rel="icon" href="/icon.svg" type="image/svg+xml" /> + <link rel="preconnect" href="https://esm.iterate.com" crossorigin /> + <script type="importmap">${IMPORT_MAP}</script> + <link rel="stylesheet" crossorigin href="${UI}/dist/styles.css" /> + <link rel="stylesheet" href="/theme.css" /> + <script> + if (getComputedStyle(document.documentElement).colorScheme === "dark") + document.documentElement.classList.add("dark"); + </script> + <style>${STYLE}</style> + </head> + <body> + <header class="where">${where}</header> + <main>${main}</main> + <script type="application/json" id="data">${JSON.stringify(data).replace(/</g, "\\u003c")}</script> + <script type="module">${SCRIPT}</script> + </body> +</html> +`; + return new Response(html, { + status, + headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" }, + }); +} + +const ESCAPES: Record<string, string> = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", +}; +const esc = (text: string) => text.replace(/[&<>"']/g, (character) => ESCAPES[character]!); +const note = (text: string) => `<p class="note">${esc(text)}</p>`; +const nameOf = (repo: string) => repo.slice("/repos/".length); +/** The zone the app is on: its hostname is one label under it. */ +const zoneOf = (url: URL) => url.hostname.split(".").slice(1).join("."); +const isMarkdown = (path: string) => /\.(md|markdown)$/i.test(path); +const subjectOf = (message: string) => message.trim().split("\n")[0] || ""; +/** The page of a file or a folder; the repo's own page for its root. */ +const treeHref = (repo: string, path: string) => + esc(path ? `${repo}/tree/main/${path.split("/").map(encodeURIComponent).join("/")}` : repo); +/** A moment as `2026-11-24 15:39 UTC`: the same for every reader. */ +const utcStamp = (timestamp: number) => + `${new Date(timestamp).toISOString().slice(0, 16).replace("T", " ")} UTC`; + +/** iterate's components, pinned to one build: the one the Dash pins. */ +const UI = "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390"; +const IMPORT_MAP = JSON.stringify({ + imports: { + "@iterate-com/ui/": `${UI}/`, + react: `${UI}/react`, + "react/": `${UI}/react/`, + "react-dom": `${UI}/react-dom`, + "react-dom/": `${UI}/react-dom/`, + "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom", + "@pierre/trees/react": "https://esm.iterate.com/@pierre/trees@1.0.0/react?external=react,react-dom", + "@pierre/diffs/react": "https://esm.iterate.com/@pierre/diffs@1.7.1/react?external=react,react-dom", + }, +}); + +/** The pages' own look, over the UI kit's stylesheet (which resets every element) and the mind's + * theme.css, whose colours these are. */ +const STYLE = ` + body { margin: 0; font-size: 0.875rem; } + a { text-decoration: underline; text-underline-offset: 2px; } + code, pre { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.75rem; } + h1 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.75rem; } + .where { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 1.5rem; + padding: 0.625rem 1rem; border-bottom: 1px solid var(--border); } + .where nav { display: flex; gap: 1rem; } + .where nav a { text-decoration: none; color: var(--muted-foreground); } + .where nav a[aria-current] { color: var(--foreground); font-weight: 600; } + .where .clone { margin-left: auto; } + .clone { color: var(--muted-foreground); user-select: all; } + .tag { border: 1px solid var(--border); border-radius: 999px; padding: 0 0.5rem; + font-size: 0.75rem; color: var(--muted-foreground); } + .note, .by, .at { color: var(--muted-foreground); } + main > h1, main > ul, main > p, .commit { margin-left: 1rem; margin-right: 1rem; } + main > h1 { margin-top: 1rem; } + .repos li, .commits li { padding: 0.25rem 0; } + .repos .clone { margin-left: 0.75rem; } + + .code { display: grid; grid-template-columns: 17rem minmax(0, 1fr); } + #tree { position: sticky; top: 0; height: 100vh; overflow: auto; + border-right: 1px solid var(--border); } + #content { min-width: 0; padding: 0.875rem 1.25rem 3rem; } + @media (max-width: 48rem) { .code { display: block; } #tree { display: none; } } + .crumbs { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.35rem; + margin-bottom: 0.75rem; } + .crumbs .at { margin-left: auto; font-size: 0.75rem; } + .entries { border: 1px solid var(--border); border-radius: 0.5rem; overflow: hidden; } + .entries li + li { border-top: 1px solid var(--border); } + .entries a { display: block; padding: 0.3rem 0.75rem; text-decoration: none; + font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.8125rem; } + .entries a:hover { background: var(--accent); } + .readme { margin-top: 1.25rem; border: 1px solid var(--border); border-radius: 0.5rem; } + .readme > h2 { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--border); + font-size: 0.75rem; color: var(--muted-foreground); } + .readme > :not(h2), .markdown { padding: 1rem 1.25rem; } + #content > .markdown { padding: 0; } + pre { overflow: auto; line-height: 1.5; } + #content > pre, #content > .file { border: 1px solid var(--border); border-radius: 0.5rem; } + #content > pre { padding: 0.75rem; } + #content > .file { overflow: hidden; } + #content > .note { margin-bottom: 0.5rem; font-size: 0.75rem; } + + .commit { margin-top: 1rem; margin-bottom: 3rem; } + .commit .message { margin-bottom: 0.75rem; white-space: pre-wrap; } + .commit > p { margin-bottom: 0.5rem; } + .changes { margin-bottom: 1.5rem; } + .changes li, .commit h2 { font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.8125rem; } + .commit section { margin-top: 1.25rem; border: 1px solid var(--border); + border-radius: 0.5rem; overflow: hidden; } + .commit h2 { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--border); } + .commit section .note { padding: 0.5rem 0.75rem; } + .diff { min-height: 4rem; } + .status { font-weight: 600; } + .status.added { color: light-dark(oklch(0.5 0.15 150), oklch(0.75 0.15 150)); } + .status.deleted { color: var(--destructive); } + .status.modified { color: light-dark(oklch(0.5 0.13 250), oklch(0.75 0.13 250)); } +`; + +/** WHAT THE BROWSER RUNS. The page is whole without it. It draws the file tree, each file and + * README in the place of its `<pre>`, and each diff of a commit when the reader scrolls near + * it. On a page of files a click on a file or a folder fetches that page and takes its content + * alone, so the tree stays as the reader left it. + * + * It is text in a template, so it has no backtick and no dollar-brace of its own. */ +const SCRIPT = String.raw` + import { createElement as h } from "react"; + import { createRoot } from "react-dom/client"; + + const data = JSON.parse(document.getElementById("data").textContent); + // The page's look is the mind's theme.css. Pierre's components would follow the visitor's + // system, so they are told. + const dark = getComputedStyle(document.documentElement).colorScheme === "dark"; + const pierre = { + theme: { light: "pierre-light", dark: "pierre-dark" }, + themeType: dark ? "dark" : "light", + disableFileHeader: true, + }; + + // what is drawn in the content, to take down when the content is replaced + let drawn = []; + function draw(place, node) { + const root = createRoot(place); + root.render(node); + drawn.push(root); + } + // The <pre> stays until the component has drawn something, so the text never blinks away. + function inPlaceOf(pre, className) { + const place = document.createElement("div"); + place.className = className; + pre.after(place); + const waiting = new ResizeObserver(() => { + if (place.offsetHeight === 0) return; + waiting.disconnect(); + pre.remove(); + }); + waiting.observe(place); + return place; + } + + async function drawContent() { + const content = document.getElementById("content"); + if (!content) return; + const files = [...content.querySelectorAll("pre[data-file]")]; + const markdowns = [...content.querySelectorAll("pre[data-markdown]")]; + if (files.length) { + const { File } = await import("@pierre/diffs/react"); + for (const pre of files.filter((pre) => pre.isConnected)) { + const file = { name: pre.dataset.file, contents: pre.textContent }; + draw(inPlaceOf(pre, "file"), h(File, { file, options: pierre })); + } + } + if (markdowns.length) { + const { Markdown } = await import("@iterate-com/ui/components/agent-chat/chat-parts"); + for (const pre of markdowns.filter((pre) => pre.isConnected)) { + const place = inPlaceOf(pre, "markdown"); + place.dataset.dir = pre.dataset.dir; + draw(place, h(Markdown, null, pre.textContent)); + } + } + } + + // A commit's diffs, each drawn when the reader scrolls near it: a commit may change many files. + async function drawDiffs() { + const places = document.querySelectorAll("[data-diff]"); + if (places.length === 0) return; + const { MultiFileDiff } = await import("@pierre/diffs/react"); + const near = new IntersectionObserver( + (entries) => { + for (const entry of entries.filter((entry) => entry.isIntersecting)) { + near.unobserve(entry.target); + const { path, before, after } = data.diffs[Number(entry.target.dataset.diff)]; + const sides = { + oldFile: { name: path, contents: before }, + newFile: { name: path, contents: after }, + }; + draw(entry.target, h(MultiFileDiff, { ...sides, options: { ...pierre, diffStyle: "unified" } })); + } + }, + { rootMargin: "800px" }, + ); + for (const place of places) near.observe(place); + } + + // ── a page of files: the tree, and a click that takes the next page's content alone ── + + const treePlace = document.getElementById("tree"); + const treeHref = (path) => + path ? data.repo + "/tree/main/" + path.split("/").map(encodeURIComponent).join("/") : data.repo; + const shownPath = () => + decodeURIComponent(location.pathname.slice((data.repo + "/tree/main/").length)); + let tree; + + async function visit(href, push) { + const answer = await fetch(href); + const next = new DOMParser().parseFromString(await answer.text(), "text/html"); + const content = next.getElementById("content"); + // a page with no content of this kind (a sign-in, an error) is shown whole + if (!content) return location.assign(href); + for (const root of drawn) root.unmount(); + drawn = []; + document.getElementById("content").replaceWith(document.adoptNode(content)); + document.title = next.title; + if (push) history.pushState(null, "", href); + scrollTo(0, 0); + const item = tree && tree.getItem(shownPath()); + if (item && !item.isDirectory() && !item.isSelected()) item.select(); + await drawContent(); + } + + async function drawTree() { + if (!treePlace) return; + const { FileTree, useFileTree } = await import("@pierre/trees/react"); + const files = new Set(data.paths); + // the folders above what is shown are open; a small repo is open whole + const segments = data.path.split("/").filter(Boolean); + const above = segments.map((_, index) => segments.slice(0, index + 1).join("/")); + function Tree() { + const { model } = useFileTree({ + paths: data.paths, + initialExpansion: data.paths.length > 150 ? "closed" : "open", + initialExpandedPaths: above, + initialSelectedPaths: files.has(data.path) ? [data.path] : [], + search: true, + onSelectionChange: (paths) => { + if (files.has(paths[0]) && paths[0] !== shownPath()) visit(treeHref(paths[0]), true); + }, + }); + tree = model; + return h(FileTree, { model, style: { colorScheme: "inherit", height: "100%" } }); + } + createRoot(treePlace).render(h(Tree)); + + addEventListener("popstate", () => visit(location.href, false)); + document.addEventListener("click", (event) => { + const plain = event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey; + const link = plain && !event.defaultPrevented && event.target.closest("#content a[href]"); + if (!link) return; + // a link in a README is written against the folder of the file it is in + const written = link.getAttribute("href"); + const markdown = link.closest(".markdown"); + const relative = markdown && !/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(written); + const dir = markdown && markdown.dataset.dir ? treeHref(markdown.dataset.dir) + "/" : data.repo + "/tree/main/"; + const folder = location.origin + dir; + const url = new URL(relative ? new URL(written, folder) : link.href); + const ofThisRepo = url.pathname === data.repo || url.pathname.startsWith(data.repo + "/tree/"); + if (url.origin !== location.origin || !ofThisRepo) return; + event.preventDefault(); + visit(url.pathname + url.search, true); + }); + } + + drawTree(); + drawContent(); + drawDiffs(); +`;
M tests/app.test.mjs
@@ -1,6 +1,7 @@ -// tests/app.test.mjs — the git app (../app.ts) between a git client and a repo's Artifacts remote. -// The remote here is a local HTTP server that records what reaches it, and the mind is a fake -// `itx` with a kv and the Artifacts verbs the app calls. The app's own fetch goes to that server. +// tests/app.test.mjs — the git remote of the app (../app.ts), between a git client and a repo's +// Artifacts remote. The remote here is a local HTTP server that records what reaches it, and the +// mind is a fake `itx` with a kv and the Artifacts verbs the app calls. The app's own fetch goes +// to that server. pages.test.mjs has the pages a browser reads. // Run it from the repo's root with `node --test "tests/*.test.mjs"`. import assert from "node:assert/strict"; import { createServer } from "node:http"; @@ -10,7 +11,7 @@ test("anyone clones a public repo: the app adds a read token of its own, minted once and kept in the mind's kv", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const refs = await git.fetch( new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), @@ -47,7 +48,7 @@ test("a repo that is not listed as public is read with the caller's own token, and with none it gets the remote's 401", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const refused = await git.fetch( new Request("https://git.example.com/repos/config/info/refs?service=git-upload-pack"), @@ -94,7 +95,7 @@ test("a push needs the caller's own token, to a public repo too: the app adds none", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const refused = await git.fetch( new Request("https://git.example.com/repos/kernel/info/refs?service=git-receive-pack"), @@ -125,7 +126,7 @@ test("a read token that is about to end is replaced, and the repo's remote is not asked for again", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const read = () => git.fetch( new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), @@ -146,33 +147,10 @@ assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]); }); -test("the app's own address lists the repos that anyone may clone, each as the command that clones it", async () => { - await using remote = await artifactsRemote(); - const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel", "/repos/stdlib"] }); - - const index = await git.fetch(new Request("https://git.example.com/"), mind); - - assert.equal(index.status, 200); - assert.equal( - await index.text(), - [ - "The repos of this mind that anyone may clone:", - "", - " git clone https://git.example.com/repos/kernel", - " git clone https://git.example.com/repos/stdlib", - "", - ].join("\n"), - ); - // a list of names from the config: the mind is asked nothing - assert.deepEqual(remote.requests, []); - assert.deepEqual(mind.minted, []); -}); - test("what is no git request is refused before the mind is asked anything", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const page = await git.fetch(new Request("https://git.example.com/about"), mind); assert.equal(page.status, 404); @@ -189,7 +167,7 @@ test("a repo the mind does not have is not found", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); - const git = gitApp({ public: ["/repos/kernel"] }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); const answer = await git.fetch( new Request("https://git.example.com/repos/missing/info/refs?service=git-upload-pack"), @@ -201,6 +179,9 @@ }); // ── the fixtures ── + +/** What worker.ts hands the app for its pages, which no test here reads. */ +const look = { icon: () => new Response("the icon"), theme: "" }; /** The mind as the app reaches it: a kv, and the Artifacts repos `kernel` and `config`, served * by `remote`. It records each token it mints and each repo whose remote it was asked for. */
A tests/local-mind.mjs
@@ -0,0 +1,123 @@ +// tests/local-mind.mjs — A MIND'S REPOS FROM FOLDERS ON THIS MACHINE. It answers what the app's +// pages ask of the mind (../app.ts): the repo verbs they call, a kv, and who is a member. Each +// answer comes from git itself, run in the folder that holds the repo. serve.mjs shows the app +// over the repos cloned beside this one, and pages.test.mjs over a repo it makes. +import { execFileSync } from "node:child_process"; + +/** `folders`: where each repo is, by its path in the mind (`/repos/<name>`). `member`: whether + * the visitor is one. `kv` is the mind's kv as the app left it, and `asked` each call the app + * made of a repo or of the list, in order (`files /repos/kernel`). */ +export function localMind({ folders, member }) { + const kv = {}; + const asked = []; + const git = (repo, args, input) => + execFileSync("git", ["-C", folders[repo], ...args], { input, maxBuffer: 2 ** 30 }); + const tipOf = (repo) => { + try { + return git(repo, ["rev-parse", "--verify", "--quiet", "HEAD"]).toString().trim(); + } catch { + return null; // a repo with no commit yet + } + }; + + /** Every file of a commit: text, or `{ base64 }` for a file that is not text. */ + const filesAt = (repo, commitOid) => { + const blobs = git(repo, ["ls-tree", "-r", "-z", commitOid]) + .toString() + .split("\0") + .filter(Boolean) + .map((line) => { + const [meta, path] = line.split("\t"); + const [, type, oid] = meta.split(" "); + return { path, type, oid }; + }) + .filter(({ type }) => type === "blob"); + // one git process for every blob: `<oid> blob <size>\n<bytes>\n`, in the order asked + const packed = git(repo, ["cat-file", "--batch"], blobs.map(({ oid }) => oid).join("\n") + "\n"); + const files = {}; + let at = 0; + for (const { path } of blobs) { + const headerEnd = packed.indexOf("\n", at); + const size = Number(packed.subarray(at, headerEnd).toString().split(" ")[2]); + const bytes = packed.subarray(headerEnd + 1, headerEnd + 1 + size); + files[path] = bytes.includes(0) ? { base64: bytes.toString("base64") } : bytes.toString(); + at = headerEnd + 1 + size + 1; + } + return files; + }; + + const handleOf = (repo) => { + // the mind's own words for a path that holds no repo + const created = (verb) => { + asked.push(`${verb} ${repo}`); + if (!folders[repo]) throw new Error(`repo ${repo}: not created`); + }; + return { + async listFiles() { + created("listFiles"); + const commitOid = tipOf(repo); + return { commitOid, paths: commitOid ? Object.keys(filesAt(repo, commitOid)).sort() : [] }; + }, + async readFile(path, options) { + created("readFile"); + const commitOid = options ? options.commitOid : tipOf(repo); + const files = commitOid ? filesAt(repo, commitOid) : {}; + if (!Object.hasOwn(files, path)) return null; + if (typeof files[path] !== "string") + throw new Error(`repo: ${path} is not text: read it with readBytes`); + return files[path]; + }, + async files(options) { + created("files"); + return filesAt(repo, options.commitOid); + }, + async log({ limit }) { + created("log"); + if (!tipOf(repo)) return []; + const format = ["%H", "%P", "%an", "%ae", "%at", "%B"].join("%x1f") + "%x1e"; + return git(repo, ["log", "-n", String(limit), `--format=${format}`]) + .toString() + .split("\x1e") + .map((entry) => entry.trim()) + .filter(Boolean) + .map((entry) => { + const [oid, parents, name, email, seconds, message] = entry.split("\x1f"); + return { + oid, + parents: parents.split(" ").filter(Boolean), + author: { name, email }, + committer: { name, email }, + timestamp: Number(seconds) * 1000, + message, + }; + }); + }, + }; + }; + + const itx = { + kv: { + get: async (key) => kv[key] || null, + put: async (key, value) => { + kv[key] = value; + }, + }, + repos: { + get: handleOf, + list: async () => { + asked.push("list"); + return Object.keys(folders).map((path) => ({ path, createdAt: "" })); + }, + }, + [Symbol.dispose]() {}, + }; + return { + kv, + asked, + getItx: () => itx, + auth: { + // null lets a member in; anyone else gets the mind's sign-in, which here is a bare 401 + require: () => (member ? null : new Response("Sign in\n", { status: 401 })), + }, + }; +}
A tests/pages.test.mjs
@@ -0,0 +1,321 @@ +// tests/pages.test.mjs — the pages a person reads a repo with (../app.ts). Each test makes a repo +// with git itself, and local-mind.mjs answers the mind's part from it. The pages are whole +// without their script, so each test reads the HTML that the app answers. +// Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { gitApp } from "../app.ts"; +import { localMind } from "./local-mind.mjs"; + +test("a repo's own page lists its files, folders first, shows its README and says how to clone it", async () => { + using kernel = repoWith([ + { + message: "Start", + files: { + "README.md": "# kernel\n\nThe platform, and [its SDK](core/sdk.ts).\n", + "core/sdk.ts": "export const one = 1;\n", + "core/lib/api.ts": "export type Api = {};\n", + "package.json": "{}\n", + }, + }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + + const answer = await git.fetch(new Request("https://git.example.com/repos/kernel"), mind); + const html = await answer.text(); + + assert.equal(answer.status, 200); + assert.deepEqual(linksIn(html, "entries"), [ + ["/repos/kernel/tree/main/core", "core/"], + ["/repos/kernel/tree/main/README.md", "README.md"], + ["/repos/kernel/tree/main/package.json", "package.json"], + ]); + // the README's text, marked for the script to draw as markdown, its links read against the root + assert.ok( + html.includes( + `<article class="readme"><h2>README.md</h2><pre data-markdown data-dir=""># kernel\n\nThe platform, and [its SDK](core/sdk.ts).\n</pre>`, + ), + ); + assert.ok(html.includes("git clone https://git.example.com/repos/kernel")); + assert.ok(html.includes(`main at <a href="/repos/kernel/commit/${kernel.commits[0]}">`)); + // what the file tree is drawn from + assert.deepEqual(dataOf(html), { + repo: "/repos/kernel", + paths: ["README.md", "core/lib/api.ts", "core/sdk.ts", "package.json"], + path: "", + }); +}); + +test("a folder's page lists what is in it, and a file's page has the file's text and the way back up", async () => { + using kernel = repoWith([ + { + message: "Start", + files: { + "core/sdk.ts": "export const html = `<b>${1 < 2 && \"yes\"}</b>`;\n", + "core/lib/api.ts": "export type Api = {};\n", + }, + }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const read = async (path) => + (await git.fetch(new Request(`https://git.example.com${path}`), mind)).text(); + + assert.deepEqual(linksIn(await read("/repos/kernel/tree/main/core"), "entries"), [ + ["/repos/kernel/tree/main/core/lib", "lib/"], + ["/repos/kernel/tree/main/core/sdk.ts", "sdk.ts"], + ]); + + const file = await read("/repos/kernel/tree/main/core/sdk.ts"); + // the text is text: nothing in a file is markup of the page + assert.ok( + file.includes( + `<pre data-file="core/sdk.ts">export const html = \`<b>\${1 < 2 && "yes"}</b>\`;\n</pre>`, + ), + ); + assert.deepEqual(linksIn(file, "crumbs").slice(0, 2), [ + ["/repos/kernel", "kernel"], + ["/repos/kernel/tree/main/core", "core"], + ]); + assert.equal(dataOf(file).path, "core/sdk.ts"); +}); + +test("a markdown file is shown as it reads, and with ?plain as its source", async () => { + using home = repoWith([{ message: "Start", files: { "todo/first.md": "# First\n" } }]); + const mind = localMind({ folders: { "/repos/home": home.folder }, member: false }); + const git = gitApp({ public: ["/repos/home"], ...look }); + const read = async (path) => + (await git.fetch(new Request(`https://git.example.com${path}`), mind)).text(); + + const shown = await read("/repos/home/tree/main/todo/first.md"); + assert.ok(shown.includes(`<pre data-markdown data-dir="todo"># First\n</pre>`)); + assert.ok(shown.includes(`<a href="/repos/home/tree/main/todo/first.md?plain">Its source</a>`)); + + const source = await read("/repos/home/tree/main/todo/first.md?plain"); + assert.ok(source.includes(`<pre data-file="todo/first.md"># First\n</pre>`)); +}); + +test("the commits are listed newest first, each with its oid, the first line of its message, who and when, and no address", async () => { + using kernel = repoWith([ + { message: "Start\n\nThe first files.", files: { "a.ts": "1\n" } }, + { message: "Add b", files: { "b.ts": "2\n" } }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + + const answer = await git.fetch(new Request("https://git.example.com/repos/kernel/commits"), mind); + const html = await answer.text(); + + const [start, addB] = kernel.commits; + assert.deepEqual(linksIn(html, "commits"), [ + [`/repos/kernel/commit/${addB}`, addB.slice(0, 7)], + [`/repos/kernel/commit/${start}`, start.slice(0, 7)], + ]); + assert.ok(html.includes(`</a> Add b <span class="by">Ada Author, 2026-11-24 10:01 UTC</span>`)); + assert.ok(html.includes(`</a> Start <span class="by">Ada Author, 2026-11-24 10:00 UTC</span>`)); + assert.ok(!html.includes("ada@example.com")); +}); + +test("a commit's page names each file it changed and carries both texts of each, and the second reader costs the repo nothing", async () => { + using kernel = repoWith([ + { message: "Start", files: { "kept.ts": "same\n", "changed.ts": "old\n", "gone.ts": "bye\n" } }, + { + message: "Change three files\n\nOne changed, one came, one went.", + files: { "changed.ts": "new\n", "came.ts": "hello\n", "gone.ts": null }, + }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const [start, change] = kernel.commits; + const read = () => + git.fetch(new Request(`https://git.example.com/repos/kernel/commit/${change}`), mind); + + const html = await (await read()).text(); + + assert.ok(html.includes("<h1>Change three files</h1>")); + assert.ok(html.includes(`<pre class="message">One changed, one came, one went.</pre>`)); + assert.ok(html.includes(`parent <a href="/repos/kernel/commit/${start}">`)); + assert.ok(html.includes("3 files changed")); + assert.deepEqual(linksIn(html, "changes"), [ + ["#diff-0", "came.ts"], + ["#diff-1", "changed.ts"], + ["#diff-2", "gone.ts"], + ]); + assert.deepEqual(dataOf(html), { + diffs: [ + { path: "came.ts", before: "", after: "hello\n" }, + { path: "changed.ts", before: "old\n", after: "new\n" }, + { path: "gone.ts", before: "bye\n", after: "" }, + ], + }); + + // a commit never changes: the app kept what it worked out, and reads the repo no more + const asked = [...mind.asked]; + assert.equal(await (await read()).text(), html); + assert.deepEqual(mind.asked, asked); + assert.deepEqual(Object.keys(mind.kv), [`git-app:commit:/repos/kernel:${change}`]); +}); + +test("a commit is found by the start of its oid, and a commit larger than the page shows names its files with no diff", async () => { + using kernel = repoWith([ + { message: "Start", files: { "small.ts": "1\n" } }, + { message: "A large file", files: { "large.txt": "x".repeat(700_000), "small.ts": "2\n" } }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + + const short = kernel.commits[1].slice(0, 7); + const answer = await git.fetch( + new Request(`https://git.example.com/repos/kernel/commit/${short}`), + mind, + ); + const html = await answer.text(); + + assert.deepEqual(linksIn(html, "changes"), [ + ["#diff-0", "large.txt"], + ["#diff-1", "small.ts"], + ]); + assert.ok(html.includes("Not shown: the commit is larger than this page shows.")); + assert.deepEqual(dataOf(html), { + diffs: [null, { path: "small.ts", before: "1\n", after: "2\n" }], + }); +}); + +test("a repo that is not public is for members: anyone else gets the mind's sign-in, and the repo is not read", async () => { + using config = repoWith([{ message: "Start", files: { "worker.ts": "export default {};\n" } }]); + const folders = { "/repos/config": config.folder }; + const git = gitApp({ public: [], ...look }); + const read = (mind) => git.fetch(new Request("https://git.example.com/repos/config"), mind); + + const anyone = localMind({ folders, member: false }); + const refused = await read(anyone); + assert.equal(refused.status, 401); + assert.equal(await refused.text(), "Sign in\n"); + assert.deepEqual(anyone.asked, []); + + const member = localMind({ folders, member: true }); + const html = await (await read(member)).text(); + assert.deepEqual(linksIn(html, "entries"), [["/repos/config/tree/main/worker.ts", "worker.ts"]]); + assert.ok(html.includes(`<span class="tag">private</span>`)); +}); + +test("the app's own address lists the repos: the public ones to anyone, with no question to the mind, and every repo to a member", async () => { + using kernel = repoWith([{ message: "Start", files: { "a.ts": "1\n" } }]); + const folders = { "/repos/kernel": kernel.folder, "/repos/config": kernel.folder }; + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const read = async (mind) => + (await git.fetch(new Request("https://git.example.com/"), mind)).text(); + + const anyone = localMind({ folders, member: false }); + const forAnyone = await read(anyone); + assert.deepEqual(linksIn(forAnyone, "repos"), [["/repos/kernel", "kernel"]]); + assert.ok(forAnyone.includes("git clone https://git.example.com/repos/kernel")); + assert.ok(forAnyone.includes(`<a href="/sign-in">Sign in</a>`)); + assert.deepEqual(anyone.asked, []); + + const forMember = await read(localMind({ folders, member: true })); + assert.deepEqual(linksIn(forMember, "repos"), [ + ["/repos/config", "config"], + ["/repos/kernel", "kernel"], + ]); + assert.ok(forMember.includes(`<b>config</b></a> <span class="tag">private</span>`)); + assert.ok(!forMember.includes("/sign-in")); +}); + +test("what is not there is not found: a path, another branch, a commit, a repo, and a file that is not text says so", async () => { + using kernel = repoWith([ + { message: "Start", files: { "a.ts": "1\n", "logo.png": Buffer.from([137, 80, 78, 71, 0, 1]) } }, + ]); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: true }); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const read = async (path) => { + const answer = await git.fetch(new Request(`https://git.example.com${path}`), mind); + return { status: answer.status, html: await answer.text() }; + }; + + const noPath = await read("/repos/kernel/tree/main/nope.ts"); + assert.equal(noPath.status, 404); + assert.ok(noPath.html.includes("kernel has no file or folder nope.ts on main.")); + + const noBranch = await read("/repos/kernel/tree/next/a.ts"); + assert.equal(noBranch.status, 404); + assert.ok(noBranch.html.includes("Only main is shown here.")); + + const noCommit = await read(`/repos/kernel/commit/${"0".repeat(40)}`); + assert.equal(noCommit.status, 404); + + const noRepo = await read("/repos/missing"); + assert.equal(noRepo.status, 404); + assert.ok(noRepo.html.includes("The mind has no repo missing.")); + + const image = await read("/repos/kernel/tree/main/logo.png"); + assert.equal(image.status, 200); + assert.ok(image.html.includes("This file is not text, so it is not shown.")); +}); + +// ── the fixtures ── + +/** What worker.ts hands the app: the mind's icon, and the stylesheet every app shares. */ +const look = { icon: () => new Response("the icon"), theme: ":root { color-scheme: light; }" }; + +/** The links in the element of the page with that class, each as [href, text]. */ +function linksIn(html, className) { + const start = html.indexOf(`class="${className}"`); + assert.ok(start > 0, `the page has an element with class ${className}`); + const end = html.indexOf(className === "crumbs" ? "</p>" : "</ul>", start); + const links = html.slice(start, end).matchAll(/<a href="([^"]*)"[^>]*>(.*?)<\/a>/g); + return [...links].map(([, href, text]) => [href, text.replace(/<[^>]+>/g, "")]); +} + +/** What the page hands its script. */ +function dataOf(html) { + return JSON.parse(/<script type="application\/json" id="data">(.*?)<\/script>/s.exec(html)[1]); +} + +/** A repo in a folder of its own, with one commit for each entry, a minute apart from 10:00 UTC + * on 24 Nov 2026, all by Ada Author. `files` are written, and a file whose content is null is + * deleted. `commits` are the oids, oldest first. The folder goes when the test ends. */ +function repoWith(history) { + const folder = mkdtempSync(join(tmpdir(), "git-app-")); + const git = (args, minute) => + execFileSync("git", ["-C", folder, ...args], { + env: { + PATH: process.env.PATH, + // this machine's own git settings stay out of the test (hooks, signing) + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_SYSTEM: "/dev/null", + GIT_AUTHOR_NAME: "Ada Author", + GIT_AUTHOR_EMAIL: "ada@example.com", + GIT_COMMITTER_NAME: "Ada Author", + GIT_COMMITTER_EMAIL: "ada@example.com", + GIT_AUTHOR_DATE: `2026-11-24T10:0${minute}:00Z`, + GIT_COMMITTER_DATE: `2026-11-24T10:0${minute}:00Z`, + }, + }) + .toString() + .trim(); + git(["init", "--quiet", "--initial-branch=main"], 0); + const commits = history.map(({ message, files }, minute) => { + for (const [path, content] of Object.entries(files)) { + const file = join(folder, path); + if (content === null) rmSync(file); + else { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + } + } + git(["add", "--all"], minute); + git(["commit", "--quiet", "--message", message], minute); + return git(["rev-parse", "HEAD"], minute); + }); + return { + folder, + commits, + [Symbol.dispose]: () => rmSync(folder, { recursive: true, force: true }), + }; +}
A tests/serve.mjs
@@ -0,0 +1,31 @@ +// tests/serve.mjs — THE APP'S PAGES ON THIS MACHINE, over the repos cloned beside this one, to +// try a change before a push: +// +// node tests/serve.mjs then open http://git.localhost:4173 +// VISITOR=anyone node tests/serve.mjs as someone who is no member +// +// The pages only: git itself is not served here (no clone, no push). +import { readFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { gitApp } from "../app.ts"; +import { localMind } from "./local-mind.mjs"; + +// The folder that holds every repo is itself the repo `home`. +const home = new URL("../../", import.meta.url).pathname; +const folders = { "/repos/home": home }; +for (const name of ["kernel", "stdlib", "dash", "tasks", "git", "config"]) + folders[`/repos/${name}`] = `${home}${name}`; + +const mind = localMind({ folders, member: process.env.VISITOR !== "anyone" }); +const git = gitApp({ + public: Object.keys(folders).filter((repo) => repo !== "/repos/config"), + icon: () => new Response("<svg xmlns='http://www.w3.org/2000/svg'/>", { headers: { "content-type": "image/svg+xml" } }), + theme: readFileSync(`${home}stdlib/theme.css`, "utf8"), +}); + +const port = 4173; +createServer(async (request, response) => { + const answer = await git.fetch(new Request(`http://${request.headers.host}${request.url}`), mind); + response.writeHead(answer.status, Object.fromEntries(answer.headers)); + response.end(Buffer.from(await answer.arrayBuffer())); +}).listen(port, () => console.log(`http://git.localhost:${port}`));