Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

scripts/e2e.ts

Raw
import { execFileSync, spawn } from "node:child_process";
import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { delimiter, isAbsolute, join, relative, sep } from "node:path";
import { pathToFileURL } from "node:url";
import { ROOT } from "./lib/common.ts";

export function within(directory: string, path: string): boolean {
	const rel = relative(directory, path);
	return (
		rel === "" ||
		(rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
	);
}

export function isolatedEnvironment(
	root: string,
	parent: NodeJS.ProcessEnv = process.env,
	platform: NodeJS.Platform = process.platform,
): NodeJS.ProcessEnv {
	const originalHome = parent["HOME"] ?? parent["USERPROFILE"];
	if (!originalHome) throw new Error("E2E requires HOME or USERPROFILE");
	const originalData =
		parent["MISE_DATA_DIR"] ??
		join(
			parent["XDG_DATA_HOME"] ??
				(platform === "win32"
					? (parent["LOCALAPPDATA"] ?? join(originalHome, "AppData", "Local"))
					: join(originalHome, ".local", "share")),
			"mise",
		);
	const originalConfig =
		parent["MISE_CONFIG_DIR"] ??
		join(parent["XDG_CONFIG_HOME"] ?? join(originalHome, ".config"), "mise");
	// Cache executables, never browser profiles or test state.
	const browserCache =
		platform === "win32"
			? (parent["LOCALAPPDATA"] ?? join(originalHome, "AppData", "Local"))
			: platform === "darwin"
				? join(originalHome, "Library", "Caches")
				: (parent["XDG_CACHE_HOME"] ?? join(originalHome, ".cache"));
	const cacheRoot =
		parent["CI"] === "true" ? parent["PI_EXT_CI_CACHE_ROOT"] : undefined;
	if (cacheRoot && !isAbsolute(cacheRoot))
		throw new Error("CI cache root must be absolute");
	const env: NodeJS.ProcessEnv = {
		...parent,
		HOME: join(root, "home"),
		USERPROFILE: join(root, "home"),
		APPDATA: join(root, "config"),
		LOCALAPPDATA: join(root, "data"),
		XDG_CONFIG_HOME: join(root, "config"),
		XDG_CACHE_HOME: join(root, "cache"),
		XDG_DATA_HOME: join(root, "data"),
		XDG_STATE_HOME: join(root, "state"),
		TMPDIR: join(root, "tmp"),
		TMP: join(root, "tmp"),
		TEMP: join(root, "tmp"),
		PLAYWRIGHT_BROWSERS_PATH: cacheRoot
			? join(cacheRoot, "browsers")
			: parent["PLAYWRIGHT_BROWSERS_PATH"] ||
				join(browserCache, "ms-playwright"),
		npm_config_cache: cacheRoot
			? (parent["NPM_CONFIG_CACHE"] ?? join(cacheRoot, "npm"))
			: join(root, "npm-cache"),
		PI_CODING_AGENT_DIR: join(root, "agent"),
		PI_BAK_E2E_S3: "0",
		PI_EXT_E2E_ROOT: root,
		MISE_CONFIG_DIR: originalConfig,
		MISE_DATA_DIR: originalData,
		MISE_CACHE_DIR: cacheRoot
			? join(cacheRoot, "downloads")
			: join(root, "mise-cache"),
		MISE_STATE_DIR: join(root, "mise-state"),
		// The fresh state dir holds no trust records; trust this checkout explicitly.
		MISE_TRUSTED_CONFIG_PATHS: [parent["MISE_TRUSTED_CONFIG_PATHS"], ROOT]
			.filter(Boolean)
			.join(delimiter),
		MISE_AUTO_INSTALL: "0",
		MISE_TASK_RUN_AUTO_INSTALL: "0",
	};
	for (const key of Object.keys(env))
		if (key.startsWith("PI_BAK_S3_")) delete env[key];
	return env;
}

export function requireVideoTools(): void {
	let encoders: string;
	try {
		encoders = execFileSync("ffmpeg", ["-hide_banner", "-encoders"], {
			encoding: "utf8",
			timeout: 5000,
			maxBuffer: 1024 * 1024,
		});
	} catch (cause) {
		throw new Error(
			"Chrome video tests require a working ffmpeg binary on PATH",
			{ cause },
		);
	}
	if (!/(?:^|\s)libvpx-vp9(?:\s|$)/u.test(encoders))
		throw new Error(
			"Chrome video tests require ffmpeg with the libvpx-vp9 encoder on PATH",
		);
	try {
		execFileSync("ffprobe", ["-version"], {
			encoding: "utf8",
			timeout: 5000,
			maxBuffer: 1024 * 1024,
		});
	} catch (cause) {
		throw new Error(
			"Chrome video tests require a working ffprobe binary on PATH",
			{ cause },
		);
	}
}

function run(
	command: string,
	args: string[],
	env: NodeJS.ProcessEnv,
	signal: AbortSignal,
): Promise<number> {
	if (signal.aborted) return Promise.resolve(130);
	return new Promise((resolve, reject) => {
		const child = spawn(command, args, {
			cwd: ROOT,
			env,
			stdio: "inherit",
			detached: process.platform !== "win32",
		});
		const interrupt = () => {
			try {
				if (process.platform !== "win32" && child.pid)
					// Playwright coordinates worker teardown on SIGINT; SIGTERM can
					// kill its coordinator before fixtures finish writing.
					process.kill(-child.pid, "SIGINT");
				else child.kill("SIGTERM");
			} catch {
				// The child already exited.
			}
		};
		signal.addEventListener("abort", interrupt, { once: true });
		child.once("error", (error) => {
			signal.removeEventListener("abort", interrupt);
			reject(error);
		});
		child.once("close", (code, exitSignal) => {
			signal.removeEventListener("abort", interrupt);
			resolve(signal.aborted ? 130 : (code ?? (exitSignal ? 1 : 0)));
		});
	});
}

export function selectedTasks(
	tasks: string[],
	filter: string | undefined,
): string[] {
	if (!filter) return tasks;
	if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(filter))
		throw new Error("E2E filter must be an extension slug");
	const selected = tasks.filter(
		(task) => task === `//extensions/${filter}:e2e`,
	);
	if (selected.length !== 1) throw new Error(`No local E2E task for ${filter}`);
	return selected;
}

