- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/open-browser.ts?format=json
54 linesspeed 100%Last change speed in version 62, 2 versions changed it
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.
5import { spawn } from "node:child_process";
7/** Why not to open a browser here, or null to open one. */
8export 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";
15 return null;
16}
18/**
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 &.
21 */
22export 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]];
26}
28/** Only web pages are opened: a link from a server is never handed to the desktop as a file or another program. */
29export function isWebLink(url: string): boolean {
30 try {
31 const u = new URL(url);
32 return u.protocol === "https:" || u.protocol === "http:";
33 } catch {
34 return false;
35 }
36}
38/**
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.
41 */
42export 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);
46 try {
47 const child = run(command, args, { detached: true, stdio: "ignore", windowsHide: true });
48 child.on("error", () => {});
49 child.unref();
50 return true;
51 } catch {
52 return false;
53 }
54}