Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/open-browser.ts

Raw
import { pathToFileURL } from "node:url";
import { openUrl as openPlatformUrl } from "./src/pi-ext-browser-open.ts";

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" };
	const command = await openPlatformUrl(url, {
		...options,
		env,
		timeoutMs: 1500,
	});
	if (command) return { ok: true, url, command };
	return { ok: false, url, error: "No browser opener found" };
}