Open History to see the last commit
1/**
2 * ExternalLauncher - external application launch service interface.
3 *
4 * Owns process launch helpers for browser URLs and workspace paths
5 * in configured editor integrations.
6 *
7 * @module ExternalLauncher
8 */
9import {
10 EDITORS,
11 ExternalLauncherError,
12 type EditorId,
13 type LaunchEditorInput,
14} from "@t3tools/contracts";
15import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
16import * as Context from "effect/Context";
17import * as Effect from "effect/Effect";
18import * as Encoding from "effect/Encoding";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
22
23// ==============================
24// Definitions
25// ==============================
26
27export { ExternalLauncherError };
28export type { LaunchEditorInput };
29export { isCommandAvailable } from "@t3tools/shared/shell";
30
31interface EditorLaunch {
32 readonly command: string;
33 readonly args: ReadonlyArray<string>;
34}
35
36interface ProcessLaunch {
37 readonly command: string;
38 readonly args: ReadonlyArray<string>;
39 readonly options: ChildProcess.CommandOptions;
40}
41
42interface TargetPathAndPosition {
43 readonly path: string;
44 readonly line: string;
45 readonly column: Option.Option<string>;
46}
47
48const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
49const POWERSHELL_ARGUMENTS_PREFIX = [
50 "-NoProfile",
51 "-NonInteractive",
52 "-ExecutionPolicy",
53 "Bypass",
54 "-EncodedCommand",
55] as const;
56
57const DETACHED_IGNORE_STDIO_OPTIONS = {
58 detached: true,
59 stdin: "ignore",
60 stdout: "ignore",
61 stderr: "ignore",
62} as const satisfies ChildProcess.CommandOptions;
63
64function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
65 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
66 if (!match?.[1] || !match[2]) {
67 return Option.none();
68 }
69
70 return Option.some({
71 path: match[1],
72 line: match[2],
73 column: Option.fromUndefinedOr(match[3]),
74 });
75}
76
77function resolveCommandEditorArgs(
78 editor: (typeof EDITORS)[number],
79 target: string,
80): ReadonlyArray<string> {
81 const parsedTarget = parseTargetPathAndPosition(target);
82
83 switch (editor.launchStyle) {
84 case "direct-path":
85 return [target];
86 case "goto":
87 return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
88 case "line-column":
89 return Option.match(parsedTarget, {
90 onNone: () => [target],
91 onSome: ({ path, line, column }) => [
92 "--line",
93 line,
94 ...Option.match(column, {
95 onNone: () => [],
96 onSome: (value) => ["--column", value],
97 }),
98 path,
99 ],
100 });
101 }
102}
103
104function resolveEditorArgs(
105 editor: (typeof EDITORS)[number],
106 target: string,
107): ReadonlyArray<string> {
108 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
109 return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
110}
111
112function resolveAvailableCommand(
113 commands: ReadonlyArray<string>,
114 options: CommandAvailabilityOptions = {},
115): Option.Option<string> {
116 for (const command of commands) {
117 if (isCommandAvailable(command, options)) {
118 return Option.some(command);
119 }
120 }
121 return Option.none();
122}
123
124function encodeUtf16LeBase64(input: string): string {
125 const bytes = new Uint8Array(input.length * 2);
126 for (let index = 0; index < input.length; index += 1) {
127 const code = input.charCodeAt(index);
128 bytes[index * 2] = code & 0xff;
129 bytes[index * 2 + 1] = code >>> 8;
130 }
131 return Encoding.encodeBase64(bytes);
132}
133
134function escapePowerShellStringLiteral(input: string): string {
135 return `'${input.replaceAll("'", "''")}'`;
136}
137
138function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
139 return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
140}
141
142function resolveWslPowerShellPath(): string {
143 return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
144}
145
146function shouldUseWindowsBrowserFromWsl(
147 platform: NodeJS.Platform,
148 env: NodeJS.ProcessEnv = process.env,
149): boolean {
150 return (
151 platform === "linux" &&
152 (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
153 env.SSH_CONNECTION === undefined &&
154 env.SSH_TTY === undefined &&
155 env.container === undefined
156 );
157}
158
159function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
160 const encodedCommand = encodeUtf16LeBase64(
161 `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
162 );
163 return {
164 command,
165 args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
166 options: {
167 detached: true,
168 shell: false,
169 stdin: "ignore",
170 stdout: "ignore",
171 stderr: "ignore",
172 },
173 };
174}
175
176function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
177 switch (platform) {
178 case "darwin":
179 return "open";
180 case "win32":
181 return "explorer";
182 default:
183 return "xdg-open";
184 }
185}
186
187export function resolveBrowserLaunch(
188 target: string,
189 platform: NodeJS.Platform = process.platform,
190 env: NodeJS.ProcessEnv = process.env,
191): ProcessLaunch {
192 if (platform === "darwin") {
193 return {
194 command: "open",
195 args: [target],
196 options: DETACHED_IGNORE_STDIO_OPTIONS,
197 };
198 }
199
200 if (platform === "win32") {
201 return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
202 }
203
204 if (shouldUseWindowsBrowserFromWsl(platform, env)) {
205 return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
206 }
207
208 return {
209 command: "xdg-open",
210 args: [target],
211 options: DETACHED_IGNORE_STDIO_OPTIONS,
212 };
213}
214
215export function resolveAvailableEditors(
216 platform: NodeJS.Platform = process.platform,
217 env: NodeJS.ProcessEnv = process.env,
218): ReadonlyArray<EditorId> {
219 const available: EditorId[] = [];
220
221 for (const editor of EDITORS) {
222 if (editor.commands === null) {
223 const command = fileManagerCommandForPlatform(platform);
224 if (isCommandAvailable(command, { platform, env })) {
225 available.push(editor.id);
226 }
227 continue;
228 }
229
230 const command = resolveAvailableCommand(editor.commands, { platform, env });
231 if (Option.isSome(command)) {
232 available.push(editor.id);
233 }
234 }
235
236 return available;
237}
238
239/**
240 * ExternalLauncherShape - Service API for browser and editor launch actions.
241 */
242export interface ExternalLauncherShape {
243 /**
244 * Launch a URL target in the default browser.
245 */
246 readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
247
248 /**
249 * Launch a workspace path in a selected editor integration.
250 *
251 * Launches the editor as a detached process so server startup is not blocked.
252 */
253 readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
254}
255
256/**
257 * ExternalLauncher - Service tag for browser/editor launch operations.
258 */
259export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
260 "t3/process/externalLauncher",
261) {}
262
263// ==============================
264// Implementations
265// ==============================
266
267export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
268 input: LaunchEditorInput,
269 platform: NodeJS.Platform = process.platform,
270 env: NodeJS.ProcessEnv = process.env,
271): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
272 yield* Effect.annotateCurrentSpan({
273 "externalLauncher.editor": input.editor,
274 "externalLauncher.cwd": input.cwd,
275 "externalLauncher.platform": platform,
276 });
277 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
278 if (!editorDef) {
279 return yield* new ExternalLauncherError({ message: `Unknown editor: ${input.editor}` });
280 }
281
282 if (editorDef.commands) {
283 const command = Option.getOrElse(
284 resolveAvailableCommand(editorDef.commands, { platform, env }),
285 () => editorDef.commands[0],
286 );
287 return {
288 command,
289 args: resolveEditorArgs(editorDef, input.cwd),
290 };
291 }
292
293 if (editorDef.id !== "file-manager") {
294 return yield* new ExternalLauncherError({ message: `Unsupported editor: ${input.editor}` });
295 }
296
297 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
298});
299
300const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
301 launch: ProcessLaunch,
302 errorMessage: string,
303): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
304 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
305 const command = ChildProcess.make(launch.command, launch.args, launch.options);
306
307 yield* spawner.spawn(command).pipe(
308 Effect.flatMap((handle) => handle.unref),
309 Effect.asVoid,
310 Effect.scoped,
311 Effect.mapError((cause) => new ExternalLauncherError({ message: errorMessage, cause })),
312 );
313});
314
315export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
316 target: string,
317): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
318 return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
319});
320
321export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
322 launch: EditorLaunch,
323): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
324 if (!isCommandAvailable(launch.command)) {
325 return yield* new ExternalLauncherError({
326 message: `Editor command not found: ${launch.command}`,
327 });
328 }
329
330 const isWin32 = process.platform === "win32";
331 yield* launchAndUnref(
332 {
333 command: launch.command,
334 args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
335 options: {
336 detached: true,
337 shell: isWin32,
338 stdin: "ignore",
339 stdout: "ignore",
340 stderr: "ignore",
341 },
342 },
343 "failed to spawn detached process",
344 );
345});
346
347const make = Effect.gen(function* () {
348 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
349
350 return {
351 launchBrowser: (target) =>
352 launchBrowser(target).pipe(
353 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
354 ),
355 launchEditor: (input) =>
356 Effect.flatMap(resolveEditorLaunch(input), (launch) =>
357 launchEditorProcess(launch).pipe(
358 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
359 ),
360 ),
361 } satisfies ExternalLauncherShape;
362});
363
364export const layer = Layer.effect(ExternalLauncher, make);