Versions 37 to 318
new file, 54 lines
1+// Opening a page in the person's own browser, as `gh auth login` and `wrangler login` do. 2+// `abso login` opens the approve page with the code already in it, and still prints the 3+// link and the code: an open that fails, or is skipped, is silent, and the printed link stands. 5+import { spawn } from "node:child_process"; 7+/** Why not to open a browser here, or null to open one. */ 8+export function browserSkip(env: Readonly<Record<string, string | undefined>>, platform: string): string | null { 9+ if (env.ABSO_NO_BROWSER) return "ABSO_NO_BROWSER is set"; 10+ // Over SSH the browser would open on the far machine's desktop, if it has one. 11+ if (env.SSH_CONNECTION || env.SSH_TTY) return "this is an SSH session"; 12+ if (env.CI && env.CI !== "false" && env.CI !== "0") return "this is CI"; 13+ if (platform !== "win32" && platform !== "darwin" && !env.DISPLAY && !env.WAYLAND_DISPLAY) 14+ return "there's no display"; 19+ * The program that opens `url` in the default browser, and its arguments. No shell, so nothing in the url is 20+ * read as shell syntax. On Windows that rules out cmd's start, which cuts a url at its first &. 22+export function openCommand(url: string, platform: string): [string, string[]] { 23+ if (platform === "win32") return ["rundll32", ["url.dll,FileProtocolHandler", url]]; 24+ if (platform === "darwin") return ["open", [url]]; 25+ return ["xdg-open", [url]]; 28+/** Only web pages are opened: a link from a server is never handed to the desktop as a file or another program. */ 29+export function isWebLink(url: string): boolean { 31+ const u = new URL(url); 32+ return u.protocol === "https:" || u.protocol === "http:"; 39+ * Opens `url` in the default browser and doesn't wait. Answers whether it started an opener; a failure 40+ * (no such program, refused) is silent. 42+export function openInBrowser(url: string, platform: string = process.platform, run: typeof spawn = spawn): boolean { 43+ if (!isWebLink(url)) return false; 44+ // The link as the check parsed it, so what opens is exactly what was checked. 45+ const [command, args] = openCommand(new URL(url).href, platform); 47+ const child = run(command, args, { detached: true, stdio: "ignore", windowsHide: true }); 48+ child.on("error", () => {});