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	browserPage,9	cacheFor,10	formatSize,11	notFound,12	openBrowserRepo,13	type PageContext,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 browserPage(c, ctx, {46			title: `${title} · ${found.repo}`,47			description: found.path,48			path: c.req.path,49			body,50		});51	});5253	app.get("/:repo/raw/:path{.+}", (c) => {54		const found = findFile(c, ctx);55		if (!found) return notFound(c, ctx);56		cacheFor(c, found.at !== null);57		const bytes = found.bytes;58		c.header("Content-Type", contentType(found.path, bytes));59		c.header("Accept-Ranges", "bytes");60		// One range, as a download manager asks for; anything else, a HEAD or several ranges61		// included, is the whole file.62		const [, from = "", to = ""] = /^bytes=(\d*)-(\d*)$/.exec(c.req.header("Range") ?? "") ?? [];63		if (from === "" && to === "") return c.body(bytes);64		const start = from === "" ? Math.max(0, bytes.length - Number(to)) : Number(from);65		const end =66			from === "" || to === "" ? bytes.length - 1 : Math.min(Number(to), bytes.length - 1);67		if (start > end) return c.body(null, 416, { "Content-Range": `bytes */${bytes.length}` });68		return c.body(bytes.slice(start, end + 1), 206, {69			"Content-Range": `bytes ${start}-${end}/${bytes.length}`,70		});71	});72}7374/** The file named by the route at `?at=<id>` or HEAD, behind the visibility gate; null means 404. */75function findFile(c: Context, ctx: PageContext): Found | null {76	const name = c.req.param("repo") as string;77	const path = c.req.param("path") as string;78	const repo = openBrowserRepo(ctx, c, name);79	if (!repo || !isSafePath(path)) return null;80	const at = c.req.query("at") ?? null;81	const saveId = at === null ? headId(repo.mirror) : (saveByPrefix(repo.mirror, at)?.id ?? null);82	const file = saveId ? fileAt(repo.mirror, saveId, path) : null;83	const bytes = file && objectBytes(repo.mirror, file.hash);84	return file && bytes ? { repo: name, path, at: at && saveId, file, bytes } : null;85}8687function contentType(path: string, bytes: Uint8Array): string {88	const type = Bun.file(path).type;89	if (type.startsWith("image/")) return type;90	if (isText(bytes)) return "text/plain; charset=utf-8";91	return PASS_THROUGH.test(type) ? type : "application/octet-stream";92}9394function rawHref(found: Found): string {95	return `/${found.repo}/raw/${pathUrl(found.path)}${found.at ? `?at=${found.at}` : ""}`;96}9798// Each folder opens the repo's Atlas with that folder unfolded (kepr.js reads `open`).99function breadcrumb(found: Found): Html {100	const dirs = found.path.split("/").slice(0, -1);101	const folderHref = (depth: number) => {102		const query = new URLSearchParams(found.at ? { at: found.at } : {});103		query.set("open", dirs.slice(0, depth + 1).join("/"));104		return `/${found.repo}?${query}#atlas`;105	};106	return html`<p class="breadcrumb mono"><a href="/${found.repo}">${found.repo}</a>${dirs.map(107		(dir, depth) => html` / <a href="${folderHref(depth)}">${dir}</a>`,108	)}${found.at && html` @ <a href="/${found.repo}/saves/${found.at}">${found.at}</a>`}</p>`;109}110111async function fileBody(found: Found, source: boolean): Promise<Html> {112	const size = formatSize(found.file.size);113	const raw = rawHref(found);114	if (IMAGE.test(found.path)) {115		return html`<p class="file-meta mono">${116			size117		} · <a href="${raw}">raw</a></p><div class="file-image"><img src="${raw}" alt="${found.path}"></div>`;118	}119	if (!isText(found.bytes)) {120		return html`<p class="file-meta mono">binary file · ${121			size122		} · <a href="${raw}" download>download</a></p>`;123	}124	const truncated = found.bytes.length > SHOWN_BYTES;125	const text = new TextDecoder().decode(found.bytes.subarray(0, SHOWN_BYTES));126	const meta = html`<p class="file-meta mono">${127		size128	}${truncated && " · showing the first 1 MB"} · <a href="${raw}">raw</a></p>`;129	if (MARKDOWN.test(found.path)) {130		const at = found.at ? `at=${found.at}&` : "";131		const toggle = html`<p class="file-toggle mono"><a href="?${132			found.at ? `at=${found.at}` : ""133		}"${!source && html` class="active"`}>rendered</a> · <a href="?${at}view=source"${source && html` class="active"`}>source</a></p>`;134		if (!source) {135			const dir = found.path.split("/").slice(0, -1).join("/");136			const rendered = renderMarkdown(text, { repo: found.repo, dir, at: found.at });137			return html`${meta}${toggle}<div class="markdown file-markdown">${rendered}</div>`;138		}139		return html`${meta}${toggle}${await codeView(text, found)}`;140	}141	return html`${meta}${await codeView(text, found)}`;142}143144// Each line is its own anchor target, so `#L42` scrolls and highlights through CSS alone; the145// script only adds ranges (`#L42-L50`).146async function codeView(text: string, found: Found): Promise<Html> {147	const lines = await highlightedLines(text, found);148	return html`<div class="file-view"><pre class="code"><code>${lines.map(149		(line, i) =>150			html`<span class="line" id="L${151				i + 1152			}"><a class="ln" href="#L${i + 1}">${i + 1}</a><span class="lc">${line}</span></span>`,153	)}</code></pre></div>`;154}155156const CACHE_ENTRIES = 100;157const CACHE_BYTES = 64 * 1024 * 1024;158const highlighted = new Map<string, { lines: Html[]; bytes: number }>();159let highlightedBytes = 0;160161/** `highlightLines`, remembered by the object's hash: a second view of a 1 MB file skips Shiki. */162async function highlightedLines(text: string, found: Found): Promise<Html[]> {163	// The extension names the language and the hash the bytes, so both together name one view.164	const key = `${found.file.hash}:${found.path.toLowerCase().split(".").pop()}`;165	const hit = highlighted.get(key);166	if (hit) {167		// A hit moves to the end, so the first entry is always the one used longest ago.168		highlighted.delete(key);169		highlighted.set(key, hit);170		return hit.lines;171	}172	const lines = await highlightLines(text, found.path);173	const bytes = lines.reduce((sum, line) => sum + line.value.length, 0);174	if (bytes > CACHE_BYTES) return lines;175	highlighted.set(key, { lines, bytes });176	highlightedBytes += bytes;177	for (const [old, entry] of highlighted) {178		if (highlighted.size <= CACHE_ENTRIES && highlightedBytes <= CACHE_BYTES) break;179		highlighted.delete(old);180		highlightedBytes -= entry.bytes;181	}182	return lines;183}