Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

externalLauncher.ts

876 lines30.1 KB

1import * as NodePath from "@effect/platform-node/NodePath";
2import {
3 EDITORS,
4 ExternalLauncherError,
5 ExternalLauncherBrowserSpawnError,
6 ExternalLauncherCommandNotFoundError,
7 ExternalLauncherEditorSpawnError,
8 ExternalLauncherUnknownEditorError,
9 ExternalLauncherUnsupportedEditorError,
10 ExternalLauncherUnsupportedTargetError,
11 type EditorId,
12 type FileManagerRevealKind,
13 type LaunchEditorInput,
14} from "@t3tools/contracts";
15import { resolveEditorCommand } from "@t3tools/shared/editor";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import {
18 isCommandAvailable,
19 resolveSpawnCommand,
20 withPathDirectoryListings,
21} from "@t3tools/shared/shell";
22import * as Clock from "effect/Clock";
23import * as Config from "effect/Config";
24import * as Context from "effect/Context";
25import * as Deferred from "effect/Deferred";
26import * as Effect from "effect/Effect";
27import * as Base64 from "effect/encoding/Base64";
28import * as Exit from "effect/Exit";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as Ref from "effect/Ref";
34import * as Scope from "effect/Scope";
35import * as Stream from "effect/Stream";
36import * as ChildProcess from "effect/process/ChildProcess";
37import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
38​
39export {
40 ExternalLauncherError,
41 ExternalLauncherBrowserSpawnError,
42 ExternalLauncherCommandNotFoundError,
43 ExternalLauncherEditorSpawnError,
44 ExternalLauncherUnknownEditorError,
45 ExternalLauncherUnsupportedEditorError,
46 ExternalLauncherUnsupportedTargetError,
47} from "@t3tools/contracts";
48export type { LaunchEditorInput };
49interface EditorLaunch {
50 readonly editor: EditorId;
51 readonly target: string;
52 readonly command: string;
53 readonly args: ReadonlyArray<string>;
54 readonly detached?: boolean;
56​
57interface ProcessLaunch {
58 readonly command: string;
59 readonly args: ReadonlyArray<string>;
60 readonly options: ChildProcess.CommandOptions;
62​
63interface TargetPathAndPosition {
64 readonly path: string;
65 readonly line: string;
66 readonly column: Option.Option<string>;
68​
69/**
70 * Windows command shims (`code.cmd`) forward arguments through `%*`, which
71 * cmd.exe parses a second time after the first escaping layer is gone: a
72 * line break ends the command there, and a double quote closes the quoting
73 * that keeps `&` or `|` literal. Neither can occur in a Windows path.
74 */
75// oxlint-disable-next-line no-control-regex
76const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
77const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
78const POWERSHELL_ARGUMENTS_PREFIX = [
79 "-NoProfile",
80 "-NonInteractive",
81 "-ExecutionPolicy",
82 "Bypass",
83 "-EncodedCommand",
84] as const;
85​
86// Windows PowerShell started with DETACHED_PROCESS exits 0 without running its
87// command, so native Windows launches through it stay attached. WSL interop
88// PowerShell starts from a Linux process and keeps the detached launch.
89const WINDOWS_POWERSHELL_DETACHED = false;
90​
91const DETACHED_IGNORE_STDIO_OPTIONS = {
92 detached: true,
93 stdin: "ignore",
94 stdout: "ignore",
95 stderr: "ignore",
96} as const satisfies ChildProcess.CommandOptions;
97​
98const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
99 Object.fromEntries(
100 Object.entries(input).flatMap(([key, value]) =>
101 Option.match(value, {
102 onNone: () => [],
103 onSome: (resolved) => [[key, resolved]],
104 }),
105 ),
106 );
107​
108const BrowserLaunchEnvConfig = Config.all({
109 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
110 windir: Config.String("windir").pipe(Config.option),
111 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
112 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
113 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
114 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
115 container: Config.String("container").pipe(Config.option),
116 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
117 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
118}).pipe(Config.map(compactEnv));
119​
120const CommandLookupEnvConfig = Config.all({
121 PATH: Config.String("PATH").pipe(Config.option),
122 Path: Config.String("Path").pipe(Config.option),
123 path: Config.String("path").pipe(Config.option),
124 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
125 HOME: Config.String("HOME").pipe(Config.option),
126 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
127 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
128 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
129 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
130 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
131}).pipe(Config.map(compactEnv));
132​
133const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
134const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
135​
136function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
137 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
138 if (!match?.[1] || !match[2]) {
139 return Option.none();
140 }
141​
142 return Option.some({
143 path: match[1],
144 line: match[2],
145 column: Option.fromUndefinedOr(match[3]),
146 });
148​
149function resolveCommandEditorArgs(
150 editor: (typeof EDITORS)[number],
151 target: string,
152): ReadonlyArray<string> {
153 const parsedTarget = parseTargetPathAndPosition(target);
154​
155 switch (editor.launchStyle) {
156 case "direct-path":
157 return [target];
158 case "goto":
159 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
160 case "line-column":
161 return Option.match(parsedTarget, {
162 onNone: () => [target],
163 onSome: ({ path, line, column }) => [
164 "--line",
165 line,
166 // JetBrains IDEs count `--column` from 0; targets count columns from 1.
167 ...Option.match(column, {
168 onNone: () => [],
169 onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))],
170 }),
171 path,
172 ],
173 });
174 }
176​
177function encodeUtf16LeBase64(input: string): string {
178 const bytes = new Uint8Array(input.length * 2);
179 for (let index = 0; index < input.length; index += 1) {
180 const code = input.charCodeAt(index);
181 bytes[index * 2] = code & 0xff;
182 bytes[index * 2 + 1] = code >>> 8;
183 }
184 return Base64.encode(bytes);
186​
187function escapePowerShellStringLiteral(input: string): string {
188 return `'${input.replaceAll("'", "''")}'`;
190​
191function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
192 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
194​
195function resolveWslPowerShellPath(): string {
196 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
198​
199// File reveals from WSL resolve PowerShell through the interop PATH rather
200// than the fixed /mnt/c mount: the automount root is configurable, and a
201// PATH-resolved command keeps the advertised capability aligned with the
202// availability check `launchEditor` performs before spawning.
203const WSL_POWERSHELL_COMMAND = "powershell.exe";
204​
205function shouldUseWindowsHostFromWsl(
206 platform: NodeJS.Platform,
207 env: NodeJS.ProcessEnv = {},
208): boolean {
209 return (
210 platform === "linux" &&
211 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
212 env.SSH_CONNECTION === undefined &&
213 env.SSH_TTY === undefined &&
214 env.container === undefined
215 );
217​
218function resolveWindowsBrowserLaunch(
219 target: string,
220 command: string,
221 detached: boolean,
222): ProcessLaunch {
223 const encodedCommand = encodeUtf16LeBase64(
224 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
225 );
226 return {
227 command,
228 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
229 options: {
230 detached,
231 shell: false,
232 stdin: "ignore",
233 stdout: "ignore",
234 stderr: "ignore",
235 },
236 };
238​
239function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
240 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
241 (value) => value !== undefined && value.trim().length > 0,
242 );
244​
245function fileManagerCommandForPlatform(
246 platform: NodeJS.Platform,
247 env: NodeJS.ProcessEnv,
248): string | undefined {
249 switch (platform) {
250 case "darwin":
251 return "open";
252 case "win32":
253 return "explorer";
254 default:
255 if (shouldUseWindowsHostFromWsl(platform, env)) {
256 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
257 }
258 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
259 }
261​
262// A graphical session variable plus an executable `xdg-open` does not prove
263// that opening a directory does anything: without an `inode/directory` MIME
264// handler, `xdg-open` exits nonzero after the launcher has already detached, so
265// the client would see a silent no-op. The probe carries its own timeout well
266// inside the scan timeout `server.getConfig` applies to editor discovery: that
267// outer timeout degrades to an empty editor list, so a hung `xdg-mime` (broken
268// D-Bus or desktop session) must cost only the file manager, not every
269// discovered editor.
270const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
271​
272const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
273 function* (
274 env: NodeJS.ProcessEnv,
275 ): Effect.fn.Return<
276 boolean,
277 never,
278 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
279 > {
280 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
281 return false;
282 }
283​
284 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
285 return yield* spawner
286 .spawn(
287 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
288 stdin: "ignore",
289 stderr: "ignore",
290 }),
291 )
292 .pipe(
293 Effect.flatMap((handle) =>
294 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
295 concurrency: "unbounded",
296 }),
297 ),
298 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
299 Effect.scoped,
300 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
301 Effect.orElseSucceed(() => false),
302 );
303 },
304);
305​
306const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
307 function* (
308 command: string,
309 env: NodeJS.ProcessEnv,
310 ): Effect.fn.Return<
311 boolean,
312 never,
313 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
314 > {
315 if (!(yield* isCommandAvailable(command, { env }))) {
316 return false;
317 }
318 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
319 },
320);
321​
322// WSL hosts prefer the Windows Explorer bridge, but interop can exist without
323// `explorer.exe` on PATH (appendWindowsPath=false) or without a distro name
324// while WSLg still provides a working Linux file manager, so they keep the
325// `xdg-open` fallback instead of losing the editor entirely.
326const resolveUsableFileManagerCommand = Effect.fn(
327 "externalLauncher.resolveUsableFileManagerCommand",
328)(function* (
329 platform: NodeJS.Platform,
330 env: NodeJS.ProcessEnv,
331): Effect.fn.Return<
332 string | undefined,
333 never,
334 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
335> {
336 const command = fileManagerCommandForPlatform(platform, env);
337 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
338 return command;
339 }
340 if (
341 shouldUseWindowsHostFromWsl(platform, env) &&
342 hasGraphicalLinuxSession(env) &&
343 (yield* isUsableFileManagerCommand("xdg-open", env))
344 ) {
345 return "xdg-open";
346 }
347 return undefined;
348});
349​
350// Reveal on Windows and WSL runs through PowerShell (see
351// resolveFileManagerRevealLaunch), not the `explorer` command that gates the
352// file-manager editor itself, so the capability must probe the executables the
353// reveal actually spawns. Callers gate on file-manager availability first;
354// the Linux "files" kind relies on that gate for the directory-handler probe,
355// while the WSL fallback re-probes because its availability may have come
356// from the Explorer bridge instead.
357const fileManagerRevealKindForPlatform = Effect.fn(
358 "externalLauncher.fileManagerRevealKindForPlatform",
359)(function* (
360 platform: NodeJS.Platform,
361 env: NodeJS.ProcessEnv,
362): Effect.fn.Return<
363 FileManagerRevealKind | undefined,
364 never,
365 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
366> {
367 if (platform === "darwin") return "finder";
368 if (platform === "win32") {
369 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
370 ? "file-explorer"
371 : undefined;
372 }
373 if (shouldUseWindowsHostFromWsl(platform, env)) {
374 if (
375 env.WSL_DISTRO_NAME?.trim() &&
376 (yield* isCommandAvailable("explorer.exe", { env })) &&
377 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
378 ) {
379 return "file-explorer";
380 }
381 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
382 ? "files"
383 : undefined;
384 }
385 return hasGraphicalLinuxSession(env) ? "files" : undefined;
386});
387​
388function resolveWslFileManagerPath(target: string, distroName: string): string {
389 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
390 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
392​
393function buildBrowserLaunch(
394 target: string,
395 platform: NodeJS.Platform,
396 env: NodeJS.ProcessEnv = {},
397): ProcessLaunch {
398 if (platform === "darwin") {
399 return {
400 command: "open",
401 args: [target],
402 options: DETACHED_IGNORE_STDIO_OPTIONS,
403 };
404 }
405​
406 if (platform === "win32") {
407 return resolveWindowsBrowserLaunch(
408 target,
409 resolvePowerShellPath(env),
410 WINDOWS_POWERSHELL_DETACHED,
411 );
412 }
413​
414 if (shouldUseWindowsHostFromWsl(platform, env)) {
415 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
416 }
417​
418 return {
419 command: "xdg-open",
420 args: [target],
421 options: DETACHED_IGNORE_STDIO_OPTIONS,
422 };
424​
425const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
426 platform: NodeJS.Platform,
427 env: NodeJS.ProcessEnv,
428): Effect.fn.Return<
429 ReadonlyArray<EditorId>,
430 never,
431 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
432> {
433 const available: EditorId[] = [];
434​
435 for (const editor of EDITORS) {
436 if (editor.commands === null) {
437 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
438 available.push(editor.id);
439 }
440 continue;
441 }
442​
443 const command = yield* resolveEditorCommand(editor, env);
444 if (Option.isSome(command)) {
445 available.push(editor.id);
446 }
447 }
448​
449 return available;
450});
451​
452const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
453 target: string,
454) {
455 const platform = yield* HostProcess.Platform;
456 const env = yield* readBrowserLaunchEnv;
457 return buildBrowserLaunch(target, platform, env);
458});
459​
460const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
461 const platform = yield* HostProcess.Platform;
462 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
463 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
464});
465​
466const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
467 function* () {
468 const platform = yield* HostProcess.Platform;
469 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
470 return yield* fileManagerRevealKindForPlatform(platform, env);
471 },
472);
473​
474// Callers apply a timeout (`resolveAvailableEditorsForConfig`) and disconnect
475// mid-connect; neither may cancel a scan other connects are waiting on, or
476// throw away work a slow host (a busy server at startup, a long PATH) needs
477// more than one connect to finish. Expiry uses the monotonic clock
478// (Clock.monotonicTimeNanos), matching the command-resolution cache in
479// @t3tools/shared/shell, so a backward wall-clock adjustment cannot keep an
480// expired entry alive.
481const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
482​
483interface EditorDiscoveryCacheEntry {
484 readonly scan: Deferred.Deferred<ReadonlyArray<EditorId>>;
485 readonly expiresAtNanos: bigint | undefined;
487​
488export class ExternalLauncher extends Context.Service<
489 ExternalLauncher,
490 {
491 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
492 /**
493 * Only meaningful when `resolveAvailableEditors` includes "file-manager":
494 * on Linux that availability check also carries the directory-handler probe
495 * this capability relies on.
496 */
497 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
498 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
499 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
500 }
501>()("t3/process/externalLauncher") {}
502​
503const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
504 input: LaunchEditorInput,
505): Effect.fn.Return<
506 EditorLaunch,
507 ExternalLauncherError,
508 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
509> {
510 const platform = yield* HostProcess.Platform;
511 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
512 yield* Effect.annotateCurrentSpan({
513 "externalLauncher.editor": input.editor,
514 "externalLauncher.cwd": input.cwd,
515 "externalLauncher.platform": platform,
516 });
517 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
518 if (!editorDef) {
519 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
520 }
521​
522 if (editorDef.commands) {
523 const { command, baseArgs } = Option.getOrElse(
524 yield* resolveEditorCommand(editorDef, env),
525 () => ({
526 command: editorDef.commands[0],
527 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
528 }),
529 );
530 return {
531 editor: editorDef.id,
532 target: input.cwd,
533 command,
534 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
535 };
536 }
537​
538 if (editorDef.id !== "file-manager") {
539 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
540 }
541​
542 const command = yield* resolveUsableFileManagerCommand(platform, env);
543 if (command === undefined) {
544 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
545 }
546​
547 if (input.reveal === true) {
548 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
549 }
550​
551 return {
552 editor: editorDef.id,
553 target: input.cwd,
554 command,
555 args:
556 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
557 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
558 : platform === "win32"
559 ? // Explorer reads `/` as a switch, so `C:/repo` silently opens
560 // a default folder instead of the target.
561 [normalizeWindowsFileManagerPath(input.cwd)]
562 : [input.cwd],
563 };
564});
565​
566// A replacement manager registers a default Directory shell verb; stock Windows
567// uses "none". Explorer needs its /select argument passed verbatim through
568// PowerShell because Node's argument quoting changes how Explorer parses it.
569function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
570 const literal = escapePowerShellStringLiteral(target);
571 return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`;
573​
574function powerShellFileManagerLaunch(
575 target: string,
576 source: string,
577 powershellCommand: string,
578): EditorLaunch {
579 return {
580 editor: "file-manager",
581 target,
582 command: powershellCommand,
583 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
584 };
586​
587function normalizeWindowsFileManagerPath(target: string): string {
588 return target.replaceAll("/", "\\");
590​
591const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
592 target: string,
593 platform: NodeJS.Platform,
594 env: NodeJS.ProcessEnv,
595 command: string,
596): Effect.fn.Return<
597 EditorLaunch,
598 never,
599 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
600> {
601 if (platform === "darwin") {
602 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
603 }
604​
605 if (platform === "win32") {
606 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
607 const windowsTarget = normalizeWindowsFileManagerPath(target);
608 return {
609 ...powerShellFileManagerLaunch(
610 target,
611 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
612 resolvePowerShellPath(env),
613 ),
614 detached: WINDOWS_POWERSHELL_DETACHED,
615 };
616 }
617​
618 if (
619 command === "explorer.exe" &&
620 shouldUseWindowsHostFromWsl(platform, env) &&
621 env.WSL_DISTRO_NAME !== undefined
622 ) {
623 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
624 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
625 // WSL names may contain quotes that Explorer's /select cannot encode.
626 // Open the parent through the shell so replacement managers still apply.
627 const path = yield* Path.Path;
628 // .NET path parsing rejects characters that are legal in WSL filenames.
629 const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME);
630 const source = explorerTarget.includes('"')
631 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
632 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
633 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
634 }
635 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
636 const path = yield* Path.Path;
637 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
638 }
639 const path = yield* Path.Path;
640 return {
641 editor: "file-manager",
642 target,
643 command: "explorer.exe",
644 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
645 };
646 }
647​
648 const path = yield* Path.Path;
649 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
650});
651​
652const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
653 function* (target: string) {
654 const env = yield* readCommandLookupEnv;
655 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
656​
657 const path = yield* Path.Path;
658 const uri = yield* path.toFileUrl(target);
659 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
660 const exitCode = yield* spawner.exitCode(
661 ChildProcess.make(
662 "gdbus",
663 [
664 "call",
665 "--session",
666 "--dest",
667 "org.freedesktop.FileManager1",
668 "--object-path",
669 "/org/freedesktop/FileManager1",
670 "--method",
671 "org.freedesktop.FileManager1.ShowItems",
672 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
673 `["${uri.href}"]`,
674 "",
675 ],
676 {
677 stdin: "ignore",
678 stdout: "ignore",
679 stderr: "ignore",
680 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
681 forceKillAfter: "1 second",
682 },
683 ),
684 );
685 return exitCode === 0;
686 },
687 Effect.timeout("2 seconds"),
688 Effect.catchTags({
689 BadArgument: () => Effect.succeed(false),
690 PlatformError: () => Effect.succeed(false),
691 TimeoutError: () => Effect.succeed(false),
692 }),
693);
694​
695const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
696 input: LaunchEditorInput,
697) {
698 const launch = yield* resolveEditorLaunch(input);
699 if (
700 input.editor === "file-manager" &&
701 input.reveal === true &&
702 launch.command === "xdg-open" &&
703 (yield* HostProcess.Platform) === "linux" &&
704 (yield* tryRevealLinuxItem(launch.target))
705 ) {
706 return;
707 }
708 yield* launchEditorProcess(launch);
709});
710​
711const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
712 launch: ProcessLaunch,
713 onError: (cause: unknown) => ExternalLauncherError,
714): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
715 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
716 // The desktop app runs this server with ELECTRON_RUN_AS_NODE. A launched file
717 // manager or browser passes its environment on to everything started from it,
718 // so any Electron app opened from there would start as plain Node and exit.
719 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
720 const command = ChildProcess.make(launch.command, launch.args, {
721 ...launch.options,
722 env,
723 extendEnv: false,
724 });
725​
726 yield* spawner.spawn(command).pipe(
727 Effect.flatMap((handle) => handle.unref),
728 Effect.asVoid,
729 Effect.scoped,
730 Effect.mapError(onError),
731 );
732});
733​
734const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
735 target: string,
736): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
737 const launch = yield* resolveBrowserLaunch(target);
738 return yield* launchAndUnref(
739 launch,
740 (cause) =>
741 new ExternalLauncherBrowserSpawnError({
742 target,
743 command: launch.command,
744 args: launch.args,
745 cause,
746 }),
747 );
748});
749​
750const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
751 launch: EditorLaunch,
752): Effect.fn.Return<
753 void,
754 ExternalLauncherError,
755 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
756> {
757 const env = yield* readCommandLookupEnv;
758 if (!(yield* isCommandAvailable(launch.command, { env }))) {
759 return yield* new ExternalLauncherCommandNotFoundError({
760 editor: launch.editor,
761 command: launch.command,
762 });
763 }
764​
765 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
766 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
767 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
768 }
769 yield* launchAndUnref(
770 {
771 command: spawnCommand.command,
772 args: spawnCommand.args,
773 options: {
774 detached: launch.detached ?? true,
775 shell: spawnCommand.shell,
776 stdin: "ignore",
777 stdout: "ignore",
778 stderr: "ignore",
779 },
780 },
781 (cause) =>
782 new ExternalLauncherEditorSpawnError({
783 editor: launch.editor,
784 target: launch.target,
785 command: spawnCommand.command,
786 args: spawnCommand.args,
787 cause,
788 }),
789 );
790});
791​
792/** @public Service construction is part of the canonical Effect module API. */
793export const make = Effect.gen(function* () {
794 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
795 const fileSystem = yield* FileSystem.FileSystem;
796 const path = yield* Path.Path;
797​
798 const provideCommandResolutionServices = <A, E, R>(
799 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
800 ) =>
801 effect.pipe(
802 Effect.provideService(FileSystem.FileSystem, fileSystem),
803 Effect.provideService(Path.Path, path),
804 );
805​
806 const scope = yield* Scope.Scope;
807 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
808 Option.none(),
809 );
810 const runEditorDiscovery = (scan: Deferred.Deferred<ReadonlyArray<EditorId>>) =>
811 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
812 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
813 Effect.onExit((exit) =>
814 Effect.gen(function* () {
815 const expiresAtNanos =
816 (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS;
817 yield* Ref.update(editorDiscoveryCache, (current) =>
818 Option.isNone(current) || current.value.scan !== scan
819 ? current
820 : Exit.isSuccess(exit)
821 ? Option.some({ scan, expiresAtNanos })
822 : Option.none(),
823 );
824 yield* Deferred.done(scan, exit);
825 }),
826 ),
827 Effect.interruptible,
828 Effect.forkIn(scope),
829 );
830 // Claiming the cache entry and starting its scan must not be split by an
831 // interrupt, or the entry would wait on a scan that never runs.
832 const acquireEditorDiscovery = Effect.gen(function* () {
833 const nowNanos = yield* Clock.monotonicTimeNanos;
834 const [scan, isNewScan] = yield* Ref.modify(
835 editorDiscoveryCache,
836 (
837 current,
838 ): [
839 [EditorDiscoveryCacheEntry["scan"], boolean],
840 Option.Option<EditorDiscoveryCacheEntry>,
841 ] => {
842 if (
843 Option.isSome(current) &&
844 (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos)
845 ) {
846 return [[current.value.scan, false], current];
847 }
848 const scan = Deferred.makeUnsafe<ReadonlyArray<EditorId>>();
849 return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })];
850 },
851 );
852 if (isNewScan) {
853 yield* runEditorDiscovery(scan);
854 }
855 return scan;
856 }).pipe(Effect.uninterruptible);
857 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
858​
859 return ExternalLauncher.of({
860 resolveAvailableEditors: () => cachedAvailableEditors,
861 resolveFileManagerRevealKind: () =>
862 provideCommandResolutionServices(resolveFileManagerRevealKind()).pipe(
863 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
864 ),
865 launchBrowser: (target) =>
866 launchBrowser(target).pipe(
867 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
868 ),
869 launchEditor: (input) =>
870 provideCommandResolutionServices(launchEditor(input)).pipe(
871 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
872 ),
873 });
874});
875​
876export const layer = Layer.effect(ExternalLauncher, make);