repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/open.ts

Raw
File outline
import { spawn } from "node:child_process";
import { uiError } from "./errors";

export function openerCandidates(
	url: string,
	options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
): Array<{ command: string; args: string[] }> {
	const platform = options.platform ?? process.platform;
	const env = options.env ?? process.env;
	if (env.TERMUX_VERSION) return [{ command: "termux-open-url", args: [url] }];
	if (platform === "darwin") return [{ command: "open", args: [url] }];
	if (platform === "win32") {
		return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
	}
	return [
		{ command: "xdg-open", args: [url] },
		{ command: "wslview", args: [url] },
		{ command: "gio", args: ["open", url] },
	];
}

export async function openBrowser(url: string): Promise<void> {
	if (process.env.NODE_ENV === "test" || process.env.VITEST) return;
	for (const candidate of openerCandidates(url)) {
		if (await trySpawn(candidate.command, candidate.args)) return;
	}
	throw uiError("open_failed", "Could not open browser", {
		action:
			"Open the /ui link manually from the terminal widget or scan the QR code.",
		retryable: true,
	});
}

function trySpawn(command: string, args: string[]): Promise<boolean> {
	return new Promise((resolve) => {
		const child = spawn(command, args, { detached: true, stdio: "ignore" });
		let settled = false;
		const done = (ok: boolean) => {
			if (settled) return;
			settled = true;
			resolve(ok);
		};
		child.once("error", () => done(false));
		child.once("spawn", () => {
			child.unref();
			done(true);
		});
		setTimeout(() => done(false), 1500).unref();
	});
}