repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/diff-review/bundle.ts

Raw
File outline
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);
const EXT_DIR = dirname(fileURLToPath(import.meta.url));
const STATIC_DIR = join(EXT_DIR, "static");
const BROWSER_DIR = join(EXT_DIR, "browser");

export function extensionDir() {
	return EXT_DIR;
}
export function staticDir() {
	return STATIC_DIR;
}

export async function ensureBrowserBundle(
	onStatus?: (message: string) => void,
): Promise<void> {
	onStatus?.("checking browser bundle");
	const problem = await bundleProblem();
	if (!problem) {
		onStatus?.("browser bundle ready");
		return;
	}
	onStatus?.(`${problem}; building browser bundle`);
	try {
		await execFileAsync("bun", ["run", "build"], {
			cwd: EXT_DIR,
			maxBuffer: 1024 * 1024 * 5,
		});
	} catch (err) {
		const anyErr = err as { stderr?: string | Buffer; message?: string };
		const stderr = anyErr.stderr ? String(anyErr.stderr).trim() : "";
		throw new Error(
			`${problem}. Build failed. Run: cd ${EXT_DIR} && bun install && bun run build${stderr ? `\n${stderr}` : ""}`,
		);
	}
	onStatus?.("verifying browser bundle");
	const after = await bundleProblem();
	if (after)
		throw new Error(
			`${after}. Run: cd ${EXT_DIR} && bun install && bun run build`,
		);
	onStatus?.("browser bundle ready");
}

async function bundleProblem(): Promise<string | undefined> {
	const index = join(STATIC_DIR, "index.html");
	const app = join(STATIC_DIR, "app.js");
	const manifestPath = join(STATIC_DIR, "manifest.json");
	if (!existsSync(index) || !existsSync(app) || !existsSync(manifestPath))
		return "Browser bundle missing";
	try {
		const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
			sources?: Record<string, { sha256: string }>;
		};
		const current = await sourceManifest();
		for (const [path, entry] of Object.entries(current)) {
			const existing = manifest.sources?.[path];
			if (!existing || existing.sha256 !== entry.sha256)
				return "Browser bundle stale";
		}
		return undefined;
	} catch {
		return "Browser bundle manifest invalid";
	}
}

export async function sourceManifest() {
	const files = await listFiles(BROWSER_DIR);
	const sources: Record<string, { sha256: string }> = {};
	for (const file of files) {
		const data = await readFile(file);
		const rel = relative(EXT_DIR, file);
		sources[rel] = { sha256: createHash("sha256").update(data).digest("hex") };
	}
	return sources;
}

async function listFiles(dir: string): Promise<string[]> {
	const out: string[] = [];
	for (const entry of await readdir(dir, { withFileTypes: true })) {
		const full = join(dir, entry.name);
		if (entry.isDirectory()) out.push(...(await listFiles(full)));
		else out.push(full);
	}
	return out.sort();
}