repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

scripts/demo.mjs

Raw
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import {
	copyFileSync,
	existsSync,
	mkdirSync,
	readdirSync,
	readFileSync,
	writeFileSync,
} from "node:fs";
import { dirname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { commandExists, git, ROOT, rel, run } from "./lib/common.mjs";

const DRIVERS = join(ROOT, "drivers");
const EXTENSIONS = join(ROOT, "extensions");
const OUT = join(ROOT, ".demo");
const CAST_IDLE_LIMIT = "4.0";
const AGG_ARGS = [
	"--theme",
	"asciinema",
	"--text-font-family",
	"JetBrains Mono",
	"--font-size",
	"14",
	"--line-height",
	"1.25",
	"--idle-time-limit",
	"4.0",
	"--last-frame-duration",
	"5",
	"--fps-cap",
	"24",
];

async function loadDriver(name) {
	const path = join(DRIVERS, `${name}.mjs`);
	if (!existsSync(path)) throw new Error(`driver not found: ${path}`);
	const m = await import(`${pathToFileURL(path).href}?v=${Date.now()}`);
	const driver = {
		name,
		title: m.title ?? name.replaceAll("_", " "),
		extensions: m.extensions,
		targets: m.targets,
		cols: m.cols ?? 100,
		rows: m.rows ?? 28,
		cwd: resolve(ROOT, m.cwd ?? "."),
		steps: m.steps,
		readme_id: m.readme_id ?? name,
		readme_items: m.readme_items,
		browser_script: m.browser_script,
		env: m.env ?? {},
	};
	return driver;
}

function validateDriver(d) {
	for (const key of ["extensions", "targets", "steps"])
		if (!Array.isArray(d[key]))
			throw new Error(`${d.name}: ${key} must be array`);
	if (
		!Number.isInteger(d.cols) ||
		!Number.isInteger(d.rows) ||
		d.cols < 40 ||
		d.rows < 12
	)
		throw new Error(`${d.name}: bad cols/rows`);
	if (!existsSync(d.cwd)) throw new Error(`${d.name}: cwd missing ${d.cwd}`);
	for (const name of d.extensions)
		if (!existsSync(join(EXTENSIONS, name, "index.ts")))
			throw new Error(`${d.name}: missing extension ${name}`);
	for (const name of d.targets)
		if (!existsSync(join(EXTENSIONS, name, "README.md")))
			throw new Error(`${d.name}: missing target ${name}`);
}

function shellQuote(s) {
	return `'${String(s).replaceAll("'", `'\\''`)}'`;
}
function piCommand(d) {
	const parts = [
		"pi",
		"--no-session",
		"--no-context-files",
		"--no-skills",
		"--no-prompt-templates",
		"--no-extensions",
	];
	for (const name of d.extensions) parts.push("-e", join(EXTENSIONS, name));
	return parts.map(shellQuote).join(" ");
}
function expectQuote(s) {
	return `{${String(s).replaceAll("}", "\\}")}}`;
}
function expectScript(d) {
	const lines = [
		`set timeout 90`,
		`cd ${expectQuote(d.cwd)}`,
		...Object.entries(d.env).map(([k, v]) => `set env(${k}) ${expectQuote(v)}`),
		`spawn -noecho -nottycopy -nottyinit -winsize ${d.rows} ${d.cols} sh -lc ${expectQuote(piCommand(d))}`,
	];
	for (const step of d.steps) {
		const [op, a, b, c] = step;
		if (op === "wait") lines.push(`after ${a}`);
		else if (op === "type" || op === "send")
			lines.push(`send -- ${expectQuote(a)}`, `after ${b ?? 500}`);
		else if (op === "command" || op === "prompt")
			lines.push(
				`send -- ${expectQuote(a)}`,
				`after ${op === "prompt" ? 450 : 350}`,
				`send -- "\\r"`,
				`after ${b ?? (op === "prompt" ? 12000 : 1000)}`,
			);
		else if (op === "expect")
			lines.push(
				`expect -timeout ${Math.ceil((b ?? 30000) / 1000)} -re ${expectQuote(a)}`,
				`after ${c ?? 300}`,
			);
		else if (op === "ready")
			lines.push(
				`expect -timeout ${Math.ceil((a ?? 30000) / 1000)} -re {(›|❯|> )}`,
				`after 300`,
			);
		else if (op === "ctrl") lines.push(`send \\003`, `after 500`);
		else if (op === "quit") break;
	}
	lines.push(`send \\003`, `after 500`, `catch {close}`, `wait`);
	return `${lines.join("\n")}\n`;
}

function ensureTools() {
	const missing = ["asciinema", "agg", "expect"].filter(
		(tool) => !commandExists(tool),
	);
	if (missing.length) throw new Error(`missing tool(s): ${missing.join(", ")}`);
}
function drive(d) {
	validateDriver(d);
	if (!commandExists("expect")) throw new Error("missing tool: expect");
	const script = expectScript(d);
	const r = spawnSync("expect", ["-c", script], {
		cwd: ROOT,
		stdio: "inherit",
		encoding: "utf8",
	});
	return r.status ?? 1;
}
function record(d, gifOut) {
	validateDriver(d);
	mkdirSync(OUT, { recursive: true });
	const cast = join(OUT, `${d.name}.cast`),
		gif = gifOut ?? join(OUT, `${d.name}.gif`),
		txt = join(OUT, `${d.name}.txt`);
	mkdirSync(dirname(gif), { recursive: true });
	if (d.browser_script) {
		if (!existsSync(join(ROOT, d.browser_script)))
			throw new Error(`${d.name}: browser_script missing`);
		run("bun", [join(ROOT, d.browser_script), "--out", gif], { cwd: ROOT });
		writeFileSync(cast, "browser demo: no asciinema cast\n");
		writeFileSync(txt, "browser demo\n");
		return [cast, gif, txt];
	}
	ensureTools();
	run(
		"asciinema",
		[
			"rec",
			"--headless",
			"--overwrite",
			"--capture-input",
			"--window-size",
			`${d.cols}x${d.rows}`,
			"-i",
			CAST_IDLE_LIMIT,
			"-c",
			`node ${shellQuote(join(ROOT, "scripts/demo.mjs"))} --drive ${shellQuote(d.name)}`,
			cast,
		],
		{ cwd: ROOT },
	);
	run(
		"agg",
		[
			"--cols",
			String(d.cols),
			"--rows",
			String(d.rows),
			...AGG_ARGS,
			cast,
			gif,
		],
		{ cwd: ROOT },
	);
	run("asciinema", ["convert", "-f", "txt", cast, txt, "--overwrite"], {
		cwd: ROOT,
		capture: true,
	});
	return [cast, gif, txt];
}
function row(cells, widths) {
	return `| ${cells.map((c, i) => c.padEnd(widths[i])).join(" | ")} |`;
}
function readmeBlock(d) {
	if (d.readme_items) {
		const headers = d.readme_items.map(([caption]) => `**${caption}**`),
			images = d.readme_items.map(
				([caption, gif]) => `![${caption}](assets/${gif})`,
			),
			widths = headers.map((h, i) => Math.max(h.length, images[i].length, 3));
		return `<!-- demo:${d.readme_id}:start -->\n\n${row(headers, widths)}\n${row(
			widths.map((w) => "-".repeat(w)),
			widths,
		)}\n${row(images, widths)}\n\n<!-- demo:${d.readme_id}:end -->`;
	}
	return `<!-- demo:${d.readme_id}:start -->\n![${d.title}](assets/${d.name}.gif)\n<!-- demo:${d.readme_id}:end -->`;
}
function stripDemoBlocks(text) {
	return (
		text
			.replace(
				/\n*## Demo\n\n<!-- demo:[^:\n]+:start -->[\s\S]*?<!-- demo:[^:\n]+:end -->\n*/g,
				"\n\n",
			)
			.replace(
				/\n*<!-- demo:[^:\n]+:start -->[\s\S]*?<!-- demo:[^:\n]+:end -->\n*/g,
				"\n\n",
			)
			.replace(/\n*## Demo\n\nNone\.\n*/g, "\n\n")
			.replace(/\n{3,}/g, "\n\n")
			.trim() + "\n"
	);
}
function updateReadme(path, d) {
	const text = stripDemoBlocks(readFileSync(path, "utf8"));
	const lines = text.split(/\r?\n/);
	const idx = lines.findIndex((l) => l.startsWith("# "));
	if (idx === -1) throw new Error(`README missing H1 title: ${path}`);
	writeFileSync(
		path,
		`${lines
			.slice(0, idx + 1)
			.join("\n")
			.trim()}\n\n${readmeBlock(d)}\n\n${lines
			.slice(idx + 1)
			.join("\n")
			.trimStart()}`.trimEnd() + "\n",
	);
}
function installAssets(d, gif) {
	for (const name of d.targets) {
		const assets = join(EXTENSIONS, name, "assets");
		mkdirSync(assets, { recursive: true });
		copyFileSync(gif, join(assets, `${d.name}.gif`));
		updateReadme(join(EXTENSIONS, name, "README.md"), d);
		console.log(`OK asset ${name}/assets/${d.name}.gif`);
	}
}
function driverNames() {
	return readdirSync(DRIVERS)
		.filter((n) => n.endsWith(".mjs") && !n.startsWith("__"))
		.map((n) => n.replace(/\.mjs$/, ""))
		.sort();
}
function latestReleaseTag() {
	const r = git(["tag", "--list", "v*", "--sort=-creatordate"], {
		capture: true,
	});
	return r.stdout.split(/\r?\n/).filter(Boolean)[0];
}
function changedSinceRelease(path, tag) {
	if (
		git(["status", "--porcelain", "--", rel(path)], {
			capture: true,
		}).stdout.trim()
	)
		return true;
	return (
		!tag ||
		git(["diff", "--quiet", tag, "--", rel(path)], { check: false }).status !==
			0
	);
}
function driverWatchPaths(d) {
	return [
		join(DRIVERS, `${d.name}.mjs`),
		...[...new Set([...d.targets, ...d.extensions])]
			.sort()
			.map((n) => join(EXTENSIONS, n)),
	];
}
async function changedDriverNames(names) {
	const tag = latestReleaseTag(),
		out = [];
	for (const name of names) {
		const d = await loadDriver(name);
		if (driverWatchPaths(d).some((p) => changedSinceRelease(p, tag)))
			out.push(name);
		else console.log(`OK demo ${name} skipped (unchanged since ${tag})`);
	}
	return out;
}
async function printDrivers() {
	for (const name of driverNames()) {
		const d = await loadDriver(name);
		console.log(
			`${name}\ttargets=${d.targets.join(",")}\textensions=${d.extensions.join(",")}`,
		);
	}
}
async function runDemo(name, noInstall, gifOut) {
	const d = await loadDriver(name);
	const [cast, gif, txt] = record(d, gifOut);
	console.log(`OK cast ${cast}`);
	console.log(`OK gif  ${gif}`);
	console.log(`OK txt  ${txt}`);
	if (!noInstall) installAssets(d, gif);
	return d.targets.map((t) => join(EXTENSIONS, t));
}
async function selectedNames(items, all, changed) {
	if (items[0] === "all") return [driverNames(), false];
	if (items[0] === "changed")
		return [
			await changedDriverNames(
				items.slice(1).length ? items.slice(1) : driverNames(),
			),
			true,
		];
	if (all) return [driverNames(), false];
	if (changed)
		return [
			await changedDriverNames(items.length ? items : driverNames()),
			true,
		];
	return [items, false];
}
async function main(argv = process.argv.slice(2)) {
	const flags = new Set(argv.filter((a) => a.startsWith("--")));
	const value = (flag) => {
		const i = argv.indexOf(flag);
		return i === -1 ? undefined : argv[i + 1];
	};
	if (value("--drive")) return drive(await loadDriver(value("--drive")));
	const items = argv.filter(
		(a, i) =>
			!a.startsWith("--") &&
			argv[i - 1] !== "--drive" &&
			argv[i - 1] !== "--out",
	);
	if (flags.has("--list") || ["list", "ls"].includes(items[0])) {
		await printDrivers();
		return 0;
	}
	const [names, wasChanged] = await selectedNames(
		items,
		flags.has("--all"),
		flags.has("--changed"),
	);
	if (!names.length) {
		if (wasChanged) console.log("OK demo none");
		else await printDrivers();
		return 0;
	}
	if (value("--out") && names.length !== 1)
		throw new Error("--out requires exactly one driver");
	for (const name of names) {
		await runDemo(name, flags.has("--no-install"), value("--out"));
		console.log(`OK demo ${name}`);
	}
	return 0;
}
if (import.meta.url === `file://${process.argv[1]}`)
	main()
		.then((code) => process.exit(code))
		.catch((e) => {
			console.error(e.message);
			process.exit(1);
		});