pi-ext
bugabingas pi extensions
owned by bugabinga
Add ui browser opener
06ec65d7c6fcb1e6346e5e267b15e9ac4c588b07
Oliver Krylow <o.krylow@isp-insoft.de> ·
unsigned
Browse filesCompare with HEAD
Changed files (2)
extensions/ui/__tests__/runtime.test.ts
Addednew file mode 100644 1 +import { describe, expect, it }
from "vitest";
2 +import { openerCandidates }
from "../open";
4 +describe(
"ui browser opener", ()
=> {
5 + it(
"uses platform openers", ()
=> {
6 + expect(
openerCandidates(
"http://x", { platform:
"win32", env: {} })[
0]).
toEqual(
9 + args: [
"/c",
"start",
"",
"http://x"],
13 + openerCandidates(
"http://x", { platform:
"darwin", env: {} })[
0],
18 + expect(
openerCandidates(
"http://x", { platform:
"linux", env: {} })[
0]).
toEqual(
20 + command:
"xdg-open",
26 + it(
"uses termux opener when available", ()
=> {
28 + openerCandidates(
"http://x", {
30 + env: { TERMUX_VERSION:
"1" },
33 + command:
"termux-open-url",
extensions/ui/open.ts
Addednew file mode 100644 1 +import { spawn }
from "node:child_process";
2 +import { uiError }
from "./errors";
4 +export function openerCandidates(
6 + options
: { platform
?: NodeJS.
Platform; env
?: NodeJS.
ProcessEnv }
= {},
7 +)
: Array<{ command
: string; args
: string[] }> {
8 + const platform
= options.
platform ?? process.
platform;
9 + const env
= options.env
?? process.
env;
10 + if (env.TERMUX_VERSION)
return [{ command:
"termux-open-url", args: [url] }];
11 + if (platform
=== "darwin")
return [{ command:
"open", args: [url] }];
12 + if (platform
=== "win32") {
13 + return [{ command:
"cmd.exe", args: [
"/c",
"start",
"", url] }];
16 + { command:
"xdg-open", args: [url] },
17 + { command:
"wslview", args: [url] },
18 + { command:
"gio", args: [
"open", url] },
22 +export async function openBrowser(url
: string)
: Promise<
void> {
23 + if (
process.
env.NODE_ENV
=== "test" || process.
env.VITEST)
return;
24 + for (
const candidate
of openerCandidates(url)) {
25 + if (
await trySpawn(candidate.command, candidate.args))
return;
27 + throw uiError(
"open_failed",
"Could not open browser", {
29 + "Open the /ui link manually from the terminal widget or scan the QR code.",
34 +function trySpawn(command
: string, args
: string[])
: Promise<
boolean> {
35 + return new Promise((resolve)
=> {
36 + const child
= spawn(command, args, { detached:
true, stdio:
"ignore" });
37 + let settled
= false;
38 + const done = (ok
: boolean)
=> {
39 + if (settled)
return;
43 + child.
once(
"error", ()
=> done(
false));
44 + child.
once(
"spawn", ()
=> {
48 + setTimeout(()
=> done(
false),
1500).
unref();