Open History to see the last commit
1/**
2 * Open - Browser/editor launch service interface.
3 *
4 * Owns process launch helpers for opening URLs in a browser and workspace
5 * paths in a configured editor.
6 *
7 * @module Open
8 */
9import { spawn } from "node:child_process";
10import { accessSync, constants, statSync } from "node:fs";
11import { extname, join } from "node:path";
12
13import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
14import { Context, Effect, Layer } from "effect";
15
16// ==============================
17// Definitions
18// ==============================
19
20export { OpenError };
21
22export interface OpenInEditorInput {
23 readonly cwd: string;
24 readonly editor: EditorId;
25}
26
27interface EditorLaunch {
28 readonly command: string;
29 readonly args: ReadonlyArray<string>;
30}
31
32interface CommandAvailabilityOptions {
33 readonly platform?: NodeJS.Platform;
34 readonly env?: NodeJS.ProcessEnv;
35}
36
37const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
38
39function parseTargetPathAndPosition(target: string): {
40 path: string;
41 line: string | undefined;
42 column: string | undefined;
43} | null {
44 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
45 if (!match?.[1] || !match[2]) {
46 return null;
47 }
48
49 return {
50 path: match[1],
51 line: match[2],
52 column: match[3],
53 };
54}
55
56function resolveCommandEditorArgs(
57 editor: (typeof EDITORS)[number],
58 target: string,
59): ReadonlyArray<string> {
60 const parsedTarget = parseTargetPathAndPosition(target);
61
62 switch (editor.launchStyle) {
63 case "direct-path":
64 return [target];
65 case "goto":
66 return parsedTarget ? ["--goto", target] : [target];
67 case "line-column": {
68 if (!parsedTarget) {
69 return [target];
70 }
71
72 const { path, line, column } = parsedTarget;
73 return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
74 }
75 }
76}
77
78function resolveEditorArgs(
79 editor: (typeof EDITORS)[number],
80 target: string,
81): ReadonlyArray<string> {
82 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
83 return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
84}
85
86function resolveAvailableCommand(
87 commands: ReadonlyArray<string>,
88 options: CommandAvailabilityOptions = {},
89): string | null {
90 for (const command of commands) {
91 if (isCommandAvailable(command, options)) {
92 return command;
93 }
94 }
95 return null;
96}
97
98function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
99 switch (platform) {
100 case "darwin":
101 return "open";
102 case "win32":
103 return "explorer";
104 default:
105 return "xdg-open";
106 }
107}
108
109function stripWrappingQuotes(value: string): string {
110 return value.replace(/^"+|"+$/g, "");
111}
112
113function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
114 return env.PATH ?? env.Path ?? env.path ?? "";
115}
116
117function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
118 const rawValue = env.PATHEXT;
119 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
120 if (!rawValue) return fallback;
121
122 const parsed = rawValue
123 .split(";")
124 .map((entry) => entry.trim())
125 .filter((entry) => entry.length > 0)
126 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
127 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
128}
129
130function resolveCommandCandidates(
131 command: string,
132 platform: NodeJS.Platform,
133 windowsPathExtensions: ReadonlyArray<string>,
134): ReadonlyArray<string> {
135 if (platform !== "win32") return [command];
136 const extension = extname(command);
137 const normalizedExtension = extension.toUpperCase();
138
139 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
140 const commandWithoutExtension = command.slice(0, -extension.length);
141 return Array.from(
142 new Set([
143 command,
144 `${commandWithoutExtension}${normalizedExtension}`,
145 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
146 ]),
147 );
148 }
149
150 const candidates: string[] = [];
151 for (const extension of windowsPathExtensions) {
152 candidates.push(`${command}${extension}`);
153 candidates.push(`${command}${extension.toLowerCase()}`);
154 }
155 return Array.from(new Set(candidates));
156}
157
158function isExecutableFile(
159 filePath: string,
160 platform: NodeJS.Platform,
161 windowsPathExtensions: ReadonlyArray<string>,
162): boolean {
163 try {
164 const stat = statSync(filePath);
165 if (!stat.isFile()) return false;
166 if (platform === "win32") {
167 const extension = extname(filePath);
168 if (extension.length === 0) return false;
169 return windowsPathExtensions.includes(extension.toUpperCase());
170 }
171 accessSync(filePath, constants.X_OK);
172 return true;
173 } catch {
174 return false;
175 }
176}
177
178function resolvePathDelimiter(platform: NodeJS.Platform): string {
179 return platform === "win32" ? ";" : ":";
180}
181
182export function isCommandAvailable(
183 command: string,
184 options: CommandAvailabilityOptions = {},
185): boolean {
186 const platform = options.platform ?? process.platform;
187 const env = options.env ?? process.env;
188 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
189 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
190
191 if (command.includes("/") || command.includes("\\")) {
192 return commandCandidates.some((candidate) =>
193 isExecutableFile(candidate, platform, windowsPathExtensions),
194 );
195 }
196
197 const pathValue = resolvePathEnvironmentVariable(env);
198 if (pathValue.length === 0) return false;
199 const pathEntries = pathValue
200 .split(resolvePathDelimiter(platform))
201 .map((entry) => stripWrappingQuotes(entry.trim()))
202 .filter((entry) => entry.length > 0);
203
204 for (const pathEntry of pathEntries) {
205 for (const candidate of commandCandidates) {
206 if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
207 return true;
208 }
209 }
210 }
211 return false;
212}
213
214export function resolveAvailableEditors(
215 platform: NodeJS.Platform = process.platform,
216 env: NodeJS.ProcessEnv = process.env,
217): ReadonlyArray<EditorId> {
218 const available: EditorId[] = [];
219
220 for (const editor of EDITORS) {
221 if (editor.commands === null) {
222 const command = fileManagerCommandForPlatform(platform);
223 if (isCommandAvailable(command, { platform, env })) {
224 available.push(editor.id);
225 }
226 continue;
227 }
228
229 const command = resolveAvailableCommand(editor.commands, { platform, env });
230 if (command !== null) {
231 available.push(editor.id);
232 }
233 }
234
235 return available;
236}
237
238/**
239 * OpenShape - Service API for browser and editor launch actions.
240 */
241export interface OpenShape {
242 /**
243 * Open a URL target in the default browser.
244 */
245 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
246
247 /**
248 * Open a workspace path in a selected editor integration.
249 *
250 * Launches the editor as a detached process so server startup is not blocked.
251 */
252 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
253}
254
255/**
256 * Open - Service tag for browser/editor launch operations.
257 */
258export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
259
260// ==============================
261// Implementations
262// ==============================
263
264export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
265 input: OpenInEditorInput,
266 platform: NodeJS.Platform = process.platform,
267 env: NodeJS.ProcessEnv = process.env,
268): Effect.fn.Return<EditorLaunch, OpenError> {
269 yield* Effect.annotateCurrentSpan({
270 "open.editor": input.editor,
271 "open.cwd": input.cwd,
272 "open.platform": platform,
273 });
274 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
275 if (!editorDef) {
276 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
277 }
278
279 if (editorDef.commands) {
280 const command =
281 resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
282 return {
283 command,
284 args: resolveEditorArgs(editorDef, input.cwd),
285 };
286 }
287
288 if (editorDef.id !== "file-manager") {
289 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
290 }
291
292 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
293});
294
295export const launchDetached = (launch: EditorLaunch) =>
296 Effect.gen(function* () {
297 if (!isCommandAvailable(launch.command)) {
298 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
299 }
300
301 yield* Effect.callback<void, OpenError>((resume) => {
302 let child;
303 try {
304 const isWin32 = process.platform === "win32";
305 child = spawn(
306 launch.command,
307 isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
308 {
309 detached: true,
310 stdio: "ignore",
311 shell: isWin32,
312 },
313 );
314 } catch (error) {
315 return resume(
316 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
317 );
318 }
319
320 const handleSpawn = () => {
321 child.unref();
322 resume(Effect.void);
323 };
324
325 child.once("spawn", handleSpawn);
326 child.once("error", (cause) =>
327 resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
328 );
329 });
330 });
331
332const make = Effect.gen(function* () {
333 const open = yield* Effect.tryPromise({
334 try: () => import("open"),
335 catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
336 });
337
338 return {
339 openBrowser: (target) =>
340 Effect.tryPromise({
341 try: () => open.default(target),
342 catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
343 }),
344 openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
345 } satisfies OpenShape;
346});
347
348export const OpenLive = Layer.effect(Open, make);