1/**
2 * spawn and manage other programs as sub-processes.
3 * @module
4 */
5
6/**
7 * execute a subprocess and wait for it to exit, returning what it wrote to
8 * stdout. stderr is captured too, shown via {@linkcode ExitError} on failure.
9 * this is, essentially, a simpler version of {@linkcode spawn}.
10 */
11export async function execute(
12 cmd: Command,
13 opts?: Omit<Options, "stdout" | "stderr">,
14): Promise<string> {
15 await using proc = spawn(cmd, { ...opts, stdout: "pipe", stderr: "pipe" });
16 const [stdout, stderr] = await Promise.all([
17 new Response(proc.stdout).text(),
18 new Response(proc.stderr).text(),
19 ]);
20
21 try {
22 await proc.wait();
23 } catch (err) {
24 if (err instanceof ExitError) err.stderr = stderr;
25 throw err;
26 }
27 return stdout;
28}
29
30/**
31 * start a command and return at once. how it ends, which includes not being
32 * able to start, is found by {@linkcode Subprocess.wait}.
33 */
34export function spawn<const O extends Options>(cmd: Command, opts?: O): Subprocess<O> {
35 const { stdin = "ignore", stdout = "inherit", stderr = "inherit" }: Options = opts ?? {};
36 const { cwd, env, signal, ipc, shell, progress: handoff }: Options = opts ?? {};
37 signal?.throwIfAborted();
38
39 const stdio: Array<Stdio | "ipc"> = [stdin, stdout, stderr];
40 if (handoff) stdio.push("pipe");
41 if (ipc) stdio.push("ipc");
42
43 const child = child_process.spawn(cmd[0], cmd.slice(1), {
44 cwd,
45 shell,
46 env: { ...process.env, ...env, ...handoff && progress.ipcChildEnvironment(progressFd) },
47 stdio,
48 });
49
50 const onAbort = () => void child.kill();
51 signal?.addEventListener("abort", onAbort);
52
53 const report = handoff
54 && progress.decodeAttachToRef(toWeb(child.stdio[progressFd] as stream.Readable), handoff);
55
56 const exit = new Promise<void>((resolve, reject) => {
57 child.on("error", reject);
58 child.once("exit", (code, exitSignal) => {
59 if (signal?.aborted) reject(signal.reason);
60 else if (code === 0) resolve();
61 else reject(new ExitError(cmd, code, exitSignal));
62 });
63 })
64 // the last of what the child reported is in before `wait` is over
65 .finally(() => report)
66 .finally(() => signal?.removeEventListener("abort", onAbort));
67
68 // a failure is only an error to those who `wait` for it
69 exit.catch(() => {});
70 report?.catch(() => {});
71
72 const proc: Subprocess = {
73 stdin: child.stdin && stream.Writable.toWeb(child.stdin),
74 stdout: child.stdout && toWeb(child.stdout),
75 stderr: child.stderr && toWeb(child.stderr),
76 wait: () => exit,
77 kill: (killSignal) => void child.kill(killSignal),
78 send(message, callback) {
79 ASSERT(ipc, "`send` is for a process started with the `ipc` option");
80 child.send(message as child_process.Serializable, callback);
81 },
82 on: (event: string, listener: (message: unknown) => void) => void child.on(event, listener),
83 off: (event: string, listener: (message: unknown) => void) => void child.off(event, listener),
84 async [Symbol.asyncDispose]() {
85 child.kill();
86 await exit.catch(() => {});
87 // a pipe that was not read to its end holds a file descriptor
88 for (const pipe of child.stdio) pipe?.destroy();
89 },
90 };
91 return proc as Subprocess<O>;
92}
93
94/** where a child has the pipe for its `progress`: after stdin, stdout, and stderr */
95const progressFd = 3;
96
97/** node.js types its web streams apart from the global ones */
98function toWeb(pipe: stream.Readable) {
99 return stream.Readable.toWeb(pipe) as ReadableStream<Uint8Array>;
100}
101
102/** a program followed by its arguments */
103export type Command = readonly [string, ...string[]];
104
105/** `"pipe"` puts a stream on the {@linkcode Subprocess} */
106export type Stdio = "pipe" | "inherit" | "ignore";
107
108export interface Options {
109 cwd?: string;
110 /** added to the environment of this process */
111 env?: Record<string, string>;
112 /** kills the process when aborted, and `wait` rejects with its reason */
113 signal?: AbortSignal;
114 /** @default "ignore" */
115 stdin?: Stdio;
116 /** @default "inherit" */
117 stdout?: Stdio;
118 /** @default "inherit" */
119 stderr?: Stdio;
120 /** run `cmd` through the system shell, which does not escape what it is given */
121 shell?: boolean;
122 /** open a channel for messages with a child that is node.js too, where it is `process` */
123 ipc?: boolean;
124 /** for a subprocess using `@clo/lib/process`, setup progress IPC. */
125 progress?: progress.Ref;
126}
127
128/** disposing kills the process if it is still running, and waits for it to exit */
129export interface Subprocess<O extends Options = Options> extends AsyncDisposable {
130 stdin: Piped<O["stdin"], WritableStream<Uint8Array>>;
131 stdout: Piped<O["stdout"], ReadableStream<Uint8Array>>;
132 stderr: Piped<O["stderr"], ReadableStream<Uint8Array>>;
133 /** resolves once the process exits with code zero. any other exit rejects with an {@linkcode ExitError} */
134 wait(): Promise<void>;
135 kill(signal?: NodeJS.Signals): void;
136
137 /** send a message over the `ipc` channel. `callback` hears if it could not be */
138 send(message: unknown, callback?: (error: Error | null) => void): void;
139 on(event: "message", listener: (message: unknown) => void): void;
140 on(event: "disconnect", listener: () => void): void;
141 off(event: "message", listener: (message: unknown) => void): void;
142 off(event: "disconnect", listener: () => void): void;
143}
144
145type Piped<S, T> = S extends "pipe" ? T : null;
146
147/** how a process ended, when that was not with exit code zero */
148export class ExitError extends Error {
149 /** as it would be typed into a shell */
150 cmd: string;
151 code: number | null;
152 signal: NodeJS.Signals | null;
153 /** only when {@linkcode execute} ran the command */
154 declare stderr?: string;
155
156 constructor(cmd: Command, code: number | null, signal: NodeJS.Signals | null) {
157 // windows prints exit codes signed, such as -1073741819 for an access violation
158 if (code !== null && code > 2 ** 31) code |= 0;
159 super(`${path.basename(cmd[0])} failed with ${signal ? `signal ${signal}` : `code ${code}`}`);
160
161 this.cmd = cmd.map(string.escapeShellArgument).join(" ");
162 this.code = code;
163 this.signal = signal;
164 }
165}
166
167async function findInodeForPort(port: number) {
168 const hexPort = port.toString(16).toUpperCase().padStart(4, "0");
169 for (const f of ["/proc/net/tcp", "/proc/net/tcp6"]) {
170 try {
171 const lines = (await fs.readFile(f, "utf8")).split("\n").slice(1);
172 for (const line of lines) {
173 const parts = line.trim().split(/\s+/);
174 if (parts[1]?.split(":")[1] === hexPort) return parts[9];
175 }
176 } catch {}
177 }
178 return null;
179}
180
181async function findPidForInode(inode: string) {
182 const target = `socket:[${inode}]`;
183 for (const pid of await fs.readdir("/proc")) {
184 if (!/^\d+$/.test(pid)) continue;
185 try {
186 for (const fd of await fs.readdir(`/proc/${pid}/fd`)) {
187 try {
188 if (await fs.readlink(`/proc/${pid}/fd/${fd}`) === target) return pid;
189 } catch {}
190 }
191 } catch {}
192 }
193 return null;
194}
195
196async function commandFromPortLinux(port: number) {
197 const inode = await findInodeForPort(port);
198 if (!inode) throw new Error(`no process on port ${port}`);
199 const pid = await findPidForInode(inode);
200 if (!pid) throw new Error(`no pid for inode ${inode}`);
201 const raw = await fs.readFile(`/proc/${pid}/cmdline`, "utf8");
202 return { pid: Number(pid), command: raw.split("\0").filter(Boolean).join(" ") };
203}
204
205async function commandFromPortMac(port: number) {
206 const lsofOut = await execute(["lsof", "-ti", `tcp:${port}`]);
207 const pid = lsofOut.trim().split("\n")[0];
208 if (!pid) throw new Error(`no process on port ${port}`);
209 const psOut = await execute(["ps", "-p", pid, "-o", "args="]);
210 return { pid: Number(pid), command: psOut.trim() };
211}
212
213async function commandFromPortWindows(port: number) {
214 const stdout = await execute(["netstat", "-ano"]);
215 const line = stdout.split("\n").find(l => {
216 const m = l.match(/\s+[\d.:]+:(\d+)\s+/);
217 return m && parseInt(m[1]!) === port && l.includes("LISTENING");
218 });
219 if (!line) throw new Error(`no process on port ${port}`);
220 const pid = line.trim().split(/\s+/).at(-1);
221 const psOut = await execute([
222 "powershell",
223 "-NoProfile",
224 "-Command",
225 `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`,
226 ]);
227 const cmdline = psOut.trim();
228 if (!cmdline) throw new Error(`no cmdline for pid ${pid}`);
229 return { pid: Number(pid), command: cmdline };
230}
231
232/** Racily searches for what process is taking up a given port. */
233export function lookupProcessOnPort(port: number): Promise<ProcessLookup> {
234 switch (os.platform()) {
235 case "linux":
236 return commandFromPortLinux(port);
237 case "darwin":
238 return commandFromPortMac(port);
239 case "win32":
240 return commandFromPortWindows(port);
241 default:
242 throw new Error(`unsupported platform: ${os.platform()}`);
243 }
244}
245
246interface ProcessLookup {
247 pid: number;
248 command: string;
249}
250
251/** opens a file in the logically configured text/code editor */
252export async function launchEditor(file: string, options: EditorOptions = {}): Promise<void> {
253 const { fileName, line: fileLine, column: fileColumn } = parsePosition(file);
254 const line = options.line ?? fileLine;
255 const column = options.column ?? fileColumn ?? 1;
256 const windows = os.platform() === "win32";
257
258 // cmd.exe would happily run an editor off of a remote share
259 if (windows && fileName.startsWith("\\\\")) {
260 throw new Error("cannot open a UNC path on windows");
261 }
262
263 const specified = options.editor ?? process.env.LAUNCH_EDITOR;
264 const [editor, ...args] = specified ? splitCommand(specified) : await runningEditor();
265 if (!editor) throw new Error(`cannot open ${path.basename(fileName)}: no editor found, set $EDITOR`);
266
267 // an editor this port has no arguments for gets a position only when the user
268 // named it, since the wrong flags make editors create files or hang on input.
269 const position = line === undefined ? null : positionArgs(editor, fileName, line, column)
270 ?? (specified ? [fileName, `${line}`, `${column}`] : null);
271 args.push(...position ?? [fileName]);
272
273 const inTerminal = terminalEditors.has(editorName(editor));
274 // two editors sharing the terminal would both read from its input
275 if (inTerminal && currentEditor) {
276 currentEditor.replaced = true;
277 await currentEditor.proc[Symbol.asyncDispose]();
278 }
279
280 const proc = spawn(windows ? [windowsLaunchCommand(editor, args)] : [editor, ...args], {
281 stdin: "inherit",
282 shell: windows,
283 });
284 const entry: typeof currentEditor = inTerminal ? { proc } : null;
285 if (entry) currentEditor = entry;
286 try {
287 await proc.wait();
288 } catch (error) {
289 if (entry?.replaced) return;
290 const why = exception.code(error) === "ENOENT" ? ": not found in $PATH" : "";
291 throw new Error(`could not open ${path.basename(fileName)} in ${editorName(editor)}${why}`, { cause: error });
292 } finally {
293 if (currentEditor === entry) currentEditor = null;
294 }
295}
296
297/** opens a url in the default browser */
298export async function launchBrowser(url: string) {
299 switch (process.platform) {
300 case "darwin":
301 await execute(["open", url]);
302 break;
303 case "win32":
304 await execute(["cmd.exe", "/c", "start", "\"\"", url]);
305 break;
306 default:
307 await execute(["xdg-open", url]);
308 break;
309 }
310}
311
312export interface EditorOptions {
313 /**
314 * the editor to run, as a shell command so that arguments may be included.
315 * defaults to `$LAUNCH_EDITOR`, then the editor this machine has running,
316 * then `$VISUAL` or `$EDITOR`. an editor named here that this module has no
317 * arguments for is passed the line and column as two more arguments.
318 */
319 editor?: string;
320 /** 1-based, taking precedence over a `:line` in the file name */
321 line?: number;
322 /** 1-based, defaulting to the first column */
323 column?: number;
324}
325
326/** the editor holding the terminal's input, which only one of them may */
327let currentEditor: { proc: Subprocess; replaced?: boolean } | null = null;
328
329/** `file.ts:12:4`, where the line and column are optional, or a `file://` url */
330function parsePosition(file: string) {
331 if (file.startsWith("file://")) file = url.fileURLToPath(file);
332 const [suffix, line, column] = /:(\d+)(?::(\d+))?$/.exec(file) ?? [];
333 return {
334 fileName: path.resolve(suffix ? file.slice(0, -suffix.length) : file),
335 line: line ? Number(line) : undefined,
336 column: column ? Number(column) : undefined,
337 };
338}
339
340/** splits `code -w` or `'/Volumes/My Disk/zed' --new`, quotes included */
341function splitCommand(command: string): string[] {
342 return command.match(/'[^']*'|"[^"]*"|\S+/g)
343 ?.map((arg) => arg.replace(/^(['"])(.*)\1$/s, "$2")) ?? [];
344}
345
346/** the name an editor is known by, however it was spelled or installed */
347function editorName(editor: string): string {
348 // `.exe`/`.cmd` and jetbrains' `64` suffix both name the editor before them
349 return path.basename(editor).toLowerCase().replace(/\.(exe|cmd|bat)$/, "").replace(/64$/, "");
350}
351
352/** arguments placing an editor's cursor at a position, or `null` if unknown */
353function positionArgs(editor: string, fileName: string, line: number, column: number): string[] | null {
354 switch (argStyles.get(editorName(editor))) {
355 case "vscode":
356 return ["-r", "-g", `${fileName}:${line}:${column}`];
357 case "suffix":
358 return [`${fileName}:${line}:${column}`];
359 case "jetbrains":
360 return ["--line", `${line}`, "--column", `${column}`, fileName];
361 case "mate":
362 return ["--line", `${line}`, fileName];
363 case "vim":
364 return [`+call cursor(${line}, ${column})`, fileName];
365 case "plus":
366 return [`+${line}`, fileName];
367 case "emacs":
368 return [`+${line}:${column}`, fileName];
369 case "notepad++":
370 return [`-n${line}`, `-c${column}`, fileName];
371 default:
372 return null;
373 }
374}
375
376/**
377 * cmd.exe would expand `&`, `|`, and friends out of a file name before the
378 * editor sees it, so they are escaped with `^`. `%var%` is expanded before the
379 * escapes are consumed and a line break starts another command: neither can be
380 * written safely, and a path containing one is refused instead.
381 */
382function windowsLaunchCommand(editor: string, args: string[]): string {
383 if (args.some((arg) => /[\r\n%]/.test(arg))) {
384 throw new Error(`cannot open a path containing a line break or '%' on windows`);
385 }
386 return [editor, ...args.map((arg) => arg.replace(/[&|<>,;=^]/g, "^$&"))]
387 // an escape has to be quoted, and the quotes around it escaped as well
388 .map((arg) => arg.includes("^") ? `^"${arg}^"` : arg.includes(" ") ? `"${arg}"` : arg)
389 .join(" ");
390}
391
392/**
393 * the editor this machine has open, found in the process list, falling back to
394 * the classic environment variables. the result is a command, since an editor
395 * in `$EDITOR` may carry arguments.
396 */
397async function runningEditor(): Promise<string[]> {
398 try {
399 const platform = os.platform();
400 if (platform === "darwin") {
401 const processes = (await execute(["ps", "x", "-o", "comm="])).split("\n");
402 for (const [app, cli] of macosEditors) {
403 // an app outside of /Applications matches too, and runs from where it is
404 const running = processes.find((name) => name.endsWith(app));
405 if (running) return [cli || running];
406 }
407 } else if (platform === "linux") {
408 const command = ["ps", "x", "--no-heading", "-o", "comm", "--sort=comm"] as const;
409 const processes = new Set((await execute(command)).split("\n").map((l) => l.trim()));
410 for (const [name, cli] of linuxEditors) {
411 if (processes.has(name) || processes.has(name + ".sh")) return [cli || name];
412 }
413 } else if (platform === "win32") {
414 const query = "select executablepath from win32_process where executablepath is not null";
415 const processes = await execute([
416 "powershell",
417 "-NoProfile",
418 "-Command",
419 `[Console]::OutputEncoding=[Text.Encoding]::UTF8;`
420 + `Get-CimInstance -Query '${query}' | ForEach-Object { $_.ExecutablePath }`,
421 ]);
422 for (const exe of processes.split("\r\n").map((line) => line.trim())) {
423 if (windowsEditors.has(path.win32.basename(exe))) return [exe];
424 }
425 }
426 } catch {
427 // without a process list there is nothing to detect
428 }
429 const fallback = process.env.VISUAL || process.env.EDITOR;
430 return fallback ? splitCommand(fallback) : [];
431}
432
433/** editor name to the shape of the arguments that open a position in it */
434const argStyles = new Map(
435 ( // deno-fmt-ignore
436 "vscode#code,code - insiders,codium,vscodium,cursor,trae,antigravity\n"
437 + "suffix#atom,subl,sublime,sublime_text,wstorm,charm,zed\n"
438 + "jetbrains#appcode,clion,idea,phpstorm,pycharm,rubymine,webstorm,goland,rider\n"
439 + "mate#mate,rmate,mine\n"
440 + "vim#vim,mvim\n"
441 + "plus#joe,gvim\n"
442 + "emacs#emacs,emacsclient\n"
443 + "notepad++#notepad++"
444 ).split("\n").flatMap((group) => {
445 const [style, editors] = group.split("#") as [string, string];
446 return editors.split(",").map((editor) => [editor, style] as const);
447 }),
448);
449
450/** editors that take over the currentEditor they are started in */
451const terminalEditors = new Set("vi vim nvim nano emacs joe helix hx micro kak".split(" "));
452
453/**
454 * the tail of the binary macos names a running editor by, to the command that
455 * opens a file in it. an app that launches itself has no command here, so the
456 * binary that is running is used, wherever it was installed.
457 */
458const macosEditors = new Map(
459 ( // deno-fmt-ignore
460 "/Atom.app/Contents/MacOS/Atom#atom\n"
461 + "/Sublime Text.app/Contents/MacOS/Sublime Text#/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl\n"
462 + "/Sublime Text.app/Contents/MacOS/sublime_text#/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl\n"
463 + "/Visual Studio Code.app/Contents/MacOS/Code#code\n"
464 + "/Visual Studio Code.app/Contents/MacOS/Electron#code\n"
465 + "/Visual Studio Code - Insiders.app/Contents/MacOS/Code - Insiders#code-insiders\n"
466 + "/Visual Studio Code - Insiders.app/Contents/MacOS/Electron#code-insiders\n"
467 + "/VSCodium.app/Contents/MacOS/Electron#codium\n"
468 + "/Cursor.app/Contents/MacOS/Cursor#cursor\n"
469 + "/Trae.app/Contents/MacOS/Electron#trae\n"
470 + "/Antigravity.app/Contents/MacOS/Electron#antigravity\n"
471 + "/Zed.app/Contents/MacOS/zed#zed\n"
472 + "/MacVim.app/Contents/MacOS/MacVim#mvim\n"
473 + "/AppCode.app/Contents/MacOS/appcode\n"
474 + "/CLion.app/Contents/MacOS/clion\n"
475 + "/IntelliJ IDEA.app/Contents/MacOS/idea\n"
476 + "/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea\n"
477 + "/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea\n"
478 + "/PhpStorm.app/Contents/MacOS/phpstorm\n"
479 + "/PyCharm.app/Contents/MacOS/pycharm\n"
480 + "/PyCharm CE.app/Contents/MacOS/pycharm\n"
481 + "/RubyMine.app/Contents/MacOS/rubymine\n"
482 + "/WebStorm.app/Contents/MacOS/webstorm\n"
483 + "/GoLand.app/Contents/MacOS/goland\n"
484 + "/Rider.app/Contents/MacOS/rider"
485 ).split("\n").map((line) => line.split("#") as [string, string | undefined]),
486);
487
488/** process name linux names a running editor by, to the command that opens a file in it */
489const linuxEditors = new Map(
490 ( // deno-fmt-ignore
491 "atom code-insiders code codium vscodium cursor trae antigravity"
492 + " zed emacs gvim vim sublime_text#subl"
493 + " idea phpstorm pycharm rubymine webstorm goland rider"
494 ).split(" ").map((entry) => entry.split("#") as [string, string | undefined]),
495);
496
497/** windows has no command to open a file in an editor, so the binary is run */
498const windowsEditors = new Set(
499 ( // deno-fmt-ignore
500 "Code.exe,Code - Insiders.exe,VSCodium.exe,Cursor.exe,Trae.exe,Antigravity.exe,zed.exe"
501 + ",atom.exe,sublime_text.exe,notepad++.exe"
502 + ",clion.exe,clion64.exe,idea.exe,idea64.exe,phpstorm.exe,phpstorm64.exe,pycharm.exe,pycharm64.exe"
503 + ",rubymine.exe,rubymine64.exe,webstorm.exe,webstorm64.exe,goland.exe,goland64.exe,rider.exe,rider64.exe"
504 ).split(","),
505);
506
507import * as child_process from "node:child_process";
508import * as fs from "node:fs/promises";
509import * as os from "node:os";
510import * as path from "node:path";
511import * as process from "node:process";
512import * as stream from "node:stream";
513import * as url from "node:url";
514import { ASSERT } from "./assert.ts";
515import * as exception from "./exception.ts";
516import * as progress from "./progress.ts";
517import * as string from "./string.ts";