export function internalTask(task: string): string {
	if (!/^\/\/extensions\/[a-z0-9]+(?:-[a-z0-9]+)*:e2e$/.test(task))
		throw new Error(`Expected an extension E2E task: ${task}`);
	return `${task}-run`;
}

export async function main(
	tasks: string[] = process.argv.slice(2),
): Promise<number> {
	const separator = tasks.indexOf("--");
	const args = separator === -1 ? [] : tasks.slice(separator + 1);
	tasks = separator === -1 ? tasks : tasks.slice(0, separator);
	if (tasks.length === 0)
		throw new Error("E2E requires explicit Mise task names");
	tasks = selectedTasks(tasks, process.env["PI_EXT_E2E_FILTER"]);
	if (args.length && tasks.length !== 1)
		throw new Error("E2E runner arguments require one selected suite");
	for (const task of tasks) internalTask(task);
	const jobs = Number(process.env["PI_EXT_E2E_JOBS"] ?? "1");
	if (!Number.isInteger(jobs) || jobs < 1 || jobs > 2)
		throw new Error("E2E suite jobs must be 1 or 2");
	if (tasks.includes("//extensions/chrome-cdp:e2e")) requireVideoTools();
	const [repo, osTemp] = await Promise.all([
		realpath(ROOT),
		realpath(tmpdir()),
	]);
	if (within(repo, osTemp))
		throw new Error(
			`OS temporary directory must be outside repository: ${osTemp}`,
		);
	const root = await mkdtemp(join(osTemp, "pi-ext-e2e-"));
	const abort = new AbortController();
	const interrupt = () => abort.abort();
	process.on("SIGINT", interrupt);
	process.on("SIGTERM", interrupt);
	try {
		for (const name of [
			"home",
			"config",
			"cache",
			"data",
			"state",
			"tmp",
			"agent",
		])
			await mkdir(join(root, name));
		const env = isolatedEnvironment(root);
		const installed = await run(
			"npm",
			["exec", "--", "playwright", "install", "chromium", "firefox"],
			env,
			abort.signal,
		);
		if (installed !== 0) return installed;
		const failures: string[] = [];
		let cursor = 0;
		// Keep each suite in its own fail-fast Mise invocation: a failed build
		// must never run its consumer against the previous dist package.
		const workers = await Promise.allSettled(
			Array.from({ length: Math.min(jobs, tasks.length) }, async () => {
				try {
					while (cursor < tasks.length && !abort.signal.aborted) {
						const task = tasks[cursor++];
						if (task === undefined) break;
						const exitCode = await run(
							"mise",
							[
								"run",
								...(process.platform === "win32"
									? ["--shell", "cmd.exe /d /s /c"]
									: []),
								internalTask(task),
								...args,
							],
							env,
							abort.signal,
						);
						if (exitCode !== 0) failures.push(task);
					}
				} catch (error) {
					abort.abort();
					throw error;
				}
			}),
		);
		for (const worker of workers)
			if (worker.status === "rejected") throw worker.reason;
		if (abort.signal.aborted) return 130;
		if (failures.length) {
			console.error(`E2E failed: ${failures.join(", ")}`);
			return 1;
		}
		return 0;
	} finally {
		try {
			await rm(root, { recursive: true, force: true });
		} finally {
			process.off("SIGINT", interrupt);
			process.off("SIGTERM", interrupt);
		}
	}
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
	try {
		process.exitCode = await main();
	} catch (error) {
		console.error(error instanceof Error ? error.message : String(error));
		process.exitCode = 1;
	}
}