routes.ts

7.6 KB · raw

1import { readFileSync } from "node:fs";2import { join } from "node:path";3import type { Context, Hono } from "hono";4import type { Bucket } from "../bucket/reader.ts";5import { isPlatform, isVersion, type ReleaseFile } from "../bucket/repo.ts";6import { headId, repoStats, saveByPrefix } from "../mirror/queries.ts";7import { notFound, openPublicRepo, type PageContext, type PublicRepo } from "../pages/layout.ts";8import { repoIntro } from "../pages/repo.ts";9import { checksumsTxt, historyJson, metaJson, releaseJson, updateInfoJson } from "./feeds.ts";10import { countDownload, type Release, releaseContentType, visibleReleases } from "./releases.ts";1112/**13 * §22.4: Koh 2's `koh update` reads `/api/koh/releases/latest`, built into every Koh 2 binary. The14 * route stays on Koh 2's last release forever, never the repo's newest, so a Koh 2 install is never15 * offered Koh 3.16 */17const FROZEN_KOH2 = { repo: "koh", version: "2.1.16" } as const;1819// §22.5: one generic script; each repo gets its own name and address filled in.20const INSTALL_SH = readFileSync(join(import.meta.dir, "install.sh"), "utf8");2122const JSON_TYPE = "application/json; charset=UTF-8";23const TEXT_TYPE = "text/plain; charset=UTF-8";24// Kepr 2's error bodies. A private repo answers exactly as an unknown one (§20).25const REPO_NOT_FOUND = '{"error":"repo_not_found","message":"repo not found"}';26const NO_RELEASES = '{"error":"not_found","message":"no releases"}';27const RELEASE_NOT_FOUND = '{"error":"not_found","message":"release not found"}';2829type Feed = { repo: PublicRepo; releases: Release[] };3031export function registerReleaseRoutes(app: Hono, ctx: PageContext, bucket: Bucket): void {32	const send = (c: Context, status: 200 | 404, body: string, type = JSON_TYPE) =>33		c.body(body, status, { "Content-Type": type });34	const feed = (name: string): Feed | null => {35		const repo = openPublicRepo(ctx, name);36		return repo && { repo, releases: visibleReleases(ctx.kepr, repo.mirror, name) };37	};38	// Counted before the redirect (§22.2); Kepr never streams a release file itself.39	const download = (c: Context, repo: string, version: string, file: ReleaseFile) => {40		countDownload(ctx.kepr, repo, version, file.platform);41		const key = `${repo}/releases/${version}/${file.platform}/${file.name}`;42		c.header("Cache-Control", "no-store");43		return c.redirect(bucket.downloadUrl(key, file.name, releaseContentType(file.name)), 302);44	};45	const downloadAt = (c: Context, name: string, version: string, requested: string) => {46		const f = feed(name);47		if (!f) return send(c, 404, REPO_NOT_FOUND);48		// Kepr 2's download links end in `<repo>-<platform>`, so `curl -O` saves a telling name.49		const platform = requested.startsWith(`${name}-`)50			? requested.slice(name.length + 1)51			: requested;52		const release = f.releases.find((r) => r.version === version);53		const file =54			release?.files.find((x) => x.name === requested) ||55			(isPlatform(platform) && release?.files.find((x) => x.platform === platform));56		return file ? download(c, name, version, file) : send(c, 404, RELEASE_NOT_FOUND);57	};58	// The newest visible release, or the response that says why there is none.59	const newest = (c: Context, name: string): Release | Response => {60		const f = feed(name);61		if (!f) return send(c, 404, REPO_NOT_FOUND);62		return f.releases[0] ?? send(c, 404, NO_RELEASES);63	};6465	app.get("/api/koh/releases/latest", (c) =>66		send(c, 404, '{"error":"no_releases","message":"no releases available"}'),67	);68	app.get("/api/koh/releases/:version/:platform", (c) =>69		downloadAt(c, FROZEN_KOH2.repo, c.req.param("version"), c.req.param("platform")),70	);71	for (const [path, cors] of [72		["/api/:repo/releases/latest", true],73		["/:repo/releases/latest.json", false],74	] as const) {75		app.get(path, (c) => {76			// §22.4 puts CORS on the route, so its 404s carry it too (Kepr 2 sent it only on success).77			if (cors) c.header("Access-Control-Allow-Origin", "*");78			const release = newest(c, c.req.param("repo"));79			if (release instanceof Response) return release;80			return send(c, 200, releaseJson(ctx.domain, c.req.param("repo"), release));81		});82	}83	for (const [path, cors] of [84		["/api/:repo/releases/history", true],85		["/:repo/releases/history.json", false],86	] as const) {87		app.get(path, (c) => {88			if (cors) c.header("Access-Control-Allow-Origin", "*");89			const f = feed(c.req.param("repo"));90			if (!f) return send(c, 404, REPO_NOT_FOUND);91			if (f.releases.length === 0) return send(c, 404, NO_RELEASES);92			return send(c, 200, historyJson(f.releases));93		});94	}95	app.get("/:repo/releases/latest", (c) => {96		const repo = openPublicRepo(ctx, c.req.param("repo"));97		if (!repo) return notFound(c, ctx);98		return c.redirect(`/${repo.settings.name}/releases`, 302);99	});100	app.get("/:repo/releases/latest/version.txt", (c) => {101		const release = newest(c, c.req.param("repo"));102		return release instanceof Response ? release : send(c, 200, release.version, TEXT_TYPE);103	});104	app.get("/:repo/releases/:version/checksums.txt", (c) => {105		const name = c.req.param("repo");106		const f = feed(name);107		if (!f) return send(c, 404, REPO_NOT_FOUND);108		const release = f.releases.find((r) => r.version === c.req.param("version"));109		if (!release) return send(c, 404, RELEASE_NOT_FOUND);110		return send(c, 200, checksumsTxt(name, release), TEXT_TYPE);111	});112	// §22.1: the newest file for that platform, from the newest release that has one.113	app.get("/:repo/releases/latest/:platform", (c) => {114		const name = c.req.param("repo");115		const f = feed(name);116		if (!f) return send(c, 404, REPO_NOT_FOUND);117		const platform = c.req.param("platform");118		for (const release of f.releases) {119			const file = release.files.find((x) => x.platform === platform);120			if (file) return download(c, name, release.version, file);121		}122		return send(c, 404, RELEASE_NOT_FOUND);123	});124	app.get("/:repo/releases/:version/:platform", (c) => {125		const version = c.req.param("version");126		if (!isVersion(version)) return send(c, 404, RELEASE_NOT_FOUND);127		return downloadAt(c, c.req.param("repo"), version, c.req.param("platform"));128	});129	// Only for a repo with a release, since the script would have nothing to install.130	app.get("/:repo/install.sh", (c) => {131		const name = c.req.param("repo");132		const release = newest(c, name);133		if (release instanceof Response) return release;134		const script = INSTALL_SH.replaceAll("@REPO@", name).replaceAll(135			"@BASE@",136			`https://${ctx.domain}/${name}`,137		);138		c.header("Cache-Control", "public, max-age=60");139		return send(c, 200, script, TEXT_TYPE);140	});141	app.get("/:repo/update-info", (c) => {142		const name = c.req.param("repo");143		const f = feed(name);144		if (!f) return send(c, 404, REPO_NOT_FOUND);145		// §22.4: head is the newest save on the line, a checkpoint included. Its version is the146		// release built from it, else its ID, as in Kepr 2.147		const id = headId(f.repo.mirror);148		const save = id ? saveByPrefix(f.repo.mirror, id) : null;149		const saveHead = save && {150			id: save.id,151			version: f.releases.find((r) => r.save === save.id)?.version ?? save.id,152			createdAt: save.created_at,153		};154		return send(c, 200, updateInfoJson(ctx.domain, name, saveHead ?? null, f.releases[0]));155	});156	app.get("/:repo/meta", (c) => {157		const f = feed(c.req.param("repo"));158		if (!f) return send(c, 404, REPO_NOT_FOUND);159		const { name, category } = f.repo.settings;160		const stats = repoStats(f.repo.mirror);161		const meta = {162			repo: name,163			saveCount: stats.saves,164			lineCount: stats.lines,165			lastSaveAt: stats.updated ?? 0,166			latestRelease: f.releases[0]?.version ?? null,167			description: repoIntro(f.repo)?.text ?? null,168			language: stats.language || null,169			category: category || null,170		};171		return send(c, 200, metaJson(meta));172	});173}