Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFS from "node:fs";
6import * as Clock from "effect/Clock";
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Path from "effect/Path";
11
12import { HostProcessEnvironment, HostProcessPlatform } from "./hostProcess.ts";
13import * as Context from "effect/Context";
14
15const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
16const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
17const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
18const WINDOWS_PATH_DELIMITER = ";";
19const POSIX_PATH_DELIMITER = ":";
20const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
21
22type ExecFileSyncLike = (
23 file: string,
24 args: ReadonlyArray<string>,
25 options: { encoding: "utf8"; timeout: number },
26) => string;
27
28function canExecuteFile(filePath: string): boolean {
29 try {
30 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
31 return true;
32 } catch {
33 return false;
34 }
35}
36
37export interface CommandAvailabilityOptions {
38 readonly env?: NodeJS.ProcessEnv;
39 readonly extendEnv?: boolean;
40}
41
42export type CommandAvailabilityChecker = (
43 command: string,
44 options?: CommandAvailabilityOptions,
45) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
46
47export class CommandResolutionError extends Data.TaggedError("CommandResolutionError")<{
48 readonly command: string;
49 readonly reason: "not-found";
50}> {}
51
52const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
53
54/**
55 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
56 * on Windows). Node joins the command and arguments with spaces and hands the
57 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
58 * must be escaped to survive both cmd.exe parsing and the target program's
59 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
60 */
61function escapeWindowsShellArg(arg: string): string {
62 // Double up backslashes that precede a double quote, then escape the quote
63 // itself so it survives CommandLineToArgvW.
64 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
65 // Double up trailing backslashes so the closing quote is not escaped away.
66 escaped = escaped.replace(/(\\*)$/, "$1$1");
67 // Quote the whole argument so embedded whitespace is preserved.
68 escaped = `"${escaped}"`;
69 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
70 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
71}
72
73/**
74 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
75 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
76 * and returns the arguments untouched everywhere else.
77 */
78function sanitizeShellModeArgsForPlatform(
79 args: ReadonlyArray<string>,
80 platform: NodeJS.Platform,
81): Array<string> {
82 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
83}
84
85export interface ResolvedSpawnCommand {
86 readonly command: string;
87 readonly args: ReadonlyArray<string>;
88 readonly shell: boolean;
89}
90
91export type SpawnExecutableResolver = (
92 command: string,
93 platform: NodeJS.Platform,
94 env: NodeJS.ProcessEnv,
95) => string | undefined;
96
97function resolveSpawnExecutableWithNode(
98 command: string,
99 platform: NodeJS.Platform,
100 env: NodeJS.ProcessEnv,
101): string | undefined {
102 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
103 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
104 const candidates = resolveCommandCandidates(
105 command,
106 platform,
107 windowsPathExtensions,
108 path.extname,
109 );
110 const isExecutable = (candidate: string) => {
111 try {
112 if (!NodeFS.statSync(candidate).isFile()) return false;
113 if (platform === "win32") {
114 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
115 }
116 return canExecuteFile(candidate);
117 } catch {
118 return false;
119 }
120 };
121
122 if (command.includes("/") || command.includes("\\")) {
123 return candidates.find(isExecutable);
124 }
125
126 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
127 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
128 if (normalizedPathEntry.length === 0) continue;
129 for (const candidate of candidates) {
130 const candidatePath = path.join(normalizedPathEntry, candidate);
131 if (isExecutable(candidatePath)) return candidatePath;
132 }
133 }
134 return undefined;
135}
136
137export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
138 "@t3tools/shared/shell/SpawnExecutableResolution",
139 {
140 defaultValue: () => resolveSpawnExecutableWithNode,
141 },
142);
143
144export interface WindowsEnvironmentProbeOptions {
145 readonly loadProfile?: boolean;
146}
147
148function trimNonEmpty(value: string | null | undefined): string | undefined {
149 const trimmed = value?.trim();
150 return trimmed && trimmed.length > 0 ? trimmed : undefined;
151}
152
153function readUserLoginShell(): string | undefined {
154 try {
155 return trimNonEmpty(NodeOS.userInfo().shell);
156 } catch {
157 return undefined;
158 }
159}
160
161export function listLoginShellCandidates(
162 platform: NodeJS.Platform,
163 shell: string | undefined,
164 userShell = readUserLoginShell(),
165): ReadonlyArray<string> {
166 const fallbackShell =
167 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
168 const seen = new Set<string>();
169 const candidates: string[] = [];
170
171 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
172 if (!candidate || seen.has(candidate)) {
173 continue;
174 }
175 seen.add(candidate);
176 candidates.push(candidate);
177 }
178
179 return candidates;
180}
181
182export function extractPathFromShellOutput(output: string): string | null {
183 const startIndex = output.indexOf(PATH_CAPTURE_START);
184 if (startIndex === -1) return null;
185
186 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
187 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
188 if (endIndex === -1) return null;
189
190 const pathValue = output.slice(valueStartIndex, endIndex).trim();
191 return pathValue.length > 0 ? pathValue : null;
192}
193
194export function readPathFromLoginShell(
195 shell: string,
196 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
197): string | undefined {
198 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
199}
200
201export function readPathFromLaunchctl(
202 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
203): string | undefined {
204 try {
205 return trimNonEmpty(
206 execFile("/bin/launchctl", ["getenv", "PATH"], {
207 encoding: "utf8",
208 timeout: 2000,
209 }),
210 );
211 } catch {
212 return undefined;
213 }
214}
215
216export function mergePathEntries(
217 preferredPath: string | undefined,
218 inheritedPath: string | undefined,
219 platform: NodeJS.Platform,
220): string | undefined {
221 const delimiter = platform === "win32" ? ";" : ":";
222 const merged: string[] = [];
223 const seen = new Set<string>();
224
225 for (const pathValue of [preferredPath, inheritedPath]) {
226 if (!pathValue) continue;
227 for (const entry of pathValue.split(delimiter)) {
228 const trimmedEntry = entry.trim();
229 if (!trimmedEntry || seen.has(trimmedEntry)) {
230 continue;
231 }
232 seen.add(trimmedEntry);
233 merged.push(trimmedEntry);
234 }
235 }
236
237 return merged.length > 0 ? merged.join(delimiter) : undefined;
238}
239
240function envCaptureStart(name: string): string {
241 return `__T3CODE_ENV_${name}_START__`;
242}
243
244function envCaptureEnd(name: string): string {
245 return `__T3CODE_ENV_${name}_END__`;
246}
247
248function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
249 return names
250 .map((name) => {
251 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
252 throw new Error(`Unsupported environment variable name: ${name}`);
253 }
254
255 return [
256 `printf '%s\\n' '${envCaptureStart(name)}'`,
257 `printenv ${name} || true`,
258 `printf '%s\\n' '${envCaptureEnd(name)}'`,
259 ].join("; ");
260 })
261 .join("; ");
262}
263
264function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
265 return [
266 "$ErrorActionPreference = 'Stop'",
267 ...names.flatMap((name) => {
268 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
269 throw new Error(`Unsupported environment variable name: ${name}`);
270 }
271
272 return [
273 `Write-Output '${envCaptureStart(name)}'`,
274 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
275 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
276 `Write-Output '${envCaptureEnd(name)}'`,
277 ];
278 }),
279 ].join("; ");
280}
281
282function extractEnvironmentValue(output: string, name: string): string | undefined {
283 const startMarker = envCaptureStart(name);
284 const endMarker = envCaptureEnd(name);
285 const startIndex = output.indexOf(startMarker);
286 if (startIndex === -1) return undefined;
287
288 const valueStartIndex = startIndex + startMarker.length;
289 const endIndex = output.indexOf(endMarker, valueStartIndex);
290 if (endIndex === -1) return undefined;
291
292 const value = output
293 .slice(valueStartIndex, endIndex)
294 .replace(/^\r?\n/, "")
295 .replace(/\r?\n$/, "");
296
297 return value.length > 0 ? value : undefined;
298}
299
300export type ShellEnvironmentReader = (
301 shell: string,
302 names: ReadonlyArray<string>,
303 execFile?: ExecFileSyncLike,
304) => Partial<Record<string, string>>;
305
306export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
307 shell,
308 names,
309 execFile = NodeChildProcess.execFileSync,
310) => {
311 if (names.length === 0) {
312 return {};
313 }
314
315 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
316 encoding: "utf8",
317 timeout: 5000,
318 });
319
320 const environment: Partial<Record<string, string>> = {};
321 for (const name of names) {
322 const value = extractEnvironmentValue(output, name);
323 if (value !== undefined) {
324 environment[name] = value;
325 }
326 }
327
328 return environment;
329};
330
331export type WindowsShellEnvironmentReader = (
332 names: ReadonlyArray<string>,
333 options?: WindowsEnvironmentProbeOptions,
334) => Partial<Record<string, string>>;
335
336export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
337 "@t3tools/shared/shell/WindowsShellEnvironment",
338 {
339 defaultValue: () => readEnvironmentFromWindowsShell,
340 },
341);
342
343export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
344 "@t3tools/shared/shell/CommandAvailability",
345 {
346 defaultValue: () => isCommandAvailable,
347 },
348);
349
350export function readEnvironmentFromWindowsShell(
351 names: ReadonlyArray<string>,
352 execFile?: ExecFileSyncLike,
353): Partial<Record<string, string>>;
354export function readEnvironmentFromWindowsShell(
355 names: ReadonlyArray<string>,
356 options?: WindowsEnvironmentProbeOptions,
357 execFile?: ExecFileSyncLike,
358): Partial<Record<string, string>>;
359export function readEnvironmentFromWindowsShell(
360 names: ReadonlyArray<string>,
361 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
362 maybeExecFile?: ExecFileSyncLike,
363): Partial<Record<string, string>> {
364 if (names.length === 0) {
365 return {};
366 }
367
368 const options =
369 typeof optionsOrExecFile === "function"
370 ? ({} satisfies WindowsEnvironmentProbeOptions)
371 : (optionsOrExecFile ?? {});
372 const execFile: ExecFileSyncLike =
373 typeof optionsOrExecFile === "function"
374 ? optionsOrExecFile
375 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
376 const command = buildWindowsEnvironmentCaptureCommand(names);
377 const args = [
378 "-NoLogo",
379 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
380 "-NonInteractive",
381 "-Command",
382 command,
383 ];
384 for (const shell of WINDOWS_SHELL_CANDIDATES) {
385 try {
386 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
387
388 const environment: Partial<Record<string, string>> = {};
389 for (const name of names) {
390 const value = extractEnvironmentValue(output, name);
391 if (value !== undefined) {
392 environment[name] = value;
393 }
394 }
395 return environment;
396 } catch {
397 continue;
398 }
399 }
400
401 return {};
402}
403
404function stripWrappingQuotes(value: string): string {
405 return value.replace(/^"+|"+$/g, "");
406}
407
408function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
409 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
410}
411
412function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
413 const normalized = stripWrappingQuotes(entry.trim());
414 return platform === "win32" ? normalized.toLowerCase() : normalized;
415}
416
417export function mergePathValues(
418 preferredPath: string | undefined,
419 inheritedPath: string | undefined,
420 platform: NodeJS.Platform,
421): string | undefined {
422 const delimiter = pathDelimiterForPlatform(platform);
423 const merged: string[] = [];
424 const seen = new Set<string>();
425
426 for (const rawValue of [preferredPath, inheritedPath]) {
427 if (!rawValue) continue;
428
429 for (const entry of rawValue.split(delimiter)) {
430 const trimmed = entry.trim();
431 if (trimmed.length === 0) continue;
432
433 const normalized = normalizePathEntryForComparison(trimmed, platform);
434 if (normalized.length === 0 || seen.has(normalized)) continue;
435
436 seen.add(normalized);
437 merged.push(trimmed);
438 }
439 }
440
441 return merged.length > 0 ? merged.join(delimiter) : undefined;
442}
443
444function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
445 return env.PATH ?? env.Path ?? env.path;
446}
447
448function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
449 return readEnvPath(env) ?? "";
450}
451
452function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
453 const rawValue = env.PATHEXT;
454 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
455 if (!rawValue) return fallback;
456
457 const parsed: string[] = [];
458 for (const entry of rawValue.split(";")) {
459 const trimmed = entry.trim();
460 if (trimmed.length === 0) continue;
461 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
462 }
463 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
464}
465
466function resolveCommandCandidates(
467 command: string,
468 platform: NodeJS.Platform,
469 windowsPathExtensions: ReadonlyArray<string>,
470 extname: (path: string) => string,
471): ReadonlyArray<string> {
472 if (platform !== "win32") return [command];
473 const extension = extname(command);
474 const normalizedExtension = extension.toUpperCase();
475
476 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
477 const commandWithoutExtension = command.slice(0, -extension.length);
478 return Array.from(
479 new Set([
480 command,
481 `${commandWithoutExtension}${normalizedExtension}`,
482 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
483 ]),
484 );
485 }
486
487 const candidates: string[] = [];
488 for (const candidateExtension of windowsPathExtensions) {
489 candidates.push(`${command}${candidateExtension}`);
490 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
491 }
492 return Array.from(new Set(candidates));
493}
494
495// Session bootstrap resolves the same commands over and over, each PATH scan
496// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of
497// thousands per connect). Memoize the scan outcome per
498// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the
499// cache while any change to the search environment invalidates immediately.
500// Explicit-path resolution is never cached - callers probe paths they have
501// just written (e.g. managed binary installs). A "not-found" outcome is also
502// cached for the TTL, so a just-installed binary can stay invisible for up to
503// 30s unless resolved by explicit path.
504// TTL expiry uses the monotonic clock (Clock.currentTimeNanos) so backward
505// wall-clock adjustments cannot keep expired entries alive.
506const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
507const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
508const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
509
510interface CommandResolutionCacheEntry {
511 readonly resolvedPath: string | null;
512 readonly expiresAtNanos: bigint;
513}
514
515// The cache lives in the Effect environment (like HostProcessPlatform above)
516// so tests and embedders can provide an isolated instance; the default is a
517// single process-wide map shared by all consumers.
518export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
519 "@t3tools/shared/shell/CommandResolutionCache",
520 {
521 defaultValue: () => new Map(),
522 },
523);
524
525function cacheCommandResolution(
526 cache: Map<string, CommandResolutionCacheEntry>,
527 cacheKey: string,
528 resolvedPath: string | null,
529 nowNanos: bigint,
530): void {
531 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
532 const oldestKey = cache.keys().next().value;
533 if (oldestKey !== undefined) {
534 cache.delete(oldestKey);
535 }
536 }
537 cache.set(cacheKey, {
538 resolvedPath,
539 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
540 });
541}
542
543const isExecutableFile = Effect.fn("shell.isExecutableFile")(function* (
544 filePath: string,
545 platform: NodeJS.Platform,
546 windowsPathExtensions: ReadonlyArray<string>,
547): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
548 const fileSystem = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
551 if (stat === null || stat.type !== "File") return false;
552
553 if (platform === "win32") {
554 const extension = path.extname(filePath);
555 if (extension.length === 0) return false;
556 return windowsPathExtensions.includes(extension.toUpperCase());
557 }
558
559 return canExecuteFile(filePath);
560});
561
562const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
563 command: string,
564 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
565): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {
566 const path = yield* Path.Path;
567 const platform = options.platform;
568 const env = options.env ?? process.env;
569 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
570 const commandCandidates = resolveCommandCandidates(
571 command,
572 platform,
573 windowsPathExtensions,
574 path.extname,
575 );
576
577 if (command.includes("/") || command.includes("\\")) {
578 for (const candidate of commandCandidates) {
579 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
580 return candidate;
581 }
582 }
583 return yield* new CommandResolutionError({ command, reason: "not-found" });
584 }
585
586 const pathValue = resolvePathEnvironmentVariable(env);
587 if (pathValue.length === 0) {
588 return yield* new CommandResolutionError({ command, reason: "not-found" });
589 }
590
591 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
592 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
593 );
594 const cache = yield* CommandResolutionCache;
595 const nowNanos = yield* Clock.currentTimeNanos;
596 const cached = cache.get(cacheKey);
597 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
598 if (cached.resolvedPath === null) {
599 return yield* new CommandResolutionError({ command, reason: "not-found" });
600 }
601 return cached.resolvedPath;
602 }
603
604 const pathEntries: string[] = [];
605 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
606 const pathEntry = stripWrappingQuotes(entry.trim());
607 if (pathEntry.length > 0) {
608 pathEntries.push(pathEntry);
609 }
610 }
611
612 for (const pathEntry of pathEntries) {
613 for (const candidate of commandCandidates) {
614 const candidatePath = path.join(pathEntry, candidate);
615 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
616 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
617 return candidatePath;
618 }
619 }
620 }
621 cacheCommandResolution(cache, cacheKey, null, nowNanos);
622 return yield* new CommandResolutionError({ command, reason: "not-found" });
623});
624
625export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
626 command: string,
627 options: CommandAvailabilityOptions = {},
628) {
629 return yield* resolveCommandPathForPlatform(command, {
630 env: options.env ?? (yield* HostProcessEnvironment),
631 platform: yield* HostProcessPlatform,
632 });
633});
634
635export const resolveSpawnCommand = Effect.fn("shell.resolveSpawnCommand")(function* (
636 command: string,
637 args: ReadonlyArray<string>,
638 options: CommandAvailabilityOptions = {},
639): Effect.fn.Return<ResolvedSpawnCommand> {
640 const platform = yield* HostProcessPlatform;
641 if (platform !== "win32") {
642 return { command, args: [...args], shell: false };
643 }
644
645 const hostEnvironment = yield* HostProcessEnvironment;
646 const env =
647 options.env === undefined
648 ? hostEnvironment
649 : options.extendEnv
650 ? { ...hostEnvironment, ...options.env }
651 : options.env;
652 const resolveExecutable = yield* SpawnExecutableResolution;
653 const resolvedCommand = resolveExecutable(command, platform, env) ?? command;
654 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
655 if (extension !== ".cmd" && extension !== ".bat") {
656 return { command: resolvedCommand, args: [...args], shell: false };
657 }
658
659 return {
660 command: escapeWindowsShellArg(resolvedCommand),
661 args: sanitizeShellModeArgsForPlatform(args, platform),
662 shell: true,
663 };
664});
665
666export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
667 command: string,
668 options: CommandAvailabilityOptions = {},
669) {
670 return yield* resolveCommandPath(command, options).pipe(
671 Effect.as(true),
672 Effect.catchTag("CommandResolutionError", () => Effect.succeed(false)),
673 );
674});
675
676export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
677 const appData = env.APPDATA?.trim();
678 const localAppData = env.LOCALAPPDATA?.trim();
679 const userProfile = env.USERPROFILE?.trim();
680
681 return [
682 ...(appData ? [`${appData}\\npm`] : []),
683 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
684 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
685 ...(userProfile ? [`${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`] : []),
686 ];
687}
688
689function readWindowsEnvironmentSafely(
690 readEnvironment: WindowsShellEnvironmentReader,
691 names: ReadonlyArray<string>,
692 options?: WindowsEnvironmentProbeOptions,
693): Partial<Record<string, string>> {
694 try {
695 return readEnvironment(names, options);
696 } catch {
697 return {};
698 }
699}
700
701function mergeWindowsEnv(
702 currentEnv: NodeJS.ProcessEnv,
703 patch: Partial<Record<string, string>>,
704): NodeJS.ProcessEnv {
705 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
706 for (const [key, value] of Object.entries(patch)) {
707 if (value !== undefined) {
708 nextEnv[key] = value;
709 }
710 }
711 return nextEnv;
712}
713
714export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
715 env: NodeJS.ProcessEnv,
716): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
717 const readEnvironment = yield* WindowsShellEnvironment;
718 const commandAvailable = yield* CommandAvailability;
719 const inheritedPath = readEnvPath(env);
720 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
721 loadProfile: false,
722 }).PATH;
723 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
724 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
725 const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
726 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
727 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
728
729 if (yield* commandAvailable("node", { env: baselineEnv })) {
730 return baselinePatch;
731 }
732
733 const profiledEnvironment = readWindowsEnvironmentSafely(
734 readEnvironment,
735 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
736 { loadProfile: true },
737 );
738 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
739 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
740 ...(profiledPath ? { PATH: profiledPath } : {}),
741 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
742 ...(profiledEnvironment.FNM_MULTISHELL_PATH
743 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
744 : {}),
745 };
746 return Object.keys(profiledPatch).length > 0
747 ? { ...baselinePatch, ...profiledPatch }
748 : baselinePatch;
749});