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

externalLauncher.ts

898 lines30.0 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 Schema from "effect/Schema";
35import * as Scope from "effect/Scope";
36import * as Stream from "effect/Stream";
37import * as ChildProcess from "effect/process/ChildProcess";
38import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
39​
40export {
41 ExternalLauncherError,
42 ExternalLauncherBrowserSpawnError,
43 ExternalLauncherCommandNotFoundError,
44 ExternalLauncherEditorSpawnError,
45 ExternalLauncherUnknownEditorError,
46 ExternalLauncherUnsupportedEditorError,
47 ExternalLauncherUnsupportedTargetError,
48} from "@t3tools/contracts";
49export type { LaunchEditorInput };
50interface EditorLaunch {
51 readonly editor: EditorId;
52 readonly target: string;
53 readonly command: string;
54 readonly args: ReadonlyArray<string>;
55 readonly detached?: boolean;
57​
58interface ProcessLaunch {
59 readonly command: string;
60 readonly args: ReadonlyArray<string>;
61 readonly options: ChildProcess.CommandOptions;
63​
64interface TargetPathAndPosition {
65 readonly path: string;
66 readonly line: string;
67 readonly column: Option.Option<string>;
69​
70// cmd shims reparse %* after escaping is gone; newlines and quotes can expose shell operators.
71const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/;
72const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
73const POWERSHELL_ARGUMENTS_PREFIX = [
74 "-NoProfile",
75 "-NonInteractive",
76 "-ExecutionPolicy",
77 "Bypass",
78 "-EncodedCommand",
79] as const;
80​
81// Detached Windows PowerShell exits 0 without executing; only WSL interop keeps detached launches.
82const WINDOWS_POWERSHELL_DETACHED = false;
83​
84const DETACHED_IGNORE_STDIO_OPTIONS = {
85 detached: true,
86 stdin: "ignore",
87 stdout: "ignore",
88 stderr: "ignore",
89} as const satisfies ChildProcess.CommandOptions;
90​
91const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
92 Object.fromEntries(
93 Object.entries(input).flatMap(([key, value]) =>
94 Option.match(value, {
95 onNone: () => [],
96 onSome: (resolved) => [[key, resolved]],
97 }),
98 ),
99 );
100​
101const BrowserLaunchEnvConfig = Config.all({
102 SYSTEMROOT: Config.String("SYSTEMROOT").pipe(Config.option),
103 windir: Config.String("windir").pipe(Config.option),
104 WSL_DISTRO_NAME: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
105 WSL_INTEROP: Config.String("WSL_INTEROP").pipe(Config.option),
106 SSH_CONNECTION: Config.String("SSH_CONNECTION").pipe(Config.option),
107 SSH_TTY: Config.String("SSH_TTY").pipe(Config.option),
108 container: Config.String("container").pipe(Config.option),
109 DISPLAY: Config.String("DISPLAY").pipe(Config.option),
110 WAYLAND_DISPLAY: Config.String("WAYLAND_DISPLAY").pipe(Config.option),
111}).pipe(Config.map(compactEnv));
112​
113const CommandLookupEnvConfig = Config.all({
114 PATH: Config.String("PATH").pipe(Config.option),
115 Path: Config.String("Path").pipe(Config.option),
116 path: Config.String("path").pipe(Config.option),
117 PATHEXT: Config.String("PATHEXT").pipe(Config.option),
118 HOME: Config.String("HOME").pipe(Config.option),
119 LOCALAPPDATA: Config.String("LOCALAPPDATA").pipe(Config.option),
120 ProgramFiles: Config.String("ProgramFiles").pipe(Config.option),
121 ProgramW6432: Config.String("ProgramW6432").pipe(Config.option),
122 XDG_DATA_HOME: Config.String("XDG_DATA_HOME").pipe(Config.option),
123 "ProgramFiles(x86)": Config.String("ProgramFiles(x86)").pipe(Config.option),
124}).pipe(Config.map(compactEnv));
125​
126const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
127const readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
128​
129function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
130 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
131 if (!match?.[1] || !match[2]) {
132 return Option.none();
133 }
134​
135 return Option.some({
136 path: match[1],
137 line: match[2],
138 column: Option.fromUndefinedOr(match[3]),
139 });
141​
142function resolveCommandEditorArgs(
143 editor: (typeof EDITORS)[number],
144 target: string,
145): ReadonlyArray<string> {
146 const parsedTarget = parseTargetPathAndPosition(target);
147​
148 switch (editor.launchStyle) {
149 case "direct-path":
150 return [target];
151 case "goto":
152 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
153 case "line-column":
154 return Option.match(parsedTarget, {
155 onNone: () => [target],
156 onSome: ({ path, line, column }) => [
157 "--line",
158 line,
159 // JetBrains IDEs count `--column` from 0; targets count columns from 1.
160 ...Option.match(column, {
161 onNone: () => [],
162 onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))],
163 }),
164 path,
165 ],
166 });
167 }
169​
170function encodeUtf16LeBase64(input: string): string {
171 const bytes = new Uint8Array(input.length * 2);
172 for (let index = 0; index < input.length; index += 1) {
173 const code = input.charCodeAt(index);
174 bytes[index * 2] = code & 0xff;
175 bytes[index * 2 + 1] = code >>> 8;
176 }
177 return Base64.encode(bytes);
179​
180function escapePowerShellStringLiteral(input: string): string {
181 return `'${input.replaceAll("'", "''")}'`;
183​
184function resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {
185 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
187​
188function resolveWslPowerShellPath(): string {
189 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
191​
192// WSL automount roots vary; resolve PowerShell via PATH to match launchEditor's availability check.
193const WSL_POWERSHELL_COMMAND = "powershell.exe";
194​
195function shouldUseWindowsHostFromWsl(
196 platform: NodeJS.Platform,
197 env: NodeJS.ProcessEnv = {},
198): boolean {
199 return (
200 platform === "linux" &&
201 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
202 env.SSH_CONNECTION === undefined &&
203 env.SSH_TTY === undefined &&
204 env.container === undefined
205 );
207​
208function resolveWindowsBrowserLaunch(
209 target: string,
210 command: string,
211 detached: boolean,
212): ProcessLaunch {
213 const encodedCommand = encodeUtf16LeBase64(
214 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
215 );
216 return {
217 command,
218 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
219 options: {
220 detached,
221 shell: false,
222 stdin: "ignore",
223 stdout: "ignore",
224 stderr: "ignore",
225 },
226 };
228​
229function hasGraphicalLinuxSession(env: NodeJS.ProcessEnv): boolean {
230 return [env.DISPLAY, env.WAYLAND_DISPLAY].some(
231 (value) => value !== undefined && value.trim().length > 0,
232 );
234​
235function fileManagerCommandForPlatform(
236 platform: NodeJS.Platform,
237 env: NodeJS.ProcessEnv,
238): string | undefined {
239 switch (platform) {
240 case "darwin":
241 return "open";
242 case "win32":
243 return "explorer";
244 default:
245 if (shouldUseWindowsHostFromWsl(platform, env)) {
246 return env.WSL_DISTRO_NAME?.trim() ? "explorer.exe" : undefined;
247 }
248 return hasGraphicalLinuxSession(env) ? "xdg-open" : undefined;
249 }
251​
252// xdg-open needs an inode/directory handler or detached launches silently fail.
253// Bound xdg-mime below discovery's timeout so a hung probe drops only the file manager.
254const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds";
255​
256const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")(
257 function* (
258 env: NodeJS.ProcessEnv,
259 ): Effect.fn.Return<
260 boolean,
261 never,
262 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
263 > {
264 if (!(yield* isCommandAvailable("xdg-mime", { env }))) {
265 return false;
266 }
267​
268 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
269 return yield* spawner
270 .spawn(
271 ChildProcess.make("xdg-mime", ["query", "default", "inode/directory"], {
272 stdin: "ignore",
273 stderr: "ignore",
274 }),
275 )
276 .pipe(
277 Effect.flatMap((handle) =>
278 Effect.all([handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], {
279 concurrency: "unbounded",
280 }),
281 ),
282 Effect.map(([stdout, exitCode]) => exitCode === 0 && stdout.trim().length > 0),
283 Effect.scoped,
284 Effect.timeout(LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT),
285 Effect.orElseSucceed(() => false),
286 );
287 },
288);
289​
290const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManagerCommand")(
291 function* (
292 command: string,
293 env: NodeJS.ProcessEnv,
294 ): Effect.fn.Return<
295 boolean,
296 never,
297 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
298 > {
299 if (!(yield* isCommandAvailable(command, { env }))) {
300 return false;
301 }
302 return command !== "xdg-open" || (yield* hasUsableLinuxDirectoryHandler(env));
303 },
304);
305​
306// WSL may lack Explorer on PATH or a distro name while WSLg still offers a Linux file manager.
307const resolveUsableFileManagerCommand = Effect.fn(
308 "externalLauncher.resolveUsableFileManagerCommand",
309)(function* (
310 platform: NodeJS.Platform,
311 env: NodeJS.ProcessEnv,
312): Effect.fn.Return<
313 string | undefined,
314 never,
315 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
316> {
317 const command = fileManagerCommandForPlatform(platform, env);
318 if (command !== undefined && (yield* isUsableFileManagerCommand(command, env))) {
319 return command;
320 }
321 if (
322 shouldUseWindowsHostFromWsl(platform, env) &&
323 hasGraphicalLinuxSession(env) &&
324 (yield* isUsableFileManagerCommand("xdg-open", env))
325 ) {
326 return "xdg-open";
327 }
328 return undefined;
329});
330​
331// Reveal uses PowerShell on Windows/WSL, so probe it separately from Explorer availability.
332// Linux relies on the file-manager gate's handler probe; WSL re-probes because the gate may use Explorer.
333const fileManagerRevealKindForPlatform = Effect.fn(
334 "externalLauncher.fileManagerRevealKindForPlatform",
335)(function* (
336 platform: NodeJS.Platform,
337 env: NodeJS.ProcessEnv,
338): Effect.fn.Return<
339 FileManagerRevealKind | undefined,
340 never,
341 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
342> {
343 if (platform === "darwin") return "finder";
344 if (platform === "win32") {
345 return (yield* isCommandAvailable(resolvePowerShellPath(env), { env }))
346 ? "file-explorer"
347 : undefined;
348 }
349 if (shouldUseWindowsHostFromWsl(platform, env)) {
350 if (
351 env.WSL_DISTRO_NAME?.trim() &&
352 (yield* isCommandAvailable("explorer.exe", { env })) &&
353 (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env }))
354 ) {
355 return "file-explorer";
356 }
357 return hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))
358 ? "files"
359 : undefined;
360 }
361 return hasGraphicalLinuxSession(env) ? "files" : undefined;
362});
363​
364function resolveWslFileManagerPath(target: string, distroName: string): string {
365 const relativePath = target.replace(/^\/+/, "").replaceAll("/", "\\");
366 return `\\\\wsl.localhost\\${distroName}${relativePath.length > 0 ? `\\${relativePath}` : ""}`;
368​
369function buildBrowserLaunch(
370 target: string,
371 platform: NodeJS.Platform,
372 env: NodeJS.ProcessEnv = {},
373): ProcessLaunch {
374 if (platform === "darwin") {
375 return {
376 command: "open",
377 args: [target],
378 options: DETACHED_IGNORE_STDIO_OPTIONS,
379 };
380 }
381​
382 if (platform === "win32") {
383 return resolveWindowsBrowserLaunch(
384 target,
385 resolvePowerShellPath(env),
386 WINDOWS_POWERSHELL_DETACHED,
387 );
388 }
389​
390 if (shouldUseWindowsHostFromWsl(platform, env)) {
391 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true);
392 }
393​
394 return {
395 command: "xdg-open",
396 args: [target],
397 options: DETACHED_IGNORE_STDIO_OPTIONS,
398 };
400​
401const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors")(function* (
402 platform: NodeJS.Platform,
403 env: NodeJS.ProcessEnv,
404): Effect.fn.Return<
405 ReadonlyArray<EditorId>,
406 never,
407 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
408> {
409 const available: EditorId[] = [];
410​
411 for (const editor of EDITORS) {
412 if (editor.commands === null) {
413 if ((yield* resolveUsableFileManagerCommand(platform, env)) !== undefined) {
414 available.push(editor.id);
415 }
416 continue;
417 }
418​
419 const command = yield* resolveEditorCommand(editor, env);
420 if (Option.isSome(command)) {
421 available.push(editor.id);
422 }
423 }
424​
425 return available;
426});
427​
428const resolveBrowserLaunch = Effect.fn("externalLauncher.resolveBrowserLaunch")(function* (
429 target: string,
430) {
431 const platform = yield* HostProcess.Platform;
432 const env = yield* readBrowserLaunchEnv;
433 return buildBrowserLaunch(target, platform, env);
434});
435​
436const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () {
437 const platform = yield* HostProcess.Platform;
438 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
439 return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings);
440});
441​
442const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")(
443 function* () {
444 const platform = yield* HostProcess.Platform;
445 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
446 return yield* fileManagerRevealKindForPlatform(platform, env);
447 },
448);
449​
450// Shared scans must survive caller timeouts/disconnects; monotonic expiry prevents clock rollback extending stale entries.
451const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
452​
453interface EditorDiscoveryCacheEntry {
454 readonly scan: Deferred.Deferred<ReadonlyArray<EditorId>>;
455 readonly expiresAtNanos: bigint | undefined;
457​
458export class ExternalLauncher extends Context.Service<
459 ExternalLauncher,
460 {
461 readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;
462 /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */
463 readonly resolveFileManagerRevealKind: () => Effect.Effect<FileManagerRevealKind | undefined>;
464 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
465 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
466 }
467>()("t3/process/externalLauncher") {}
468​
469const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
470 input: LaunchEditorInput,
471): Effect.fn.Return<
472 EditorLaunch,
473 ExternalLauncherError,
474 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
475> {
476 const platform = yield* HostProcess.Platform;
477 const env = { ...(yield* readBrowserLaunchEnv), ...(yield* readCommandLookupEnv) };
478 yield* Effect.annotateCurrentSpan({
479 "externalLauncher.editor": input.editor,
480 "externalLauncher.cwd": input.cwd,
481 "externalLauncher.platform": platform,
482 });
483 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
484 if (!editorDef) {
485 return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });
486 }
487​
488 if (editorDef.commands) {
489 const { command, baseArgs } = Option.getOrElse(
490 yield* resolveEditorCommand(editorDef, env),
491 () => ({
492 command: editorDef.commands[0],
493 baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [],
494 }),
495 );
496 return {
497 editor: editorDef.id,
498 target: input.cwd,
499 command,
500 args: [...baseArgs, ...resolveCommandEditorArgs(editorDef, input.cwd)],
501 };
502 }
503​
504 if (editorDef.id !== "file-manager") {
505 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
506 }
507​
508 const command = yield* resolveUsableFileManagerCommand(platform, env);
509 if (command === undefined) {
510 return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
511 }
512​
513 if (input.reveal === true) {
514 return yield* resolveFileManagerRevealLaunch(input.cwd, platform, env, command);
515 }
516​
517 return {
518 editor: editorDef.id,
519 target: input.cwd,
520 command,
521 args:
522 command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined
523 ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)]
524 : platform === "win32"
525 ? // Explorer interprets / as a switch and silently opens a fallback folder.
526 [normalizeWindowsFileManagerPath(input.cwd)]
527 : [input.cwd],
528 };
529});
530​
531// A replacement manager registers a default Directory shell verb; stock Windows
532// uses "none". Explorer needs its /select argument passed verbatim through
533// PowerShell because Node's argument quoting changes how Explorer parses it.
534function buildFileManagerRevealPowerShellSource(target: string, parent: string): string {
535 const literal = escapePowerShellStringLiteral(target);
536 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} + '"') }`;
538​
539function powerShellFileManagerLaunch(
540 target: string,
541 source: string,
542 powershellCommand: string,
543): EditorLaunch {
544 return {
545 editor: "file-manager",
546 target,
547 command: powershellCommand,
548 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)],
549 };
551​
552function normalizeWindowsFileManagerPath(target: string): string {
553 return target.replaceAll("/", "\\");
555​
556const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch")(function* (
557 target: string,
558 platform: NodeJS.Platform,
559 env: NodeJS.ProcessEnv,
560 command: string,
561): Effect.fn.Return<
562 EditorLaunch,
563 never,
564 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
565> {
566 if (platform === "darwin") {
567 return { editor: "file-manager", target, command: "open", args: ["-R", target] };
568 }
569​
570 if (platform === "win32") {
571 const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32));
572 const windowsTarget = normalizeWindowsFileManagerPath(target);
573 return {
574 ...powerShellFileManagerLaunch(
575 target,
576 buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)),
577 resolvePowerShellPath(env),
578 ),
579 detached: WINDOWS_POWERSHELL_DETACHED,
580 };
581 }
582​
583 if (
584 command === "explorer.exe" &&
585 shouldUseWindowsHostFromWsl(platform, env) &&
586 env.WSL_DISTRO_NAME !== undefined
587 ) {
588 const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME);
589 if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) {
590 // WSL names may contain quotes that Explorer's /select cannot encode.
591 // Open the parent through the shell so replacement managers still apply.
592 const path = yield* Path.Path;
593 // .NET path parsing rejects characters that are legal in WSL filenames.
594 const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME);
595 const source = explorerTarget.includes('"')
596 ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}`
597 : buildFileManagerRevealPowerShellSource(explorerTarget, parent);
598 return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND);
599 }
600 if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) {
601 const path = yield* Path.Path;
602 return { editor: "file-manager", target, command: "xdg-open", args: [path.dirname(target)] };
603 }
604 const path = yield* Path.Path;
605 return {
606 editor: "file-manager",
607 target,
608 command: "explorer.exe",
609 args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)],
610 };
611 }
612​
613 const path = yield* Path.Path;
614 return { editor: "file-manager", target, command, args: [path.dirname(target)] };
615});
616​
617const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")(
618 function* (target: string) {
619 const env = yield* readCommandLookupEnv;
620 if (!(yield* isCommandAvailable("gdbus", { env }))) return false;
621​
622 const path = yield* Path.Path;
623 const uri = yield* path.toFileUrl(target);
624 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
625 const exitCode = yield* spawner.exitCode(
626 ChildProcess.make(
627 "gdbus",
628 [
629 "call",
630 "--session",
631 "--dest",
632 "org.freedesktop.FileManager1",
633 "--object-path",
634 "/org/freedesktop/FileManager1",
635 "--method",
636 "org.freedesktop.FileManager1.ShowItems",
637 // File URLs percent-encode the double quotes and backslashes GVariant would interpret.
638 `["${uri.href}"]`,
639 "",
640 ],
641 {
642 stdin: "ignore",
643 stdout: "ignore",
644 stderr: "ignore",
645 // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM.
646 forceKillAfter: "1 second",
647 },
648 ),
649 );
650 return exitCode === 0;
651 },
652 Effect.timeout("2 seconds"),
653 Effect.catchTags({
654 BadArgument: () => Effect.succeed(false),
655 PlatformError: () => Effect.succeed(false),
656 TimeoutError: () => Effect.succeed(false),
657 }),
658);
659​
660const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* (
661 input: LaunchEditorInput,
662) {
663 const launch = yield* resolveEditorLaunch(input);
664 if (
665 input.editor === "file-manager" &&
666 input.reveal === true &&
667 launch.command === "xdg-open" &&
668 (yield* HostProcess.Platform) === "linux" &&
669 (yield* tryRevealLinuxItem(launch.target))
670 ) {
671 return;
672 }
673 yield* launchEditorProcess(launch);
674});
675​
676const GRAPHICAL_SESSION_ENV_KEYS: ReadonlySet<string> = new Set([
677 "DISPLAY",
678 "WAYLAND_DISPLAY",
679 "XAUTHORITY",
680]);
681​
682// The user manager's environment over D-Bus. `systemctl show-environment` would
683// shell-quote values with spaces as $'...', while this JSON carries them raw.
684const decodeManagerEnvironment = Schema.decodeUnknownEffect(
685 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
686);
687​
688// Boot services miss the desktop environment imported later into the systemd user manager.
689const readGraphicalSessionEnv = Effect.fn("externalLauncher.readGraphicalSessionEnv")(
690 function* () {
691 const hostEnv = yield* HostProcess.Environment;
692 if ((yield* HostProcess.Platform) !== "linux" || hasGraphicalLinuxSession(hostEnv)) {
693 return {};
694 }
695 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
696 const output = yield* spawner.string(
697 ChildProcess.make(
698 "busctl",
699 [
700 "--user",
701 "--json=short",
702 "get-property",
703 "org.freedesktop.systemd1",
704 "/org/freedesktop/systemd1",
705 "org.freedesktop.systemd1.Manager",
706 "Environment",
707 ],
708 { stdin: "ignore", stderr: "ignore" },
709 ),
710 );
711 const { data } = yield* decodeManagerEnvironment(output);
712 return Object.fromEntries(
713 data.flatMap((line) => {
714 const separator = line.indexOf("=");
715 const key = line.slice(0, separator);
716 return separator > 0 && GRAPHICAL_SESSION_ENV_KEYS.has(key)
717 ? [[key, line.slice(separator + 1)]]
718 : [];
719 }),
720 );
721 },
722 Effect.timeout("2 seconds"),
723 Effect.orElseSucceed((): NodeJS.ProcessEnv => ({})),
724);
725​
726const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
727 launch: ProcessLaunch,
728 onError: (cause: unknown) => ExternalLauncherError,
729): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
730 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
731 // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit.
732 const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment;
733 const command = ChildProcess.make(launch.command, launch.args, {
734 ...launch.options,
735 env: { ...env, ...launch.options.env },
736 extendEnv: false,
737 });
738​
739 yield* spawner.spawn(command).pipe(
740 Effect.flatMap((handle) => handle.unref),
741 Effect.asVoid,
742 Effect.scoped,
743 Effect.mapError(onError),
744 );
745});
746​
747const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
748 target: string,
749): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
750 const launch = yield* resolveBrowserLaunch(target);
751 return yield* launchAndUnref(
752 launch,
753 (cause) =>
754 new ExternalLauncherBrowserSpawnError({
755 target,
756 command: launch.command,
757 args: launch.args,
758 cause,
759 }),
760 );
761});
762​
763const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
764 launch: EditorLaunch,
765): Effect.fn.Return<
766 void,
767 ExternalLauncherError,
768 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
769> {
770 const env = yield* readCommandLookupEnv;
771 if (!(yield* isCommandAvailable(launch.command, { env }))) {
772 return yield* new ExternalLauncherCommandNotFoundError({
773 editor: launch.editor,
774 command: launch.command,
775 });
776 }
777​
778 const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });
779 if (spawnCommand.shell && launch.args.some((arg) => WINDOWS_SHIM_UNSAFE_ARG_PATTERN.test(arg))) {
780 return yield* new ExternalLauncherUnsupportedTargetError({ editor: launch.editor });
781 }
782 yield* launchAndUnref(
783 {
784 command: spawnCommand.command,
785 args: spawnCommand.args,
786 options: {
787 detached: launch.detached ?? true,
788 shell: spawnCommand.shell,
789 env: yield* readGraphicalSessionEnv(),
790 stdin: "ignore",
791 stdout: "ignore",
792 stderr: "ignore",
793 },
794 },
795 (cause) =>
796 new ExternalLauncherEditorSpawnError({
797 editor: launch.editor,
798 target: launch.target,
799 command: spawnCommand.command,
800 args: spawnCommand.args,
801 cause,
802 }),
803 );
804});
805​
806/** @public */
807export const make = Effect.gen(function* () {
808 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
809 const fileSystem = yield* FileSystem.FileSystem;
810 const path = yield* Path.Path;
811​
812 const provideCommandResolutionServices = <A, E, R>(
813 effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
814 ) =>
815 effect.pipe(
816 Effect.provideService(FileSystem.FileSystem, fileSystem),
817 Effect.provideService(Path.Path, path),
818 );
819​
820 const scope = yield* Scope.Scope;
821 const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
822 Option.none(),
823 );
824 const runEditorDiscovery = (scan: Deferred.Deferred<ReadonlyArray<EditorId>>) =>
825 provideCommandResolutionServices(resolveAvailableEditors()).pipe(
826 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
827 Effect.onExit((exit) =>
828 Effect.gen(function* () {
829 const expiresAtNanos =
830 (yield* Clock.monotonicTimeNanos) + EDITOR_DISCOVERY_CACHE_TTL_NANOS;
831 yield* Ref.update(editorDiscoveryCache, (current) =>
832 Option.isNone(current) || current.value.scan !== scan
833 ? current
834 : Exit.isSuccess(exit)
835 ? Option.some({ scan, expiresAtNanos })
836 : Option.none(),
837 );
838 yield* Deferred.done(scan, exit);
839 }),
840 ),
841 Effect.interruptible,
842 Effect.forkIn(scope),
843 );
844 // Claim and start atomically; interruption between them would leave an entry waiting on no scan.
845 const acquireEditorDiscovery = Effect.gen(function* () {
846 const nowNanos = yield* Clock.monotonicTimeNanos;
847 const [scan, isNewScan] = yield* Ref.modify(
848 editorDiscoveryCache,
849 (
850 current,
851 ): [
852 [EditorDiscoveryCacheEntry["scan"], boolean],
853 Option.Option<EditorDiscoveryCacheEntry>,
854 ] => {
855 if (
856 Option.isSome(current) &&
857 (current.value.expiresAtNanos === undefined || current.value.expiresAtNanos > nowNanos)
858 ) {
859 return [[current.value.scan, false], current];
860 }
861 const scan = Deferred.makeUnsafe<ReadonlyArray<EditorId>>();
862 return [[scan, true], Option.some({ scan, expiresAtNanos: undefined })];
863 },
864 );
865 if (isNewScan) {
866 yield* runEditorDiscovery(scan);
867 }
868 return scan;
869 }).pipe(Effect.uninterruptible);
870 const cachedAvailableEditors = Effect.flatMap(acquireEditorDiscovery, Deferred.await);
871​
872 // Forwarders retain the underlying launcher and discovery spans.
873 return ExternalLauncher.of({
874 resolveAvailableEditors: Effect.fnUntraced(function* () {
875 return yield* cachedAvailableEditors;
876 }),
877 resolveFileManagerRevealKind: Effect.fnUntraced(
878 function* () {
879 return yield* provideCommandResolutionServices(resolveFileManagerRevealKind());
880 },
881 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
882 ),
883 launchBrowser: Effect.fnUntraced(
884 function* (target) {
885 return yield* launchBrowser(target);
886 },
887 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
888 ),
889 launchEditor: Effect.fnUntraced(
890 function* (input) {
891 return yield* provideCommandResolutionServices(launchEditor(input));
892 },
893 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
894 ),
895 });
896});
897​
898export const layer = Layer.effect(ExternalLauncher, make);