Open History to see the last commit
1import * as OS from "node:os";
2import { Effect, Path } from "effect";
3import {
4 listLoginShellCandidates,
5 mergePathEntries,
6 readPathFromLaunchctl,
7 readPathFromLoginShell,
8} from "@t3tools/shared/shell";
9
10function logPathHydrationWarning(message: string, error?: unknown): void {
11 console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
12}
13
14export function fixPath(
15 options: {
16 env?: NodeJS.ProcessEnv;
17 platform?: NodeJS.Platform;
18 readPath?: typeof readPathFromLoginShell;
19 readLaunchctlPath?: typeof readPathFromLaunchctl;
20 userShell?: string;
21 logWarning?: (message: string, error?: unknown) => void;
22 } = {},
23): void {
24 const platform = options.platform ?? process.platform;
25 if (platform !== "darwin" && platform !== "linux") return;
26
27 const env = options.env ?? process.env;
28 const logWarning = options.logWarning ?? logPathHydrationWarning;
29 const readPath = options.readPath ?? readPathFromLoginShell;
30
31 try {
32 let shellPath: string | undefined;
33 for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
34 try {
35 shellPath = readPath(shell);
36 } catch (error) {
37 logWarning(`Failed to read PATH from login shell ${shell}.`, error);
38 }
39
40 if (shellPath) {
41 break;
42 }
43 }
44
45 const launchctlPath =
46 platform === "darwin" && !shellPath
47 ? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
48 : undefined;
49 const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
50 if (mergedPath) {
51 env.PATH = mergedPath;
52 }
53 } catch (error) {
54 logWarning("Failed to hydrate PATH from the user environment.", error);
55 }
56}
57
58export const expandHomePath = Effect.fn(function* (input: string) {
59 const { join } = yield* Path.Path;
60 if (input === "~") {
61 return OS.homedir();
62 }
63 if (input.startsWith("~/") || input.startsWith("~\\")) {
64 return join(OS.homedir(), input.slice(2));
65 }
66 return input;
67});
68
69export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
70 const { join, resolve } = yield* Path.Path;
71 if (!raw || raw.trim().length === 0) {
72 return join(OS.homedir(), ".t3");
73 }
74 return resolve(yield* expandHomePath(raw.trim()));
75});