files.ts

5.3 KB · raw

1import type { Context, Hono } from "hono";2import { isSafePath } from "../bucket/repo.ts";3import { type FileEntry, fileAt, headId, objectBytes, saveByPrefix } from "../mirror/queries.ts";4import { highlightLines } from "./highlight.ts";5import { type Html, html } from "./html.ts";6import {7	cacheFor,8	formatSize,9	notFound,10	openPublicRepo,11	type PageContext,12	page,13	pathUrl,14} from "./layout.ts";15import { renderMarkdown } from "./markdown.ts";1617const SHOWN_BYTES = 1024 * 1024;18const IMAGE = /\.(png|jpe?g|gif|webp|avif|ico|svg)$/i;19const MARKDOWN = /\.(md|markdown)$/i;20// Binary types a browser can show or save as they are; anything else textual stays text/plain (§21.8).21const PASS_THROUGH = /^(image|audio|video|font)\/|^application\/(pdf|zip|gzip|wasm)$/;2223type Found = {24	repo: string;25	path: string;26	at: string | null;27	file: FileEntry;28	bytes: Uint8Array<ArrayBuffer>;29};3031export function registerFileRoutes(app: Hono, ctx: PageContext): void {32	app.get("/:repo/files/:path{.+}", async (c) => {33		const found = findFile(c, ctx);34		if (!found) return notFound(c, ctx);35		cacheFor(c, found.at !== null);36		const title = found.path.split("/").pop() as string;37		const body = html`${breadcrumb(found)}38<h1 class="file-page-title">${title}</h1>39${await fileBody(found, c.req.query("view") === "source")}`;40		return c.html(41			page(ctx, {42				title: `${title} · ${found.repo}`,43				description: found.path,44				path: c.req.path,45				body,46			}),47		);48	});4950	app.get("/:repo/raw/:path{.+}", (c) => {51		const found = findFile(c, ctx);52		if (!found) return notFound(c, ctx);53		cacheFor(c, found.at !== null);54		c.header("Content-Type", contentType(found.path, found.bytes));55		return c.body(found.bytes);56	});57}5859/** The file named by the route at `?at=<id>` or HEAD, behind the visibility gate; null means 404. */60function findFile(c: Context, ctx: PageContext): Found | null {61	const name = c.req.param("repo") as string;62	const path = c.req.param("path") as string;63	const repo = openPublicRepo(ctx, name);64	if (!repo || !isSafePath(path)) return null;65	const at = c.req.query("at") ?? null;66	const saveId = at === null ? headId(repo.mirror) : (saveByPrefix(repo.mirror, at)?.id ?? null);67	const file = saveId ? fileAt(repo.mirror, saveId, path) : null;68	const bytes = file && objectBytes(repo.mirror, file.hash);69	return file && bytes ? { repo: name, path, at: at && saveId, file, bytes } : null;70}7172function isText(bytes: Uint8Array): boolean {73	if (bytes.subarray(0, 8000).includes(0)) return false;74	try {75		// Streaming mode tolerates only a character cut at the 1 MB mark; invalid bytes still throw.76		const cut = bytes.length > SHOWN_BYTES;77		new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, SHOWN_BYTES), {78			stream: cut,79		});80		return true;81	} catch {82		return false;83	}84}8586function contentType(path: string, bytes: Uint8Array): string {87	const type = Bun.file(path).type;88	if (type.startsWith("image/")) return type;89	if (isText(bytes)) return "text/plain; charset=utf-8";90	return PASS_THROUGH.test(type) ? type : "application/octet-stream";91}9293function rawHref(found: Found): string {94	return `/${found.repo}/raw/${pathUrl(found.path)}${found.at ? `?at=${found.at}` : ""}`;95}9697function breadcrumb(found: Found): Html {98	const dirs = found.path.split("/").slice(0, -1);99	return html`<p class="breadcrumb mono"><a href="/${found.repo}">${found.repo}</a>${dirs.map((dir) => ` / ${dir}`)}${found.at && html` @ <a href="/${found.repo}/saves/${found.at}">${found.at}</a>`}</p>`;100}101102async function fileBody(found: Found, source: boolean): Promise<Html> {103	const size = formatSize(found.file.size);104	const raw = rawHref(found);105	if (IMAGE.test(found.path)) {106		return html`<p class="file-meta mono">${size} · <a href="${raw}">raw</a></p><div class="file-image"><img src="${raw}" alt="${found.path}"></div>`;107	}108	if (!isText(found.bytes)) {109		return html`<p class="file-meta mono">binary file · ${size} · <a href="${raw}" download>download</a></p>`;110	}111	const truncated = found.bytes.length > SHOWN_BYTES;112	const text = new TextDecoder().decode(found.bytes.subarray(0, SHOWN_BYTES));113	const meta = html`<p class="file-meta mono">${size}${truncated && " · showing the first 1 MB"} · <a href="${raw}">raw</a></p>`;114	if (MARKDOWN.test(found.path)) {115		const at = found.at ? `at=${found.at}&` : "";116		const toggle = html`<p class="file-toggle mono"><a href="?${found.at ? `at=${found.at}` : ""}"${!source && html` class="active"`}>rendered</a> · <a href="?${at}view=source"${source && html` class="active"`}>source</a></p>`;117		if (!source) {118			const dir = found.path.split("/").slice(0, -1).join("/");119			const rendered = renderMarkdown(text, { repo: found.repo, dir, at: found.at });120			return html`${meta}${toggle}<div class="markdown file-markdown">${rendered}</div>`;121		}122		return html`${meta}${toggle}${await codeView(text, found.path)}`;123	}124	return html`${meta}${await codeView(text, found.path)}`;125}126127// Each line is its own anchor target, so `#L42` scrolls and highlights through CSS alone; the128// script only adds ranges (`#L42-L50`).129async function codeView(text: string, path: string): Promise<Html> {130	const lines = await highlightLines(text, path);131	return html`<div class="file-view"><pre class="code"><code>${lines.map(132		(line, i) =>133			html`<span class="line" id="L${i + 1}"><a class="ln" href="#L${i + 1}">${i + 1}</a><span class="lc">${line}</span></span>`,134	)}</code></pre></div>`;135}