Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell.ts

874 lines29.9 KB

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