repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/open-browser.ts

Raw
File outline
import { spawn } from "node:child_process";
import { pathToFileURL } from "node:url";

export type BrowserOpenResult =
	| { ok: true; url: string; command: string }
	| { ok: false; url: string; error: string };

export async function openHtmlFile(
	file: string,
	options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
): Promise<BrowserOpenResult> {
	return openUrl(pathToFileURL(file).href, options);
}

export async function openUrl(
	url: string,
	options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
): Promise<BrowserOpenResult> {
	const env = options.env ?? process.env;
	if (env.NODE_ENV === "test" || env.VITEST)
		return { ok: false, url, error: "Browser opener disabled" };
	for (const candidate of openerCandidates(url, options)) {
		const ok = await trySpawn(candidate.command, candidate.args, env);
		if (ok) return { ok: true, url, command: candidate.command };
	}
	return { ok: false, url, error: "No browser opener found" };
}

export type BrowserOpenerCandidate = {
	command: string;
	args: string[];
};

export function openerCandidates(
	url: string,
	options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
): BrowserOpenerCandidate[] {
	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: "rundll32.exe",
				args: ["url.dll,FileProtocolHandler", url],
			},
		];
	return [
		{ command: "xdg-open", args: [url] },
		{ command: "wslview", args: [url] },
		{ command: "gio", args: ["open", url] },
	];
}

function trySpawn(
	command: string,
	args: string[],
	env: NodeJS.ProcessEnv,
): Promise<boolean> {
	return new Promise((resolve) => {
		const child = spawn(command, args, {
			detached: true,
			stdio: "ignore",
			windowsHide: true,
			env,
		});
		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();
	});
}