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
417function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
418 return platform === "win32" ? entry.replaceAll('"', "") : entry;
419}
420
421export function mergePathValues(
422 preferredPath: string | undefined,
423 inheritedPath: string | undefined,
424 platform: NodeJS.Platform,
425): string | undefined {
426 const delimiter = pathDelimiterForPlatform(platform);
427 const merged: string[] = [];
428 const seen = new Set<string>();
429
430 for (const rawValue of [preferredPath, inheritedPath]) {
431 if (!rawValue) continue;
432
433 for (const entry of rawValue.split(delimiter)) {
434 const sanitized = sanitizePathEntry(entry.trim(), platform);
435 if (sanitized.length === 0) continue;
436
437 const normalized = normalizePathEntryForComparison(sanitized, platform);
438 if (normalized.length === 0 || seen.has(normalized)) continue;
439
440 seen.add(normalized);
441 merged.push(sanitized);
442 }
443 }
444
445 return merged.length > 0 ? merged.join(delimiter) : undefined;
446}
447
448function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
449 return env.PATH ?? env.Path ?? env.path;
450}
451
452function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
453 return readEnvPath(env) ?? "";
454}
455
456function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
457 const rawValue = env.PATHEXT;
458 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
459 if (!rawValue) return fallback;
460
461 const parsed: string[] = [];
462 for (const entry of rawValue.split(";")) {
463 const trimmed = entry.trim();
464 if (trimmed.length === 0) continue;
465 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
466 }
467 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
468}
469
470function resolveCommandCandidates(
471 command: string,
472 platform: NodeJS.Platform,
473 windowsPathExtensions: ReadonlyArray<string>,
474 extname: (path: string) => string,
475): ReadonlyArray<string> {
476 if (platform !== "win32") return [command];
477 const extension = extname(command);
478 const normalizedExtension = extension.toUpperCase();
479
480 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
481 const commandWithoutExtension = command.slice(0, -extension.length);
482 return Array.from(
483 new Set([
484 command,
485 `${commandWithoutExtension}${normalizedExtension}`,
486 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
487 ]),
488 );
489 }
490
491 const candidates: string[] = [];
492 for (const candidateExtension of windowsPathExtensions) {
493 candidates.push(`${command}${candidateExtension}`);
494 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
495 }
496 return Array.from(new Set(candidates));
497}
498
499// Session bootstrap resolves the same commands over and over, each PATH scan
500// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of
501// thousands per connect). Memoize the scan outcome per
502// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the
503// cache while any change to the search environment invalidates immediately.
504// Explicit-path resolution is never cached - callers probe paths they have
505// just written (e.g. managed binary installs). A "not-found" outcome is also
506// cached for the TTL, so a just-installed binary can stay invisible for up to
507// 30s unless resolved by explicit path.
508// TTL expiry uses the monotonic clock (Clock.currentTimeNanos) so backward
509// wall-clock adjustments cannot keep expired entries alive.
510const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
511const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
512const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
513
514interface CommandResolutionCacheEntry {
515 readonly resolvedPath: string | null;
516 readonly expiresAtNanos: bigint;
517}
518
519// The cache lives in the Effect environment (like HostProcessPlatform above)
520// so tests and embedders can provide an isolated instance; the default is a
521// single process-wide map shared by all consumers.
522export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
523 "@t3tools/shared/shell/CommandResolutionCache",
524 {
525 defaultValue: () => new Map(),
526 },
527);
528
529function cacheCommandResolution(
530 cache: Map<string, CommandResolutionCacheEntry>,
531 cacheKey: string,
532 resolvedPath: string | null,
533 nowNanos: bigint,
534): void {
535 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
536 const oldestKey = cache.keys().next().value;
537 if (oldestKey !== undefined) {
538 cache.delete(oldestKey);
539 }
540 }
541 cache.set(cacheKey, {
542 resolvedPath,
543 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
544 });
545}
546
547const isExecutableFile = Effect.fn("shell.isExecutableFile")(function* (
548 filePath: string,
549 platform: NodeJS.Platform,
550 windowsPathExtensions: ReadonlyArray<string>,
551): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
552 const fileSystem = yield* FileSystem.FileSystem;
553 const path = yield* Path.Path;
554 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
555 if (stat === null || stat.type !== "File") return false;
556
557 if (platform === "win32") {
558 const extension = path.extname(filePath);
559 if (extension.length === 0) return false;
560 return windowsPathExtensions.includes(extension.toUpperCase());
561 }
562
563 return canExecuteFile(filePath);
564});
565
566const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
567 command: string,
568 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
569): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {
570 const path = yield* Path.Path;
571 const platform = options.platform;
572 const env = options.env ?? process.env;
573 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
574 const commandCandidates = resolveCommandCandidates(
575 command,
576 platform,
577 windowsPathExtensions,
578 path.extname,
579 );
580
581 if (command.includes("/") || command.includes("\\")) {
582 for (const candidate of commandCandidates) {
583 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
584 return candidate;
585 }
586 }
587 return yield* new CommandResolutionError({ command, reason: "not-found" });
588 }
589
590 const pathValue = resolvePathEnvironmentVariable(env);
591 if (pathValue.length === 0) {
592 return yield* new CommandResolutionError({ command, reason: "not-found" });
593 }
594
595 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
596 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
597 );
598 const cache = yield* CommandResolutionCache;
599 const nowNanos = yield* Clock.currentTimeNanos;
600 const cached = cache.get(cacheKey);
601 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
602 if (cached.resolvedPath === null) {
603 return yield* new CommandResolutionError({ command, reason: "not-found" });
604 }
605 return cached.resolvedPath;
606 }
607
608 const pathEntries: string[] = [];
609 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
610 const pathEntry = stripWrappingQuotes(entry.trim());
611 if (pathEntry.length > 0) {
612 pathEntries.push(pathEntry);
613 }
614 }
615
616 for (const pathEntry of pathEntries) {
617 for (const candidate of commandCandidates) {
618 const candidatePath = path.join(pathEntry, candidate);
619 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
620 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
621 return candidatePath;
622 }
623 }
624 }
625 cacheCommandResolution(cache, cacheKey, null, nowNanos);
626 return yield* new CommandResolutionError({ command, reason: "not-found" });
627});
628
629export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
630 command: string,
631 options: CommandAvailabilityOptions = {},
632) {
633 return yield* resolveCommandPathForPlatform(command, {
634 env: options.env ?? (yield* HostProcessEnvironment),
635 platform: yield* HostProcessPlatform,
636 });
637});
638
639export const resolveSpawnCommand = Effect.fn("shell.resolveSpawnCommand")(function* (
640 command: string,
641 args: ReadonlyArray<string>,
642 options: CommandAvailabilityOptions = {},
643): Effect.fn.Return<ResolvedSpawnCommand> {
644 const platform = yield* HostProcessPlatform;
645 if (platform !== "win32") {
646 return { command, args: [...args], shell: false };
647 }
648
649 const hostEnvironment = yield* HostProcessEnvironment;
650 const env =
651 options.env === undefined
652 ? hostEnvironment
653 : options.extendEnv
654 ? { ...hostEnvironment, ...options.env }
655 : options.env;
656 const resolveExecutable = yield* SpawnExecutableResolution;
657 const resolvedCommand = resolveExecutable(command, platform, env) ?? command;
658 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
659 if (extension !== ".cmd" && extension !== ".bat") {
660 return { command: resolvedCommand, args: [...args], shell: false };
661 }
662
663 return {
664 command: escapeWindowsShellArg(resolvedCommand),
665 args: sanitizeShellModeArgsForPlatform(args, platform),
666 shell: true,
667 };
668});
669
670export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
671 command: string,
672 options: CommandAvailabilityOptions = {},
673) {
674 return yield* resolveCommandPath(command, options).pipe(
675 Effect.as(true),
676 Effect.catchTag("CommandResolutionError", () => Effect.succeed(false)),
677 );
678});
679
680export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
681 const appData = env.APPDATA?.trim();
682 const localAppData = env.LOCALAPPDATA?.trim();
683 const userProfile = env.USERPROFILE?.trim();
684
685 return [
686 ...(appData ? [`${appData}\\npm`] : []),
687 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
688 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
689 ...(userProfile
690 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
691 : []),
692 ];
693}
694
695function readWindowsEnvironmentSafely(
696 readEnvironment: WindowsShellEnvironmentReader,
697 names: ReadonlyArray<string>,
698 options?: WindowsEnvironmentProbeOptions,
699): Partial<Record<string, string>> {
700 try {
701 return readEnvironment(names, options);
702 } catch {
703 return {};
704 }
705}
706
707function mergeWindowsEnv(
708 currentEnv: NodeJS.ProcessEnv,
709 patch: Partial<Record<string, string>>,
710): NodeJS.ProcessEnv {
711 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
712 for (const [key, value] of Object.entries(patch)) {
713 if (value !== undefined) {
714 nextEnv[key] = value;
715 }
716 }
717 return nextEnv;
718}
719
720export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
721 env: NodeJS.ProcessEnv,
722): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
723 const readEnvironment = yield* WindowsShellEnvironment;
724 const commandAvailable = yield* CommandAvailability;
725 const inheritedPath = readEnvPath(env);
726 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
727 loadProfile: false,
728 }).PATH;
729 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
730 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
731 const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
732 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
733 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
734
735 if (yield* commandAvailable("node", { env: baselineEnv })) {
736 return baselinePatch;
737 }
738
739 const profiledEnvironment = readWindowsEnvironmentSafely(
740 readEnvironment,
741 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
742 { loadProfile: true },
743 );
744 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
745 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
746 ...(profiledPath ? { PATH: profiledPath } : {}),
747 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
748 ...(profiledEnvironment.FNM_MULTISHELL_PATH
749 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
750 : {}),
751 };
752 return Object.keys(profiledPatch).length > 0
753 ? { ...baselinePatch, ...profiledPatch }
754 : baselinePatch;
755});