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 { ServiceMap, 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 LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
38
39function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
40 return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
41}
42
43function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
44 switch (platform) {
45 case "darwin":
46 return "open";
47 case "win32":
48 return "explorer";
49 default:
50 return "xdg-open";
51 }
52}
53
54function stripWrappingQuotes(value: string): string {
55 return value.replace(/^"+|"+$/g, "");
56}
57
58function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
59 return env.PATH ?? env.Path ?? env.path ?? "";
60}
61
62function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
63 const rawValue = env.PATHEXT;
64 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
65 if (!rawValue) return fallback;
66
67 const parsed = rawValue
68 .split(";")
69 .map((entry) => entry.trim())
70 .filter((entry) => entry.length > 0)
71 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
72 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
73}
74
75function resolveCommandCandidates(
76 command: string,
77 platform: NodeJS.Platform,
78 windowsPathExtensions: ReadonlyArray<string>,
79): ReadonlyArray<string> {
80 if (platform !== "win32") return [command];
81 const extension = extname(command);
82 const normalizedExtension = extension.toUpperCase();
83
84 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
85 const commandWithoutExtension = command.slice(0, -extension.length);
86 return Array.from(
87 new Set([
88 command,
89 `${commandWithoutExtension}${normalizedExtension}`,
90 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
91 ]),
92 );
93 }
94
95 const candidates: string[] = [];
96 for (const extension of windowsPathExtensions) {
97 candidates.push(`${command}${extension}`);
98 candidates.push(`${command}${extension.toLowerCase()}`);
99 }
100 return Array.from(new Set(candidates));
101}
102
103function isExecutableFile(
104 filePath: string,
105 platform: NodeJS.Platform,
106 windowsPathExtensions: ReadonlyArray<string>,
107): boolean {
108 try {
109 const stat = statSync(filePath);
110 if (!stat.isFile()) return false;
111 if (platform === "win32") {
112 const extension = extname(filePath);
113 if (extension.length === 0) return false;
114 return windowsPathExtensions.includes(extension.toUpperCase());
115 }
116 accessSync(filePath, constants.X_OK);
117 return true;
118 } catch {
119 return false;
120 }
121}
122
123function resolvePathDelimiter(platform: NodeJS.Platform): string {
124 return platform === "win32" ? ";" : ":";
125}
126
127export function isCommandAvailable(
128 command: string,
129 options: CommandAvailabilityOptions = {},
130): boolean {
131 const platform = options.platform ?? process.platform;
132 const env = options.env ?? process.env;
133 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
134 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
135
136 if (command.includes("/") || command.includes("\\")) {
137 return commandCandidates.some((candidate) =>
138 isExecutableFile(candidate, platform, windowsPathExtensions),
139 );
140 }
141
142 const pathValue = resolvePathEnvironmentVariable(env);
143 if (pathValue.length === 0) return false;
144 const pathEntries = pathValue
145 .split(resolvePathDelimiter(platform))
146 .map((entry) => stripWrappingQuotes(entry.trim()))
147 .filter((entry) => entry.length > 0);
148
149 for (const pathEntry of pathEntries) {
150 for (const candidate of commandCandidates) {
151 if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
152 return true;
153 }
154 }
155 }
156 return false;
157}
158
159export function resolveAvailableEditors(
160 platform: NodeJS.Platform = process.platform,
161 env: NodeJS.ProcessEnv = process.env,
162): ReadonlyArray<EditorId> {
163 const available: EditorId[] = [];
164
165 for (const editor of EDITORS) {
166 const command = editor.command ?? fileManagerCommandForPlatform(platform);
167 if (isCommandAvailable(command, { platform, env })) {
168 available.push(editor.id);
169 }
170 }
171
172 return available;
173}
174
175/**
176 * OpenShape - Service API for browser and editor launch actions.
177 */
178export interface OpenShape {
179 /**
180 * Open a URL target in the default browser.
181 */
182 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
183
184 /**
185 * Open a workspace path in a selected editor integration.
186 *
187 * Launches the editor as a detached process so server startup is not blocked.
188 */
189 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
190}
191
192/**
193 * Open - Service tag for browser/editor launch operations.
194 */
195export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
196
197// ==============================
198// Implementations
199// ==============================
200
201export const resolveEditorLaunch = Effect.fnUntraced(function* (
202 input: OpenInEditorInput,
203 platform: NodeJS.Platform = process.platform,
204): Effect.fn.Return<EditorLaunch, OpenError> {
205 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
206 if (!editorDef) {
207 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
208 }
209
210 if (editorDef.command) {
211 return shouldUseGotoFlag(editorDef, input.cwd)
212 ? { command: editorDef.command, args: ["--goto", input.cwd] }
213 : { command: editorDef.command, args: [input.cwd] };
214 }
215
216 if (editorDef.id !== "file-manager") {
217 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
218 }
219
220 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
221});
222
223export const launchDetached = (launch: EditorLaunch) =>
224 Effect.gen(function* () {
225 if (!isCommandAvailable(launch.command)) {
226 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
227 }
228
229 yield* Effect.callback<void, OpenError>((resume) => {
230 let child;
231 try {
232 child = spawn(launch.command, [...launch.args], {
233 detached: true,
234 stdio: "ignore",
235 shell: process.platform === "win32",
236 });
237 } catch (error) {
238 return resume(
239 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
240 );
241 }
242
243 const handleSpawn = () => {
244 child.unref();
245 resume(Effect.void);
246 };
247
248 child.once("spawn", handleSpawn);
249 child.once("error", (cause) =>
250 resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
251 );
252 });
253 });
254
255const make = Effect.gen(function* () {
256 const open = yield* Effect.tryPromise({
257 try: () => import("open"),
258 catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
259 });
260
261 return {
262 openBrowser: (target) =>
263 Effect.tryPromise({
264 try: () => open.default(target),
265 catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
266 }),
267 openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
268 } satisfies OpenShape;
269});
270
271export const OpenLive = Layer.effect(Open, make);