diff --git a/packages/cli/src/open.ts b/packages/cli/src/open.ts index 495346a..8663e1b 100644 --- a/packages/cli/src/open.ts +++ b/packages/cli/src/open.ts @@ -3,14 +3,27 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; /** - * One way to open a file. `orAt` is where `cmd` lives when it isn't on the PATH. `startFile` is a file for - * PowerShell to start (WSL): its Windows path goes on the end of `args`, as an encoded command. + * One way to open a file. `orAt` finds `cmd` when it isn't on the PATH. `startFile` is a file for PowerShell to + * start (WSL): its Windows path goes on the end of `args`, as an encoded command. `wait` is how long, in ms, the + * opener gets to exit before it counts as having handed the file off. */ -export type Opener = { cmd: string; args: string[]; orAt?: string; startFile?: string }; +export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number }; -// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`; this is the default mount. -const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'; const NOT_FOUND = 'not found'; +// xdg-open can turn into the browser itself and never exit, so a short wait has to count as a hand-off. +const HANDED_OFF = 3000; +// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only +// sign that nothing opened. +const WINDOWS_START = 15000; + +// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt. +function powershell(): string { + try { + return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'); + } catch { + return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'; + } +} /** Whether this Linux is WSL, where a stock distro has no xdg-open but Windows has a browser. */ export function isWsl(env: NodeJS.ProcessEnv = process.env): boolean { @@ -38,22 +51,26 @@ export function browserCommands( if (!wsl) return [{ cmd: 'xdg-open', args: [file] }]; // The browser is on the Windows side. xdg-open comes last: with no Linux browser it can exit 0 having opened // nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file. - return [ - { cmd: 'wslview', args: [file] }, - { cmd: 'powershell.exe', orAt: POWERSHELL, args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], startFile: file }, - { cmd: 'xdg-open', args: [file] }, - ]; + const start: Opener = { + cmd: 'powershell.exe', + orAt: powershell, + args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], + startFile: file, + wait: WINDOWS_START, + }; + // wslview hands the path to PowerShell with quoting of its own, so it only gets paths PowerShell reads literally. + const viaWslview: Opener[] = /[$`'"‘’‚‛“”„]/.test(file) ? [] : [{ cmd: 'wslview', args: [file], wait: WINDOWS_START }]; + return [...viaWslview, start, { cmd: 'xdg-open', args: [file] }]; } -/** The PowerShell command that opens `windowsPath` with its default app. */ export function startCommand(windowsPath: string): string { // PowerShell ends a single-quoted string on the curly quotes too; a doubled one is the only escape. return `Start-Process -FilePath '${windowsPath.replace(/['‘’‚‛]/g, '$&$&')}'`; } -function wslpath(file: string): string { +function wslpath(to: '-w' | '-u', path: string): string { // stderr is dropped so that wslpath's own message doesn't land ahead of the warning. - return execFileSync('wslpath', ['-w', file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); + return execFileSync('wslpath', [to, path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } /** @@ -65,8 +82,10 @@ export async function openInBrowser(file: string): Promise { return 'refused' in commands ? commands.refused : openWith(commands); } -/** Tries each opener until one hands the file off; resolves null then, or why every one of them failed. */ -export async function openWith(openers: Opener[], windowsPath: (file: string) => string = wslpath): Promise { +export async function openWith( + openers: Opener[], + windowsPath: (file: string) => string = (file) => wslpath('-w', file), +): Promise { const failures: string[] = []; for (const opener of openers) { const why = await run(opener, windowsPath); @@ -76,7 +95,10 @@ export async function openWith(openers: Opener[], windowsPath: (file: string) => return failures.join('; '); } -async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: string) => string): Promise { +async function run( + { cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener, + windowsPath: (file: string) => string, +): Promise { if (startFile !== undefined) { try { args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')]; @@ -84,16 +106,16 @@ async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: s return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path"; } } - let why = await launch(cmd, args); - if (why === NOT_FOUND && orAt) why = await launch(orAt, args); + let why = await launch(cmd, args, wait); + if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait); return why === null ? null : `${cmd} ${why}`; } -/** Resolves null once the command exits cleanly or is still running after a moment, else what went wrong. */ -function launch(cmd: string, args: string[]): Promise { +/** Resolves null once the command exits cleanly or is still running after `wait` ms, else what went wrong. */ +function launch(cmd: string, args: string[], wait: number): Promise { return new Promise((done) => { const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' }); - const timer = setTimeout(() => done(null), 3000); + const timer = setTimeout(() => done(null), wait); const finish = (why: string | null) => { clearTimeout(timer); done(why); diff --git a/packages/cli/test/open.test.ts b/packages/cli/test/open.test.ts index 31e26de..43e1681 100644 --- a/packages/cli/test/open.test.ts +++ b/packages/cli/test/open.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { browserCommands, isWsl, openWith, startCommand } from '../src/open'; +import { browserCommands, isWsl, openWith, startCommand, type Opener } from '../src/open'; const NODE = process.execPath; const MISSING = 'stackmap-no-such-opener'; const exits = (code: number) => ({ cmd: NODE, args: ['-e', `process.exit(${code})`] }); +// A Windows host has no signal exit status, and its path.resolve puts a drive on a POSIX path. +const posix = it.skipIf(process.platform === 'win32'); describe('browserCommands', () => { it('uses the native opener on darwin and linux', () => { @@ -12,8 +14,18 @@ describe('browserCommands', () => { }); it('tries the Windows side first on WSL, and xdg-open last', () => { - const commands = browserCommands('/tmp/a.html', 'linux', true); - expect(Array.isArray(commands) && commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']); + const commands = browserCommands('/tmp/a.html', 'linux', true) as Opener[]; + expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']); + // run() puts the encoded command straight after the last argument. + expect(commands[1]).toMatchObject({ startFile: '/tmp/a.html', orAt: expect.any(Function) }); + expect(commands[1]!.args.at(-1)).toBe('-EncodedCommand'); + }); + + it('keeps a path PowerShell would expand or unquote away from wslview', () => { + for (const file of ['/home/u/$(x)/a.html', '/home/u/a`b.html', "/home/u/it's.html", '/home/u/a"b.html']) { + const commands = browserCommands(file, 'linux', true) as Opener[]; + expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'xdg-open']); + } }); it('quotes the path for cmd on win32', () => { @@ -56,17 +68,23 @@ describe('openWith', () => { expect(await openWith([{ cmd: MISSING, args: [] }, exits(1)])).toBe(`${MISSING} not found; ${NODE} exited with 1`); }); - it('takes an opener killed by a signal as failed', async () => { + posix('takes an opener killed by a signal as failed', async () => { const killed = { cmd: NODE, args: ['-e', "process.kill(process.pid, 'SIGKILL')"] }; expect(await openWith([killed])).toBe(`${NODE} was killed by SIGKILL`); }); it('finds an opener that is off the PATH at its known location', async () => { - expect(await openWith([{ cmd: MISSING, orAt: NODE, args: ['-e', ''] }])).toBeNull(); - expect(await openWith([{ cmd: MISSING, orAt: `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`); + expect(await openWith([{ cmd: MISSING, orAt: () => NODE, args: ['-e', ''] }])).toBeNull(); + expect(await openWith([{ cmd: MISSING, orAt: () => `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`); + }); + + it('waits as long as the opener asks before taking it as handed off', async () => { + const slow = { cmd: NODE, args: ['-e', 'setTimeout(() => process.exit(1), 1000)'] }; + expect(await openWith([{ ...slow, wait: 100 }])).toBeNull(); + expect(await openWith([{ ...slow, wait: 30000 }])).toBe(`${NODE} exited with 1`); }); - it('hands PowerShell the Windows path of the file as an encoded command', async () => { + posix('hands PowerShell the Windows path of the file as an encoded command', async () => { const want = "Start-Process -FilePath '\\\\wsl.localhost\\Ubuntu\\home\\u\\it''s.html'"; // The child exits 0 only when the argument after its own decodes to the command. const check = `process.exit(Buffer.from(process.argv[1], 'base64').toString('utf16le') === ${JSON.stringify(want)} ? 0 : 7)`;