files.ts

7.4 KB · raw

1import type { Context, Hono } from "hono";2import { isSafePath } from "../bucket/repo.ts";3import { isText, SHOWN_BYTES } from "../describe/describe.ts";4import { type FileEntry, fileAt, headId, objectBytes, saveByPrefix } from "../mirror/queries.ts";5import { highlightLines } from "./highlight.ts";6import { type Html, html } from "./html.ts";7import {8	cacheFor,9	formatSize,10	notFound,11	openPublicRepo,12	type PageContext,13	page,14	pathUrl,15} from "./layout.ts";16import { registerHeavyLimit } from "./limit.ts";17import { renderMarkdown } from "./markdown.ts";1819const IMAGE = /\.(png|jpe?g|gif|webp|avif|ico|svg)$/i;20const MARKDOWN = /\.(md|markdown)$/i;21// Binary types a browser can show or save as they are; anything else textual stays22// text/plain (§21.8).23const PASS_THROUGH = /^(image|audio|video|font)\/|^application\/(pdf|zip|gzip|wasm)$/;2425type Found = {26	repo: string;27	path: string;28	at: string | null;29	file: FileEntry;30	bytes: Uint8Array<ArrayBuffer>;31};3233export function registerFileRoutes(app: Hono, ctx: PageContext): void {34	// Ahead of this group's routes, and so of every route registered after it: bundle, archive,35	// saves, files and raw share one per-address budget.36	registerHeavyLimit(app);37	app.get("/:repo/files/:path{.+}", async (c) => {38		const found = findFile(c, ctx);39		if (!found) return notFound(c, ctx);40		cacheFor(c, found.at !== null);41		const title = found.path.split("/").pop() as string;42		const body = html`${breadcrumb(found)}43<h1 class="file-page-title">${title}</h1>44${await fileBody(found, c.req.query("view") === "source")}`;45		return c.html(46			page(ctx, {47				title: `${title} · ${found.repo}`,48				description: found.path,49				path: c.req.path,50				body,51			}),52		);53	});5455	app.get("/:repo/raw/:path{.+}", (c) => {56		const found = findFile(c, ctx);57		if (!found) return notFound(c, ctx);58		cacheFor(c, found.at !== null);59		const bytes = found.bytes;60		c.header("Content-Type", contentType(found.path, bytes));61		c.header("Accept-Ranges", "bytes");62		// One range, as a download manager asks for; anything else, a HEAD or several ranges63		// included, is the whole file.64		const [, from = "", to = ""] = /^bytes=(\d*)-(\d*)$/.exec(c.req.header("Range") ?? "") ?? [];65		if (from === "" && to === "") return c.body(bytes);66		const start = from === "" ? Math.max(0, bytes.length - Number(to)) : Number(from);67		const end =68			from === "" || to === "" ? bytes.length - 1 : Math.min(Number(to), bytes.length - 1);69		if (start > end) return c.body(null, 416, { "Content-Range": `bytes */${bytes.length}` });70		return c.body(bytes.slice(start, end + 1), 206, {71			"Content-Range": `bytes ${start}-${end}/${bytes.length}`,72		});73	});74}7576/** The file named by the route at `?at=<id>` or HEAD, behind the visibility gate; null means 404. */77function findFile(c: Context, ctx: PageContext): Found | null {78	const name = c.req.param("repo") as string;79	const path = c.req.param("path") as string;80	const repo = openPublicRepo(ctx, name);81	if (!repo || !isSafePath(path)) return null;82	const at = c.req.query("at") ?? null;83	const saveId = at === null ? headId(repo.mirror) : (saveByPrefix(repo.mirror, at)?.id ?? null);84	const file = saveId ? fileAt(repo.mirror, saveId, path) : null;85	const bytes = file && objectBytes(repo.mirror, file.hash);86	return file && bytes ? { repo: name, path, at: at && saveId, file, bytes } : null;87}8889function contentType(path: string, bytes: Uint8Array): string {90	const type = Bun.file(path).type;91	if (type.startsWith("image/")) return type;92	if (isText(bytes)) return "text/plain; charset=utf-8";93	return PASS_THROUGH.test(type) ? type : "application/octet-stream";94}9596function rawHref(found: Found): string {97	return `/${found.repo}/raw/${pathUrl(found.path)}${found.at ? `?at=${found.at}` : ""}`;98}99100// Each folder opens the repo's Atlas with that folder unfolded (kepr.js reads `open`).101function breadcrumb(found: Found): Html {102	const dirs = found.path.split("/").slice(0, -1);103	const folderHref = (depth: number) => {104		const query = new URLSearchParams(found.at ? { at: found.at } : {});105		query.set("open", dirs.slice(0, depth + 1).join("/"));106		return `/${found.repo}?${query}#atlas`;107	};108	return html`<p class="breadcrumb mono"><a href="/${found.repo}">${found.repo}</a>${dirs.map(109		(dir, depth) => html` / <a href="${folderHref(depth)}">${dir}</a>`,110	)}${found.at && html` @ <a href="/${found.repo}/saves/${found.at}">${found.at}</a>`}</p>`;111}112113async function fileBody(found: Found, source: boolean): Promise<Html> {114	const size = formatSize(found.file.size);115	const raw = rawHref(found);116	if (IMAGE.test(found.path)) {117		return html`<p class="file-meta mono">${118			size119		} · <a href="${raw}">raw</a></p><div class="file-image"><img src="${raw}" alt="${found.path}"></div>`;120	}121	if (!isText(found.bytes)) {122		return html`<p class="file-meta mono">binary file · ${123			size124		} · <a href="${raw}" download>download</a></p>`;125	}126	const truncated = found.bytes.length > SHOWN_BYTES;127	const text = new TextDecoder().decode(found.bytes.subarray(0, SHOWN_BYTES));128	const meta = html`<p class="file-meta mono">${129		size130	}${truncated && " · showing the first 1 MB"} · <a href="${raw}">raw</a></p>`;131	if (MARKDOWN.test(found.path)) {132		const at = found.at ? `at=${found.at}&` : "";133		const toggle = html`<p class="file-toggle mono"><a href="?${134			found.at ? `at=${found.at}` : ""135		}"${!source && html` class="active"`}>rendered</a> · <a href="?${at}view=source"${source && html` class="active"`}>source</a></p>`;136		if (!source) {137			const dir = found.path.split("/").slice(0, -1).join("/");138			const rendered = renderMarkdown(text, { repo: found.repo, dir, at: found.at });139			return html`${meta}${toggle}<div class="markdown file-markdown">${rendered}</div>`;140		}141		return html`${meta}${toggle}${await codeView(text, found)}`;142	}143	return html`${meta}${await codeView(text, found)}`;144}145146// Each line is its own anchor target, so `#L42` scrolls and highlights through CSS alone; the147// script only adds ranges (`#L42-L50`).148async function codeView(text: string, found: Found): Promise<Html> {149	const lines = await highlightedLines(text, found);150	return html`<div class="file-view"><pre class="code"><code>${lines.map(151		(line, i) =>152			html`<span class="line" id="L${153				i + 1154			}"><a class="ln" href="#L${i + 1}">${i + 1}</a><span class="lc">${line}</span></span>`,155	)}</code></pre></div>`;156}157158const CACHE_ENTRIES = 100;159const CACHE_BYTES = 64 * 1024 * 1024;160const highlighted = new Map<string, { lines: Html[]; bytes: number }>();161let highlightedBytes = 0;162163/** `highlightLines`, remembered by the object's hash: a second view of a 1 MB file skips Shiki. */164async function highlightedLines(text: string, found: Found): Promise<Html[]> {165	// The extension names the language and the hash the bytes, so both together name one view.166	const key = `${found.file.hash}:${found.path.toLowerCase().split(".").pop()}`;167	const hit = highlighted.get(key);168	if (hit) {169		// A hit moves to the end, so the first entry is always the one used longest ago.170		highlighted.delete(key);171		highlighted.set(key, hit);172		return hit.lines;173	}174	const lines = await highlightLines(text, found.path);175	const bytes = lines.reduce((sum, line) => sum + line.value.length, 0);176	if (bytes > CACHE_BYTES) return lines;177	highlighted.set(key, { lines, bytes });178	highlightedBytes += bytes;179	for (const [old, entry] of highlighted) {180		if (highlighted.size <= CACHE_ENTRIES && highlightedBytes <= CACHE_BYTES) break;181		highlighted.delete(old);182		highlightedBytes -= entry.bytes;183	}184	return lines;185}