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 Cache from "effect/Cache";
7import * as Clock from "effect/Clock";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12
13import * as HostProcess from "./HostProcess.ts";
14import * as Context from "effect/Context";
15const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
16const WINDOWS_PATH_DELIMITER = ";";
17const POSIX_PATH_DELIMITER = ":";
18const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
19
20type ExecFileSyncLike = (
21 file: string,
22 args: ReadonlyArray<string>,
23 options: { encoding: "utf8"; timeout: number },
24) => string;
25
26function canExecuteFile(filePath: string): boolean {
27 try {
28 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
29 return true;
30 } catch {
31 return false;
32 }
33}
34
35export interface CommandAvailabilityOptions {
36 readonly env?: NodeJS.ProcessEnv;
37 readonly extendEnv?: boolean;
38}
39
40export type CommandAvailabilityChecker = (
41 command: string,
42 options?: CommandAvailabilityOptions,
43) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
44
45const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
46
47/**
48 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
49 * on Windows). Node joins the command and arguments with spaces and hands the
50 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
51 * must be escaped to survive both cmd.exe parsing and the target program's
52 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
53 */
54function escapeWindowsShellArg(arg: string): string {
55 // Double up backslashes that precede a double quote, then escape the quote
56 // itself so it survives CommandLineToArgvW.
57 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
58 // Double up trailing backslashes so the closing quote is not escaped away.
59 escaped = escaped.replace(/(\\*)$/, "$1$1");
60 // Quote the whole argument so embedded whitespace is preserved.
61 escaped = `"${escaped}"`;
62 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
63 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
64}
65
66/**
67 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
68 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
69 * and returns the arguments untouched everywhere else.
70 */
71function sanitizeShellModeArgsForPlatform(
72 args: ReadonlyArray<string>,
73 platform: NodeJS.Platform,
74): Array<string> {
75 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
76}
77
78export interface ResolvedSpawnCommand {
79 readonly command: string;
80 readonly args: ReadonlyArray<string>;
81 readonly shell: boolean;
82}
83
84export type SpawnExecutableResolver = (
85 command: string,
86 platform: NodeJS.Platform,
87 env: NodeJS.ProcessEnv,
88) => string | undefined;
89
90function resolveSpawnExecutableWithNode(
91 command: string,
92 platform: NodeJS.Platform,
93 env: NodeJS.ProcessEnv,
94): string | undefined {
95 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
96 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
97 const candidates = resolveCommandCandidates(
98 command,
99 platform,
100 windowsPathExtensions,
101 path.extname,
102 );
103 const isExecutable = (candidate: string) => {
104 try {
105 if (!NodeFS.statSync(candidate).isFile()) return false;
106 if (platform === "win32") {
107 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
108 }
109 return canExecuteFile(candidate);
110 } catch {
111 return false;
112 }
113 };
114
115 if (command.includes("/") || command.includes("\\")) {
116 return candidates.find(isExecutable);
117 }
118
119 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
120 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
121 if (normalizedPathEntry.length === 0) continue;
122 for (const candidate of candidates) {
123 const candidatePath = path.join(normalizedPathEntry, candidate);
124 if (isExecutable(candidatePath)) return candidatePath;
125 }
126 }
127 return undefined;
128}
129
130export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
131 "@t3tools/shared/shell/SpawnExecutableResolution",
132 {
133 defaultValue: () => resolveSpawnExecutableWithNode,
134 },
135);
136
137export interface WindowsEnvironmentProbeOptions {
138 readonly loadProfile?: boolean;
139}
140
141function trimNonEmpty(value: string | null | undefined): string | undefined {
142 const trimmed = value?.trim();
143 return trimmed && trimmed.length > 0 ? trimmed : undefined;
144}
145
146function readUserLoginShell(): string | undefined {
147 try {
148 return trimNonEmpty(NodeOS.userInfo().shell);
149 } catch {
150 return undefined;
151 }
152}
153
154export function listLoginShellCandidates(
155 platform: NodeJS.Platform,
156 shell: string | undefined,
157 userShell = readUserLoginShell(),
158): ReadonlyArray<string> {
159 const fallbackShell =
160 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
161 const seen = new Set<string>();
162 const candidates: string[] = [];
163
164 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
165 if (!candidate || seen.has(candidate)) {
166 continue;
167 }
168 seen.add(candidate);
169 candidates.push(candidate);
170 }
171
172 return candidates;
173}
174
175export function readPathFromLaunchctl(
176 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
177): string | undefined {
178 try {
179 return trimNonEmpty(
180 execFile("/bin/launchctl", ["getenv", "PATH"], {
181 encoding: "utf8",
182 timeout: 2000,
183 }),
184 );
185 } catch {
186 return undefined;
187 }
188}
189
190export function mergePathEntries(
191 preferredPath: string | undefined,
192 inheritedPath: string | undefined,
193 platform: NodeJS.Platform,
194): string | undefined {
195 const delimiter = platform === "win32" ? ";" : ":";
196 const merged: string[] = [];
197 const seen = new Set<string>();
198
199 for (const pathValue of [preferredPath, inheritedPath]) {
200 if (!pathValue) continue;
201 for (const entry of pathValue.split(delimiter)) {
202 const trimmedEntry = entry.trim();
203 if (!trimmedEntry || seen.has(trimmedEntry)) {
204 continue;
205 }
206 seen.add(trimmedEntry);
207 merged.push(trimmedEntry);
208 }
209 }
210
211 return merged.length > 0 ? merged.join(delimiter) : undefined;
212}
213
214function envCaptureStart(name: string): string {
215 return `__T3CODE_ENV_${name}_START__`;
216}
217
218function envCaptureEnd(name: string): string {
219 return `__T3CODE_ENV_${name}_END__`;
220}
221
222function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
223 return names
224 .map((name) => {
225 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
226 throw new Error(`Unsupported environment variable name: ${name}`);
227 }
228
229 return [
230 `printf '%s\\n' '${envCaptureStart(name)}'`,
231 `printenv ${name} || true`,
232 `printf '%s\\n' '${envCaptureEnd(name)}'`,
233 ].join("; ");
234 })
235 .join("; ");
236}
237
238function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
239 return [
240 "$ErrorActionPreference = 'Stop'",
241 ...names.flatMap((name) => {
242 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
243 throw new Error(`Unsupported environment variable name: ${name}`);
244 }
245
246 return [
247 `Write-Output '${envCaptureStart(name)}'`,
248 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
249 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
250 `Write-Output '${envCaptureEnd(name)}'`,
251 ];
252 }),
253 ].join("; ");
254}
255
256function extractEnvironmentValue(output: string, name: string): string | undefined {
257 const startMarker = envCaptureStart(name);
258 const endMarker = envCaptureEnd(name);
259 const startIndex = output.indexOf(startMarker);
260 if (startIndex === -1) return undefined;
261
262 const valueStartIndex = startIndex + startMarker.length;
263 const endIndex = output.indexOf(endMarker, valueStartIndex);
264 if (endIndex === -1) return undefined;
265
266 const value = output
267 .slice(valueStartIndex, endIndex)
268 .replace(/^\r?\n/, "")
269 .replace(/\r?\n$/, "");
270
271 return value.length > 0 ? value : undefined;
272}
273
274export type ShellEnvironmentReader = (
275 shell: string,
276 names: ReadonlyArray<string>,
277 execFile?: ExecFileSyncLike,
278) => Partial<Record<string, string>>;
279
280export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
281 shell,
282 names,
283 execFile = NodeChildProcess.execFileSync,
284) => {
285 if (names.length === 0) {
286 return {};
287 }
288
289 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
290 encoding: "utf8",
291 timeout: 5000,
292 });
293
294 const environment: Partial<Record<string, string>> = {};
295 for (const name of names) {
296 const value = extractEnvironmentValue(output, name);
297 if (value !== undefined) {
298 environment[name] = value;
299 }
300 }
301
302 return environment;
303};
304
305export type WindowsShellEnvironmentReader = (
306 names: ReadonlyArray<string>,
307 options?: WindowsEnvironmentProbeOptions,
308) => Partial<Record<string, string>>;
309
310export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
311 "@t3tools/shared/shell/WindowsShellEnvironment",
312 {
313 defaultValue: () => readEnvironmentFromWindowsShell,
314 },
315);
316
317export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
318 "@t3tools/shared/shell/CommandAvailability",
319 {
320 defaultValue: () => isCommandAvailable,
321 },
322);
323
324export function readEnvironmentFromWindowsShell(
325 names: ReadonlyArray<string>,
326 execFile?: ExecFileSyncLike,
327): Partial<Record<string, string>>;
328export function readEnvironmentFromWindowsShell(
329 names: ReadonlyArray<string>,
330 options?: WindowsEnvironmentProbeOptions,
331 execFile?: ExecFileSyncLike,
332): Partial<Record<string, string>>;
333export function readEnvironmentFromWindowsShell(
334 names: ReadonlyArray<string>,
335 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
336 maybeExecFile?: ExecFileSyncLike,
337): Partial<Record<string, string>> {
338 if (names.length === 0) {
339 return {};
340 }
341
342 const options =
343 typeof optionsOrExecFile === "function"
344 ? ({} satisfies WindowsEnvironmentProbeOptions)
345 : (optionsOrExecFile ?? {});
346 const execFile: ExecFileSyncLike =
347 typeof optionsOrExecFile === "function"
348 ? optionsOrExecFile
349 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
350 const command = buildWindowsEnvironmentCaptureCommand(names);
351 const args = [
352 "-NoLogo",
353 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
354 "-NonInteractive",
355 "-Command",
356 command,
357 ];
358 for (const shell of WINDOWS_SHELL_CANDIDATES) {
359 try {
360 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
361
362 const environment: Partial<Record<string, string>> = {};
363 for (const name of names) {
364 const value = extractEnvironmentValue(output, name);
365 if (value !== undefined) {
366 environment[name] = value;
367 }
368 }
369 return environment;
370 } catch {
371 continue;
372 }
373 }
374
375 return {};
376}
377
378function stripWrappingQuotes(value: string): string {
379 return value.replace(/^"+|"+$/g, "");
380}
381
382function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
383 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
384}
385
386function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
387 const normalized = stripWrappingQuotes(entry.trim());
388 return platform === "win32" ? normalized.toLowerCase() : normalized;
389}
390
391function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
392 return platform === "win32" ? entry.replaceAll('"', "") : entry;
393}
394
395export function mergePathValues(
396 preferredPath: string | undefined,
397 inheritedPath: string | undefined,
398 platform: NodeJS.Platform,
399): string | undefined {
400 const delimiter = pathDelimiterForPlatform(platform);
401 const merged: string[] = [];
402 const seen = new Set<string>();
403
404 for (const rawValue of [preferredPath, inheritedPath]) {
405 if (!rawValue) continue;
406
407 for (const entry of rawValue.split(delimiter)) {
408 const sanitized = sanitizePathEntry(entry.trim(), platform);
409 if (sanitized.length === 0) continue;
410
411 const normalized = normalizePathEntryForComparison(sanitized, platform);
412 if (normalized.length === 0 || seen.has(normalized)) continue;
413
414 seen.add(normalized);
415 merged.push(sanitized);
416 }
417 }
418
419 return merged.length > 0 ? merged.join(delimiter) : undefined;
420}
421
422function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
423 return env.PATH ?? env.Path ?? env.path;
424}
425
426function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
427 return readEnvPath(env) ?? "";
428}
429
430function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
431 const rawValue = env.PATHEXT;
432 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
433 if (!rawValue) return fallback;
434
435 const parsed: string[] = [];
436 for (const entry of rawValue.split(";")) {
437 const trimmed = entry.trim();
438 if (trimmed.length === 0) continue;
439 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
440 }
441 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
442}
443
444function resolveCommandCandidates(
445 command: string,
446 platform: NodeJS.Platform,
447 windowsPathExtensions: ReadonlyArray<string>,
448 extname: (path: string) => string,
449): ReadonlyArray<string> {
450 if (platform !== "win32") return [command];
451 const extension = extname(command);
452 const normalizedExtension = extension.toUpperCase();
453
454 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
455 const commandWithoutExtension = command.slice(0, -extension.length);
456 return Array.from(
457 new Set([
458 command,
459 `${commandWithoutExtension}${normalizedExtension}`,
460 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
461 ]),
462 );
463 }
464
465 const candidates: string[] = [];
466 for (const candidateExtension of windowsPathExtensions) {
467 candidates.push(`${command}${candidateExtension}`);
468 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
469 }
470 return Array.from(new Set(candidates));
471}
472
473// Session bootstrap resolves the same commands over and over, each PATH scan
474// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of
475// thousands per connect). Memoize the scan outcome per
476// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the
477// cache while any change to the search environment invalidates immediately.
478// Explicit-path resolution is never cached - callers probe paths they have
479// just written (e.g. managed binary installs). A "not-found" outcome is also
480// cached for the TTL, so a just-installed binary can stay invisible for up to
481// 30s unless resolved by explicit path.
482// TTL expiry uses the monotonic clock (Clock.monotonicTimeNanos) so backward
483// wall-clock adjustments cannot keep expired entries alive.
484const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
485const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
486const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
487
488interface CommandResolutionCacheEntry {
489 readonly resolvedPath: string | null;
490 readonly expiresAtNanos: bigint;
491}
492
493// The cache lives in the Effect environment (like HostProcess.Platform above)
494// so tests and embedders can provide an isolated instance; the default is a
495// single process-wide map shared by all consumers.
496export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
497 "@t3tools/shared/shell/CommandResolutionCache",
498 {
499 defaultValue: () => new Map(),
500 },
501);
502
503interface PathDirectoryListing {
504 readonly modified: number | null | undefined;
505 readonly names: ReadonlySet<string> | undefined;
506}
507
508// mtime of a PATH directory; null when missing, undefined when unreadable.
509const directoryMtime = (directory: string) =>
510 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
511 Effect.map((info) =>
512 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
513 ),
514 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
515 );
516
517// Dated before it is read, so an entry added in between changes the mtime seen
518// on the next check. Without names, lookups probe candidates directly.
519const listPathDirectory = Effect.fnUntraced(function* (
520 directory: string,
521): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
522 const modified = yield* directoryMtime(directory);
523 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
524 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
525 fileSystem.readDirectory(directory),
526 ).pipe(Effect.orElseSucceed(() => undefined));
527 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
528});
529
530const PathDirectoryListings = Context.Reference<
531 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
532>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
533
534/**
535 * Run a batch of command lookups (e.g. editor discovery) that lists each PATH
536 * directory once, relisting it if its mtime changes, and probes only listed
537 * names instead of every PATH x PATHEXT candidate per command.
538 */
539export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
540 Effect.gen(function* () {
541 const listings = yield* Cache.make({
542 capacity: 1024,
543 lookup: listPathDirectory,
544 requireServicesAt: "lookup",
545 });
546 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
547 });
548
549// An injected resolver may answer differently for the same search, so its
550// entries are kept apart from every other resolver's.
551let spawnResolverCacheIdCount = 0;
552const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
553function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
554 const known = spawnResolverCacheIds.get(resolver);
555 if (known !== undefined) return known;
556 const id = spawnResolverCacheIdCount++;
557 spawnResolverCacheIds.set(resolver, id);
558 return id;
559}
560
561function cacheCommandResolution(
562 cache: Map<string, CommandResolutionCacheEntry>,
563 cacheKey: string,
564 resolvedPath: string | null,
565 nowNanos: bigint,
566): void {
567 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
568 const oldestKey = cache.keys().next().value;
569 if (oldestKey !== undefined) {
570 cache.delete(oldestKey);
571 }
572 }
573 cache.set(cacheKey, {
574 resolvedPath,
575 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
576 });
577}
578
579// Trace each command lookup, not every candidate file it probes.
580const isExecutableFile = Effect.fnUntraced(function* (
581 filePath: string,
582 platform: NodeJS.Platform,
583 windowsPathExtensions: ReadonlyArray<string>,
584): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
585 const fileSystem = yield* FileSystem.FileSystem;
586 const path = yield* Path.Path;
587 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
588 if (stat === null || stat.type !== "File") return false;
589
590 if (platform === "win32") {
591 const extension = path.extname(filePath);
592 if (extension.length === 0) return false;
593 return windowsPathExtensions.includes(extension.toUpperCase());
594 }
595
596 return canExecuteFile(filePath);
597});
598
599const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
600 command: string,
601 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
602): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
603 const path = yield* Path.Path;
604 const platform = options.platform;
605 const env = options.env ?? process.env;
606 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
607 const commandCandidates = resolveCommandCandidates(
608 command,
609 platform,
610 windowsPathExtensions,
611 path.extname,
612 );
613
614 if (command.includes("/") || command.includes("\\")) {
615 for (const candidate of commandCandidates) {
616 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
617 return candidate;
618 }
619 }
620 return null;
621 }
622
623 const pathValue = resolvePathEnvironmentVariable(env);
624 if (pathValue.length === 0) {
625 return null;
626 }
627
628 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
629 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
630 );
631 const cache = yield* CommandResolutionCache;
632 const nowNanos = yield* Clock.monotonicTimeNanos;
633 const cached = cache.get(cacheKey);
634 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
635 return cached.resolvedPath;
636 }
637
638 // Keep case variants: Windows can make PATH directories case-sensitive.
639 const pathEntries: string[] = [];
640 const seenPathEntries = new Set<string>();
641 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
642 const pathEntry = stripWrappingQuotes(entry.trim());
643 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
644
645 seenPathEntries.add(pathEntry);
646 pathEntries.push(pathEntry);
647 }
648
649 const listings = yield* PathDirectoryListings;
650 for (const pathEntry of pathEntries) {
651 let listing = listings && (yield* Cache.get(listings, pathEntry));
652 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
653 yield* Cache.invalidate(listings, pathEntry);
654 listing = yield* Cache.get(listings, pathEntry);
655 }
656 for (const candidate of commandCandidates) {
657 // The stat below still checks exact case and rejects non-files.
658 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
659 const candidatePath = path.join(pathEntry, candidate);
660 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
661 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
662 return candidatePath;
663 }
664 }
665 }
666 cacheCommandResolution(cache, cacheKey, null, nowNanos);
667 return null;
668});
669
670export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
671 command: string,
672 options: CommandAvailabilityOptions = {},
673) {
674 return yield* resolveCommandPathForPlatform(command, {
675 env: options.env ?? (yield* HostProcess.Environment),
676 platform: yield* HostProcess.Platform,
677 });
678});
679
680// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
681// live in clangarm64 and 32-bit ones in mingw32.
682const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
683
684function isFileSync(filePath: string): boolean {
685 try {
686 return NodeFS.statSync(filePath).isFile();
687 } catch {
688 return false;
689 }
690}
691
692/**
693 * Swaps Git for Windows' launcher (`<Git>\cmd\git.exe`, the only git its
694 * installer puts on PATH, or the portable build's `<Git>\bin\git.exe`) for the
695 * git.exe it starts. The launcher costs a second process on every git command,
696 * and each launch leaks a kernel token reference that slows process creation
697 * machine-wide until reboot. The real binary sets HOME itself, but adds its own
698 * folders to PATH for hooks, ssh and credential helpers only when MSYSTEM is
699 * unset, so the launcher stays when MSYSTEM is set. Anything else is returned
700 * as is.
701 */
702export function preferGitForWindowsBinary(
703 executable: string,
704 env: NodeJS.ProcessEnv,
705 isFile: (filePath: string) => boolean = isFileSync,
706): string {
707 if (env.MSYSTEM) return executable;
708 const path = NodePath.win32;
709 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
710 const launcherDirectory = path.dirname(executable);
711 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
712 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
713 const installRoot = path.dirname(launcherDirectory);
714 for (const build of GIT_FOR_WINDOWS_BUILDS) {
715 const candidate = path.join(installRoot, build, "bin", "git.exe");
716 if (isFile(candidate)) return candidate;
717 }
718 return executable;
719}
720
721// Untraced because it runs before most spawns and returns at once off Windows.
722export const resolveSpawnCommand = Effect.fnUntraced(function* (
723 command: string,
724 args: ReadonlyArray<string>,
725 options: CommandAvailabilityOptions = {},
726): Effect.fn.Return<ResolvedSpawnCommand> {
727 const platform = yield* HostProcess.Platform;
728 if (platform !== "win32") {
729 return { command, args: [...args], shell: false };
730 }
731
732 const hostEnvironment = yield* HostProcess.Environment;
733 const env =
734 options.env === undefined
735 ? hostEnvironment
736 : options.extendEnv
737 ? { ...hostEnvironment, ...options.env }
738 : options.env;
739 const resolveExecutable = yield* SpawnExecutableResolution;
740 // The scan is synchronous and runs before every child process, so it shares
741 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
742 // and so do misses: a failed spawn is how providers report "not installed",
743 // and that has to clear the moment the binary appears.
744 const explicitPath = command.includes("/") || command.includes("\\");
745 const cache = yield* CommandResolutionCache;
746 const cacheKey = [
747 "spawn",
748 String(spawnResolverCacheId(resolveExecutable)),
749 platform,
750 resolvePathEnvironmentVariable(env),
751 resolveWindowsPathExtensions(env).join(";"),
752 env.MSYSTEM ? "msystem" : "",
753 command,
754 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
755 const nowNanos = yield* Clock.currentTimeNanos;
756 const cached = explicitPath ? undefined : cache.get(cacheKey);
757 let resolvedExecutable: string | null;
758 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
759 resolvedExecutable = cached.resolvedPath;
760 } else {
761 // Cached with the scan: its file checks would otherwise run before every
762 // git launch. A Git upgrade that moves the real binary can fail git for up
763 // to the cache lifetime.
764 const found = resolveExecutable(command, platform, env);
765 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
766 if (!explicitPath && resolvedExecutable !== null) {
767 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
768 }
769 }
770 const resolvedCommand = resolvedExecutable ?? command;
771 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
772 if (extension !== ".cmd" && extension !== ".bat") {
773 return { command: resolvedCommand, args: [...args], shell: false };
774 }
775
776 return {
777 command: escapeWindowsShellArg(resolvedCommand),
778 args: sanitizeShellModeArgsForPlatform(args, platform),
779 shell: true,
780 };
781});
782
783export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
784 command: string,
785 options: CommandAvailabilityOptions = {},
786) {
787 return (yield* resolveCommandPath(command, options)) !== null;
788});
789
790export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
791 const appData = env.APPDATA?.trim();
792 const localAppData = env.LOCALAPPDATA?.trim();
793 const userProfile = env.USERPROFILE?.trim();
794
795 return [
796 ...(appData ? [`${appData}\\npm`] : []),
797 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
798 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
799 ...(userProfile
800 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
801 : []),
802 ];
803}
804
805function readWindowsEnvironmentSafely(
806 readEnvironment: WindowsShellEnvironmentReader,
807 names: ReadonlyArray<string>,
808 options?: WindowsEnvironmentProbeOptions,
809): Partial<Record<string, string>> {
810 try {
811 return readEnvironment(names, options);
812 } catch {
813 return {};
814 }
815}
816
817function mergeWindowsEnv(
818 currentEnv: NodeJS.ProcessEnv,
819 patch: Partial<Record<string, string>>,
820): NodeJS.ProcessEnv {
821 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
822 for (const [key, value] of Object.entries(patch)) {
823 if (value !== undefined) {
824 nextEnv[key] = value;
825 }
826 }
827 return nextEnv;
828}
829
830export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
831 env: NodeJS.ProcessEnv,
832): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
833 const readEnvironment = yield* WindowsShellEnvironment;
834 const commandAvailable = yield* CommandAvailability;
835 const inheritedPath = readEnvPath(env);
836 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
837 loadProfile: false,
838 }).PATH;
839 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
840 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
841 // Preserve the order a user's shell uses. These directories fill gaps when
842 // desktop apps launch without the full interactive-shell PATH.
843 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
844 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
845 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
846
847 if (yield* commandAvailable("node", { env: baselineEnv })) {
848 return baselinePatch;
849 }
850
851 const profiledEnvironment = readWindowsEnvironmentSafely(
852 readEnvironment,
853 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
854 { loadProfile: true },
855 );
856 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
857 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
858 ...(profiledPath ? { PATH: profiledPath } : {}),
859 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
860 ...(profiledEnvironment.FNM_MULTISHELL_PATH
861 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
862 : {}),
863 };
864 return Object.keys(profiledPatch).length > 0
865 ? { ...baselinePatch, ...profiledPatch }
866 : baselinePatch;
867});