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";
10
11import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
12import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
13import { Context, Effect, Layer } from "effect";
14
15// ==============================
16// Definitions
17// ==============================
18
19export { OpenError };
20export { isCommandAvailable } from "@t3tools/shared/shell";
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
32const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
33
34function parseTargetPathAndPosition(target: string): {
35 path: string;
36 line: string | undefined;
37 column: string | undefined;
38} | null {
39 const match = TARGET_WITH_POSITION_PATTERN.exec(target);
40 if (!match?.[1] || !match[2]) {
41 return null;
42 }
43
44 return {
45 path: match[1],
46 line: match[2],
47 column: match[3],
48 };
49}
50
51function resolveCommandEditorArgs(
52 editor: (typeof EDITORS)[number],
53 target: string,
54): ReadonlyArray<string> {
55 const parsedTarget = parseTargetPathAndPosition(target);
56
57 switch (editor.launchStyle) {
58 case "direct-path":
59 return [target];
60 case "goto":
61 return parsedTarget ? ["--goto", target] : [target];
62 case "line-column": {
63 if (!parsedTarget) {
64 return [target];
65 }
66
67 const { path, line, column } = parsedTarget;
68 return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
69 }
70 }
71}
72
73function resolveEditorArgs(
74 editor: (typeof EDITORS)[number],
75 target: string,
76): ReadonlyArray<string> {
77 const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
78 return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
79}
80
81function resolveAvailableCommand(
82 commands: ReadonlyArray<string>,
83 options: CommandAvailabilityOptions = {},
84): string | null {
85 for (const command of commands) {
86 if (isCommandAvailable(command, options)) {
87 return command;
88 }
89 }
90 return null;
91}
92
93function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
94 switch (platform) {
95 case "darwin":
96 return "open";
97 case "win32":
98 return "explorer";
99 default:
100 return "xdg-open";
101 }
102}
103
104export function resolveAvailableEditors(
105 platform: NodeJS.Platform = process.platform,
106 env: NodeJS.ProcessEnv = process.env,
107): ReadonlyArray<EditorId> {
108 const available: EditorId[] = [];
109
110 for (const editor of EDITORS) {
111 if (editor.commands === null) {
112 const command = fileManagerCommandForPlatform(platform);
113 if (isCommandAvailable(command, { platform, env })) {
114 available.push(editor.id);
115 }
116 continue;
117 }
118
119 const command = resolveAvailableCommand(editor.commands, { platform, env });
120 if (command !== null) {
121 available.push(editor.id);
122 }
123 }
124
125 return available;
126}
127
128/**
129 * OpenShape - Service API for browser and editor launch actions.
130 */
131export interface OpenShape {
132 /**
133 * Open a URL target in the default browser.
134 */
135 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
136
137 /**
138 * Open a workspace path in a selected editor integration.
139 *
140 * Launches the editor as a detached process so server startup is not blocked.
141 */
142 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
143}
144
145/**
146 * Open - Service tag for browser/editor launch operations.
147 */
148export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
149
150// ==============================
151// Implementations
152// ==============================
153
154export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
155 input: OpenInEditorInput,
156 platform: NodeJS.Platform = process.platform,
157 env: NodeJS.ProcessEnv = process.env,
158): Effect.fn.Return<EditorLaunch, OpenError> {
159 yield* Effect.annotateCurrentSpan({
160 "open.editor": input.editor,
161 "open.cwd": input.cwd,
162 "open.platform": platform,
163 });
164 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
165 if (!editorDef) {
166 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
167 }
168
169 if (editorDef.commands) {
170 const command =
171 resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
172 return {
173 command,
174 args: resolveEditorArgs(editorDef, input.cwd),
175 };
176 }
177
178 if (editorDef.id !== "file-manager") {
179 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
180 }
181
182 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
183});
184
185export const launchDetached = (launch: EditorLaunch) =>
186 Effect.gen(function* () {
187 if (!isCommandAvailable(launch.command)) {
188 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
189 }
190
191 yield* Effect.callback<void, OpenError>((resume) => {
192 let child;
193 try {
194 const isWin32 = process.platform === "win32";
195 child = spawn(
196 launch.command,
197 isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
198 {
199 detached: true,
200 stdio: "ignore",
201 shell: isWin32,
202 },
203 );
204 } catch (error) {
205 return resume(
206 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
207 );
208 }
209
210 const handleSpawn = () => {
211 child.unref();
212 resume(Effect.void);
213 };
214
215 child.once("spawn", handleSpawn);
216 child.once("error", (cause) =>
217 resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
218 );
219 });
220 });
221
222const make = Effect.gen(function* () {
223 const open = yield* Effect.tryPromise({
224 try: () => import("open"),
225 catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
226 });
227
228 return {
229 openBrowser: (target) =>
230 Effect.tryPromise({
231 try: () => open.default(target),
232 catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
233 }),
234 openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
235 } satisfies OpenShape;
236});
237
238export const OpenLive = Layer.effect(Open, make);