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

open.ts

340 lines9.5 KB

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;
26​
27interface EditorLaunch {
28 readonly command: string;
29 readonly args: ReadonlyArray<string>;
31​
32interface CommandAvailabilityOptions {
33 readonly platform?: NodeJS.Platform;
34 readonly env?: NodeJS.ProcessEnv;
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 };
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 }
77​
78function resolveAvailableCommand(
79 commands: ReadonlyArray<string>,
80 options: CommandAvailabilityOptions = {},
81): string | null {
82 for (const command of commands) {
83 if (isCommandAvailable(command, options)) {
84 return command;
85 }
86 }
87 return null;
89​
90function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
91 switch (platform) {
92 case "darwin":
93 return "open";
94 case "win32":
95 return "explorer";
96 default:
97 return "xdg-open";
98 }
100​
101function stripWrappingQuotes(value: string): string {
102 return value.replace(/^"+|"+$/g, "");
104​
105function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
106 return env.PATH ?? env.Path ?? env.path ?? "";
108​
109function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
110 const rawValue = env.PATHEXT;
111 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
112 if (!rawValue) return fallback;
113​
114 const parsed = rawValue
115 .split(";")
116 .map((entry) => entry.trim())
117 .filter((entry) => entry.length > 0)
118 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
119 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
121​
122function resolveCommandCandidates(
123 command: string,
124 platform: NodeJS.Platform,
125 windowsPathExtensions: ReadonlyArray<string>,
126): ReadonlyArray<string> {
127 if (platform !== "win32") return [command];
128 const extension = extname(command);
129 const normalizedExtension = extension.toUpperCase();
130​
131 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
132 const commandWithoutExtension = command.slice(0, -extension.length);
133 return Array.from(
134 new Set([
135 command,
136 `${commandWithoutExtension}${normalizedExtension}`,
137 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
138 ]),
139 );
140 }
141​
142 const candidates: string[] = [];
143 for (const extension of windowsPathExtensions) {
144 candidates.push(`${command}${extension}`);
145 candidates.push(`${command}${extension.toLowerCase()}`);
146 }
147 return Array.from(new Set(candidates));
149​
150function isExecutableFile(
151 filePath: string,
152 platform: NodeJS.Platform,
153 windowsPathExtensions: ReadonlyArray<string>,
154): boolean {
155 try {
156 const stat = statSync(filePath);
157 if (!stat.isFile()) return false;
158 if (platform === "win32") {
159 const extension = extname(filePath);
160 if (extension.length === 0) return false;
161 return windowsPathExtensions.includes(extension.toUpperCase());
162 }
163 accessSync(filePath, constants.X_OK);
164 return true;
165 } catch {
166 return false;
167 }
169​
170function resolvePathDelimiter(platform: NodeJS.Platform): string {
171 return platform === "win32" ? ";" : ":";
173​
174export function isCommandAvailable(
175 command: string,
176 options: CommandAvailabilityOptions = {},
177): boolean {
178 const platform = options.platform ?? process.platform;
179 const env = options.env ?? process.env;
180 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
181 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
182​
183 if (command.includes("/") || command.includes("\\")) {
184 return commandCandidates.some((candidate) =>
185 isExecutableFile(candidate, platform, windowsPathExtensions),
186 );
187 }
188​
189 const pathValue = resolvePathEnvironmentVariable(env);
190 if (pathValue.length === 0) return false;
191 const pathEntries = pathValue
192 .split(resolvePathDelimiter(platform))
193 .map((entry) => stripWrappingQuotes(entry.trim()))
194 .filter((entry) => entry.length > 0);
195​
196 for (const pathEntry of pathEntries) {
197 for (const candidate of commandCandidates) {
198 if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
199 return true;
200 }
201 }
202 }
203 return false;
205​
206export function resolveAvailableEditors(
207 platform: NodeJS.Platform = process.platform,
208 env: NodeJS.ProcessEnv = process.env,
209): ReadonlyArray<EditorId> {
210 const available: EditorId[] = [];
211​
212 for (const editor of EDITORS) {
213 if (editor.commands === null) {
214 const command = fileManagerCommandForPlatform(platform);
215 if (isCommandAvailable(command, { platform, env })) {
216 available.push(editor.id);
217 }
218 continue;
219 }
220​
221 const command = resolveAvailableCommand(editor.commands, { platform, env });
222 if (command !== null) {
223 available.push(editor.id);
224 }
225 }
226​
227 return available;
229​
230/**
231 * OpenShape - Service API for browser and editor launch actions.
232 */
233export interface OpenShape {
234 /**
235 * Open a URL target in the default browser.
236 */
237 readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
238​
239 /**
240 * Open a workspace path in a selected editor integration.
241 *
242 * Launches the editor as a detached process so server startup is not blocked.
243 */
244 readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
246​
247/**
248 * Open - Service tag for browser/editor launch operations.
249 */
250export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
251​
252// ==============================
253// Implementations
254// ==============================
255​
256export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
257 input: OpenInEditorInput,
258 platform: NodeJS.Platform = process.platform,
259 env: NodeJS.ProcessEnv = process.env,
260): Effect.fn.Return<EditorLaunch, OpenError> {
261 yield* Effect.annotateCurrentSpan({
262 "open.editor": input.editor,
263 "open.cwd": input.cwd,
264 "open.platform": platform,
265 });
266 const editorDef = EDITORS.find((editor) => editor.id === input.editor);
267 if (!editorDef) {
268 return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
269 }
270​
271 if (editorDef.commands) {
272 const command =
273 resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
274 return {
275 command,
276 args: resolveCommandEditorArgs(editorDef, input.cwd),
277 };
278 }
279​
280 if (editorDef.id !== "file-manager") {
281 return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
282 }
283​
284 return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
285});
286​
287export const launchDetached = (launch: EditorLaunch) =>
288 Effect.gen(function* () {
289 if (!isCommandAvailable(launch.command)) {
290 return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
291 }
292​
293 yield* Effect.callback<void, OpenError>((resume) => {
294 let child;
295 try {
296 const isWin32 = process.platform === "win32";
297 child = spawn(
298 launch.command,
299 isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
300 {
301 detached: true,
302 stdio: "ignore",
303 shell: isWin32,
304 },
305 );
306 } catch (error) {
307 return resume(
308 Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
309 );
310 }
311​
312 const handleSpawn = () => {
313 child.unref();
314 resume(Effect.void);
315 };
316​
317 child.once("spawn", handleSpawn);
318 child.once("error", (cause) =>
319 resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
320 );
321 });
322 });
323​
324const make = Effect.gen(function* () {
325 const open = yield* Effect.tryPromise({
326 try: () => import("open"),
327 catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
328 });
329​
330 return {
331 openBrowser: (target) =>
332 Effect.tryPromise({
333 try: () => open.default(target),
334 catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
335 }),
336 openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
337 } satisfies OpenShape;
338});
339​
340export const OpenLive = Layer.effect(Open, make);