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 override get message(): string {
52 return `Command "${this.command}" could not be resolved (${this.reason}).`;
53 }
54}
55
56const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
57
58/**
59 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
60 * on Windows). Node joins the command and arguments with spaces and hands the
61 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
62 * must be escaped to survive both cmd.exe parsing and the target program's
63 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
64 */
65function escapeWindowsShellArg(arg: string): string {
66 // Double up backslashes that precede a double quote, then escape the quote
67 // itself so it survives CommandLineToArgvW.
68 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
69 // Double up trailing backslashes so the closing quote is not escaped away.
70 escaped = escaped.replace(/(\\*)$/, "$1$1");
71 // Quote the whole argument so embedded whitespace is preserved.
72 escaped = `"${escaped}"`;
73 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
74 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
75}
76
77/**
78 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
79 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
80 * and returns the arguments untouched everywhere else.
81 */
82function sanitizeShellModeArgsForPlatform(
83 args: ReadonlyArray<string>,
84 platform: NodeJS.Platform,
85): Array<string> {
86 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
87}
88
89export interface ResolvedSpawnCommand {
90 readonly command: string;
91 readonly args: ReadonlyArray<string>;
92 readonly shell: boolean;
93}
94
95export type SpawnExecutableResolver = (
96 command: string,
97 platform: NodeJS.Platform,
98 env: NodeJS.ProcessEnv,
99) => string | undefined;
100
101function resolveSpawnExecutableWithNode(
102 command: string,
103 platform: NodeJS.Platform,
104 env: NodeJS.ProcessEnv,
105): string | undefined {
106 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
107 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
108 const candidates = resolveCommandCandidates(
109 command,
110 platform,
111 windowsPathExtensions,
112 path.extname,
113 );
114 const isExecutable = (candidate: string) => {
115 try {
116 if (!NodeFS.statSync(candidate).isFile()) return false;
117 if (platform === "win32") {
118 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
119 }
120 return canExecuteFile(candidate);
121 } catch {
122 return false;
123 }
124 };
125
126 if (command.includes("/") || command.includes("\\")) {
127 return candidates.find(isExecutable);
128 }
129
130 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
131 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
132 if (normalizedPathEntry.length === 0) continue;
133 for (const candidate of candidates) {
134 const candidatePath = path.join(normalizedPathEntry, candidate);
135 if (isExecutable(candidatePath)) return candidatePath;
136 }
137 }
138 return undefined;
139}
140
141export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
142 "@t3tools/shared/shell/SpawnExecutableResolution",
143 {
144 defaultValue: () => resolveSpawnExecutableWithNode,
145 },
146);
147
148export interface WindowsEnvironmentProbeOptions {
149 readonly loadProfile?: boolean;
150}
151
152function trimNonEmpty(value: string | null | undefined): string | undefined {
153 const trimmed = value?.trim();
154 return trimmed && trimmed.length > 0 ? trimmed : undefined;
155}
156
157function readUserLoginShell(): string | undefined {
158 try {
159 return trimNonEmpty(NodeOS.userInfo().shell);
160 } catch {
161 return undefined;
162 }
163}
164
165export function listLoginShellCandidates(
166 platform: NodeJS.Platform,
167 shell: string | undefined,
168 userShell = readUserLoginShell(),
169): ReadonlyArray<string> {
170 const fallbackShell =
171 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
172 const seen = new Set<string>();
173 const candidates: string[] = [];
174
175 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
176 if (!candidate || seen.has(candidate)) {
177 continue;
178 }
179 seen.add(candidate);
180 candidates.push(candidate);
181 }
182
183 return candidates;
184}
185
186export function extractPathFromShellOutput(output: string): string | null {
187 const startIndex = output.indexOf(PATH_CAPTURE_START);
188 if (startIndex === -1) return null;
189
190 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
191 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
192 if (endIndex === -1) return null;
193
194 const pathValue = output.slice(valueStartIndex, endIndex).trim();
195 return pathValue.length > 0 ? pathValue : null;
196}
197
198export function readPathFromLoginShell(
199 shell: string,
200 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
201): string | undefined {
202 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
203}
204
205export function readPathFromLaunchctl(
206 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
207): string | undefined {
208 try {
209 return trimNonEmpty(
210 execFile("/bin/launchctl", ["getenv", "PATH"], {
211 encoding: "utf8",
212 timeout: 2000,
213 }),
214 );
215 } catch {
216 return undefined;
217 }
218}
219
220export function mergePathEntries(
221 preferredPath: string | undefined,
222 inheritedPath: string | undefined,
223 platform: NodeJS.Platform,
224): string | undefined {
225 const delimiter = platform === "win32" ? ";" : ":";
226 const merged: string[] = [];
227 const seen = new Set<string>();
228
229 for (const pathValue of [preferredPath, inheritedPath]) {
230 if (!pathValue) continue;
231 for (const entry of pathValue.split(delimiter)) {
232 const trimmedEntry = entry.trim();
233 if (!trimmedEntry || seen.has(trimmedEntry)) {
234 continue;
235 }
236 seen.add(trimmedEntry);
237 merged.push(trimmedEntry);
238 }
239 }
240
241 return merged.length > 0 ? merged.join(delimiter) : undefined;
242}
243
244function envCaptureStart(name: string): string {
245 return `__T3CODE_ENV_${name}_START__`;
246}
247
248function envCaptureEnd(name: string): string {
249 return `__T3CODE_ENV_${name}_END__`;
250}
251
252function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
253 return names
254 .map((name) => {
255 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
256 throw new Error(`Unsupported environment variable name: ${name}`);
257 }
258
259 return [
260 `printf '%s\\n' '${envCaptureStart(name)}'`,
261 `printenv ${name} || true`,
262 `printf '%s\\n' '${envCaptureEnd(name)}'`,
263 ].join("; ");
264 })
265 .join("; ");
266}
267
268function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
269 return [
270 "$ErrorActionPreference = 'Stop'",
271 ...names.flatMap((name) => {
272 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
273 throw new Error(`Unsupported environment variable name: ${name}`);
274 }
275
276 return [
277 `Write-Output '${envCaptureStart(name)}'`,
278 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
279 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
280 `Write-Output '${envCaptureEnd(name)}'`,
281 ];
282 }),
283 ].join("; ");
284}
285
286function extractEnvironmentValue(output: string, name: string): string | undefined {
287 const startMarker = envCaptureStart(name);
288 const endMarker = envCaptureEnd(name);
289 const startIndex = output.indexOf(startMarker);
290 if (startIndex === -1) return undefined;
291
292 const valueStartIndex = startIndex + startMarker.length;
293 const endIndex = output.indexOf(endMarker, valueStartIndex);
294 if (endIndex === -1) return undefined;
295
296 const value = output
297 .slice(valueStartIndex, endIndex)
298 .replace(/^\r?\n/, "")
299 .replace(/\r?\n$/, "");
300
301 return value.length > 0 ? value : undefined;
302}
303
304export type ShellEnvironmentReader = (
305 shell: string,
306 names: ReadonlyArray<string>,
307 execFile?: ExecFileSyncLike,
308) => Partial<Record<string, string>>;
309
310export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
311 shell,
312 names,
313 execFile = NodeChildProcess.execFileSync,
314) => {
315 if (names.length === 0) {
316 return {};
317 }
318
319 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
320 encoding: "utf8",
321 timeout: 5000,
322 });
323
324 const environment: Partial<Record<string, string>> = {};
325 for (const name of names) {
326 const value = extractEnvironmentValue(output, name);
327 if (value !== undefined) {
328 environment[name] = value;
329 }
330 }
331
332 return environment;
333};
334
335export type WindowsShellEnvironmentReader = (
336 names: ReadonlyArray<string>,
337 options?: WindowsEnvironmentProbeOptions,
338) => Partial<Record<string, string>>;
339
340export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
341 "@t3tools/shared/shell/WindowsShellEnvironment",
342 {
343 defaultValue: () => readEnvironmentFromWindowsShell,
344 },
345);
346
347export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
348 "@t3tools/shared/shell/CommandAvailability",
349 {
350 defaultValue: () => isCommandAvailable,
351 },
352);
353
354export function readEnvironmentFromWindowsShell(
355 names: ReadonlyArray<string>,
356 execFile?: ExecFileSyncLike,
357): Partial<Record<string, string>>;
358export function readEnvironmentFromWindowsShell(
359 names: ReadonlyArray<string>,
360 options?: WindowsEnvironmentProbeOptions,
361 execFile?: ExecFileSyncLike,
362): Partial<Record<string, string>>;
363export function readEnvironmentFromWindowsShell(
364 names: ReadonlyArray<string>,
365 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
366 maybeExecFile?: ExecFileSyncLike,
367): Partial<Record<string, string>> {
368 if (names.length === 0) {
369 return {};
370 }
371
372 const options =
373 typeof optionsOrExecFile === "function"
374 ? ({} satisfies WindowsEnvironmentProbeOptions)
375 : (optionsOrExecFile ?? {});
376 const execFile: ExecFileSyncLike =
377 typeof optionsOrExecFile === "function"
378 ? optionsOrExecFile
379 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
380 const command = buildWindowsEnvironmentCaptureCommand(names);
381 const args = [
382 "-NoLogo",
383 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
384 "-NonInteractive",
385 "-Command",
386 command,
387 ];
388 for (const shell of WINDOWS_SHELL_CANDIDATES) {
389 try {
390 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
391
392 const environment: Partial<Record<string, string>> = {};
393 for (const name of names) {
394 const value = extractEnvironmentValue(output, name);
395 if (value !== undefined) {
396 environment[name] = value;
397 }
398 }
399 return environment;
400 } catch {
401 continue;
402 }
403 }
404
405 return {};
406}
407
408function stripWrappingQuotes(value: string): string {
409 return value.replace(/^"+|"+$/g, "");
410}
411
412function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
413 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
414}
415
416function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
417 const normalized = stripWrappingQuotes(entry.trim());
418 return platform === "win32" ? normalized.toLowerCase() : normalized;
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 trimmed = entry.trim();
435 if (trimmed.length === 0) continue;
436
437 const normalized = normalizePathEntryForComparison(trimmed, platform);
438 if (normalized.length === 0 || seen.has(normalized)) continue;
439
440 seen.add(normalized);
441 merged.push(trimmed);
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});