import { spawn } from "node:child_process";
import process from "node:process";
export async function openExternal(url, options = {}) {
    const parsed = new URL(url);
    const { command, args } = browserCommand(parsed.href, options.platform ?? process.platform);
    await launchBrowser(command, args, options.spawnProcess ?? spawn);
}
function browserCommand(url, platform) {
    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] };
}
function launchBrowser(command, args, spawnProcess) {
    return new Promise((resolve, reject) => {
        const child = spawnProcess(command, args, { detached: true, stdio: "ignore" });
        child.once("error", reject);
        child.once("close", (code, signal) => {
            if (code !== 0) {
                const reason = code === null ? `signal ${signal ?? "unknown"}` : `code ${code}`;
                reject(new Error(`Browser launcher exited with ${reason}`));
                return;
            }
            child.unref();
            resolve();
        });
    });
}
