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

externalLauncher.ts

849 lines28.2 KB

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