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: {
24 encoding: "utf8";
25 timeout: number;
26 detached?: true;
27 stdio?: ["ignore", "pipe", "ignore"];
28 },
29) => string;
30
31function canExecuteFile(filePath: string): boolean {
32 try {
33 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
34 return true;
35 } catch {
36 return false;
37 }
38}
39
40export interface CommandAvailabilityOptions {
41 readonly env?: NodeJS.ProcessEnv;
42 readonly extendEnv?: boolean;
43}
44
45export type CommandAvailabilityChecker = (
46 command: string,
47 options?: CommandAvailabilityOptions,
48) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
49
50const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
51
52/**
53 * Node hands the command string to `cmd.exe /d /s /c "<command>"` without any
54 * quoting, so every dynamic argument must be escaped to survive both cmd.exe
55 * parsing and the target program's `CommandLineToArgvW` parsing.
56 */
57function escapeWindowsShellArg(arg: string): string {
58 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
59 // Double up trailing backslashes so the closing quote is not escaped away.
60 escaped = escaped.replace(/(\\*)$/, "$1$1");
61 escaped = `"${escaped}"`;
62 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
63}
64
65export interface ResolvedSpawnCommand {
66 readonly command: string;
67 readonly args: ReadonlyArray<string>;
68 readonly shell: boolean;
69}
70
71export type SpawnExecutableResolver = (
72 command: string,
73 platform: NodeJS.Platform,
74 env: NodeJS.ProcessEnv,
75) => string | undefined;
76
77function resolveSpawnExecutableWithNode(
78 command: string,
79 platform: NodeJS.Platform,
80 env: NodeJS.ProcessEnv,
81): string | undefined {
82 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
83 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
84 const candidates = resolveCommandCandidates(
85 command,
86 platform,
87 windowsPathExtensions,
88 path.extname,
89 );
90 const isExecutable = (candidate: string) => {
91 try {
92 if (!NodeFS.statSync(candidate).isFile()) return false;
93 if (platform === "win32") {
94 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
95 }
96 return canExecuteFile(candidate);
97 } catch {
98 return false;
99 }
100 };
101
102 if (command.includes("/") || command.includes("\\")) {
103 return candidates.find(isExecutable);
104 }
105
106 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
107 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
108 if (normalizedPathEntry.length === 0) continue;
109 for (const candidate of candidates) {
110 const candidatePath = path.join(normalizedPathEntry, candidate);
111 if (isExecutable(candidatePath)) return candidatePath;
112 }
113 }
114 return undefined;
115}
116
117export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
118 "@t3tools/shared/shell/SpawnExecutableResolution",
119 {
120 defaultValue: () => resolveSpawnExecutableWithNode,
121 },
122);
123
124export interface WindowsEnvironmentProbeOptions {
125 readonly loadProfile?: boolean;
126}
127
128function trimNonEmpty(value: string | null | undefined): string | undefined {
129 const trimmed = value?.trim();
130 return trimmed && trimmed.length > 0 ? trimmed : undefined;
131}
132
133function readUserLoginShell(): string | undefined {
134 try {
135 return trimNonEmpty(NodeOS.userInfo().shell);
136 } catch {
137 return undefined;
138 }
139}
140
141export function listLoginShellCandidates(
142 platform: NodeJS.Platform,
143 shell: string | undefined,
144 userShell = readUserLoginShell(),
145): ReadonlyArray<string> {
146 const fallbackShell =
147 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
148 const seen = new Set<string>();
149 const candidates: string[] = [];
150
151 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
152 if (!candidate || seen.has(candidate)) {
153 continue;
154 }
155 seen.add(candidate);
156 candidates.push(candidate);
157 }
158
159 return candidates;
160}
161
162export function readPathFromLaunchctl(
163 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
164): string | undefined {
165 try {
166 return trimNonEmpty(
167 execFile("/bin/launchctl", ["getenv", "PATH"], {
168 encoding: "utf8",
169 timeout: 2000,
170 }),
171 );
172 } catch {
173 return undefined;
174 }
175}
176
177export function mergePathEntries(
178 preferredPath: string | undefined,
179 inheritedPath: string | undefined,
180 platform: NodeJS.Platform,
181): string | undefined {
182 const delimiter = platform === "win32" ? ";" : ":";
183 const merged: string[] = [];
184 const seen = new Set<string>();
185
186 for (const pathValue of [preferredPath, inheritedPath]) {
187 if (!pathValue) continue;
188 for (const entry of pathValue.split(delimiter)) {
189 const trimmedEntry = entry.trim();
190 if (!trimmedEntry || seen.has(trimmedEntry)) {
191 continue;
192 }
193 seen.add(trimmedEntry);
194 merged.push(trimmedEntry);
195 }
196 }
197
198 return merged.length > 0 ? merged.join(delimiter) : undefined;
199}
200
201function envCaptureStart(name: string): string {
202 return `__T3CODE_ENV_${name}_START__`;
203}
204
205function envCaptureEnd(name: string): string {
206 return `__T3CODE_ENV_${name}_END__`;
207}
208
209export function buildEnvironmentCaptureCommand(
210 shell: string,
211 names: ReadonlyArray<string>,
212): string {
213 const executableName = NodePath.basename(shell).toLowerCase();
214 const isNushell = executableName.startsWith("nu");
215
216 return names
217 .map((name) => {
218 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
219 throw new Error(`Unsupported environment variable name: ${name}`);
220 }
221
222 if (isNushell) {
223 // Without a configured conversion, Nu expands home paths only in a list PATH.
224 const defaultValue =
225 name === "PATH"
226 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
227 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
228 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
229 "} else { $env.PATH? | default '' }"
230 : `$env.${name}? | default ''`;
231 const value =
232 `if $env.${name}? == null { '' } else if ` +
233 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
234 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
235 `} else { ${defaultValue} }`;
236 return [
237 `print '${envCaptureStart(name)}'`,
238 `print (${value})`,
239 `print '${envCaptureEnd(name)}'`,
240 ].join("; ");
241 }
242
243 return [
244 `printf '%s\\n' '${envCaptureStart(name)}'`,
245 `printenv ${name} || true`,
246 `printf '%s\\n' '${envCaptureEnd(name)}'`,
247 ].join("; ");
248 })
249 .join("; ");
250}
251
252function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
253 return [
254 "$ErrorActionPreference = 'Stop'",
255 ...names.flatMap((name) => {
256 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
257 throw new Error(`Unsupported environment variable name: ${name}`);
258 }
259
260 return [
261 `Write-Output '${envCaptureStart(name)}'`,
262 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
263 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
264 `Write-Output '${envCaptureEnd(name)}'`,
265 ];
266 }),
267 ].join("; ");
268}
269
270function extractEnvironmentValue(output: string, name: string): string | undefined {
271 const startMarker = envCaptureStart(name);
272 const endMarker = envCaptureEnd(name);
273 const startIndex = output.indexOf(startMarker);
274 if (startIndex === -1) return undefined;
275
276 const valueStartIndex = startIndex + startMarker.length;
277 const endIndex = output.indexOf(endMarker, valueStartIndex);
278 if (endIndex === -1) return undefined;
279
280 const value = output
281 .slice(valueStartIndex, endIndex)
282 .replace(/^\r?\n/, "")
283 .replace(/\r?\n$/, "");
284
285 return value.length > 0 ? value : undefined;
286}
287
288export type ShellEnvironmentReader = (
289 shell: string,
290 names: ReadonlyArray<string>,
291 execFile?: ExecFileSyncLike,
292) => Partial<Record<string, string>>;
293
294export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
295 shell,
296 names,
297 execFile = NodeChildProcess.execFileSync,
298) => {
299 if (names.length === 0) {
300 return {};
301 }
302
303 // Interactive startup loads PATH entries; detaching prevents job control on an
304 // inherited controlling TTY from stopping the probe while the parent waits.
305 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
306 encoding: "utf8",
307 timeout: 5000,
308 detached: true,
309 stdio: ["ignore", "pipe", "ignore"],
310 });
311
312 const environment: Partial<Record<string, string>> = {};
313 for (const name of names) {
314 const value = extractEnvironmentValue(output, name);
315 if (value !== undefined) {
316 environment[name] = value;
317 }
318 }
319
320 return environment;
321};
322
323export type WindowsShellEnvironmentReader = (
324 names: ReadonlyArray<string>,
325 options?: WindowsEnvironmentProbeOptions,
326) => Partial<Record<string, string>>;
327
328export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
329 "@t3tools/shared/shell/WindowsShellEnvironment",
330 {
331 defaultValue: () => readEnvironmentFromWindowsShell,
332 },
333);
334
335export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
336 "@t3tools/shared/shell/CommandAvailability",
337 {
338 defaultValue: () => isCommandAvailable,
339 },
340);
341
342export function readEnvironmentFromWindowsShell(
343 names: ReadonlyArray<string>,
344 execFile?: ExecFileSyncLike,
345): Partial<Record<string, string>>;
346export function readEnvironmentFromWindowsShell(
347 names: ReadonlyArray<string>,
348 options?: WindowsEnvironmentProbeOptions,
349 execFile?: ExecFileSyncLike,
350): Partial<Record<string, string>>;
351export function readEnvironmentFromWindowsShell(
352 names: ReadonlyArray<string>,
353 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
354 maybeExecFile?: ExecFileSyncLike,
355): Partial<Record<string, string>> {
356 if (names.length === 0) {
357 return {};
358 }
359
360 const options =
361 typeof optionsOrExecFile === "function"
362 ? ({} satisfies WindowsEnvironmentProbeOptions)
363 : (optionsOrExecFile ?? {});
364 const execFile: ExecFileSyncLike =
365 typeof optionsOrExecFile === "function"
366 ? optionsOrExecFile
367 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
368 const command = buildWindowsEnvironmentCaptureCommand(names);
369 const args = [
370 "-NoLogo",
371 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
372 "-NonInteractive",
373 "-Command",
374 command,
375 ];
376 for (const shell of WINDOWS_SHELL_CANDIDATES) {
377 try {
378 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
379
380 const environment: Partial<Record<string, string>> = {};
381 for (const name of names) {
382 const value = extractEnvironmentValue(output, name);
383 if (value !== undefined) {
384 environment[name] = value;
385 }
386 }
387 return environment;
388 } catch {
389 continue;
390 }
391 }
392
393 return {};
394}
395
396function stripWrappingQuotes(value: string): string {
397 return value.replace(/^"+|"+$/g, "");
398}
399
400function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
401 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
402}
403
404function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
405 const normalized = stripWrappingQuotes(entry.trim());
406 return platform === "win32" ? normalized.toLowerCase() : normalized;
407}
408
409function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
410 return platform === "win32" ? entry.replaceAll('"', "") : entry;
411}
412
413export function mergePathValues(
414 preferredPath: string | undefined,
415 inheritedPath: string | undefined,
416 platform: NodeJS.Platform,
417): string | undefined {
418 const delimiter = pathDelimiterForPlatform(platform);
419 const merged: string[] = [];
420 const seen = new Set<string>();
421
422 for (const rawValue of [preferredPath, inheritedPath]) {
423 if (!rawValue) continue;
424
425 for (const entry of rawValue.split(delimiter)) {
426 const sanitized = sanitizePathEntry(entry.trim(), platform);
427 if (sanitized.length === 0) continue;
428
429 const normalized = normalizePathEntryForComparison(sanitized, platform);
430 if (normalized.length === 0 || seen.has(normalized)) continue;
431
432 seen.add(normalized);
433 merged.push(sanitized);
434 }
435 }
436
437 return merged.length > 0 ? merged.join(delimiter) : undefined;
438}
439
440function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
441 return env.PATH ?? env.Path ?? env.path;
442}
443
444function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
445 return readEnvPath(env) ?? "";
446}
447
448function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
449 const rawValue = env.PATHEXT;
450 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
451 if (!rawValue) return fallback;
452
453 const parsed: string[] = [];
454 for (const entry of rawValue.split(";")) {
455 const trimmed = entry.trim();
456 if (trimmed.length === 0) continue;
457 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
458 }
459 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
460}
461
462function resolveCommandCandidates(
463 command: string,
464 platform: NodeJS.Platform,
465 windowsPathExtensions: ReadonlyArray<string>,
466 extname: (path: string) => string,
467): ReadonlyArray<string> {
468 if (platform !== "win32") return [command];
469 const extension = extname(command);
470 const normalizedExtension = extension.toUpperCase();
471
472 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
473 const commandWithoutExtension = command.slice(0, -extension.length);
474 return Array.from(
475 new Set([
476 command,
477 `${commandWithoutExtension}${normalizedExtension}`,
478 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
479 ]),
480 );
481 }
482
483 const candidates: string[] = [];
484 for (const candidateExtension of windowsPathExtensions) {
485 candidates.push(`${command}${candidateExtension}`);
486 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
487 }
488 return Array.from(new Set(candidates));
489}
490
491// Explicit-path resolution is never cached - callers probe paths they have
492// just written (e.g. managed binary installs). A "not-found" outcome is also
493// cached for the TTL, so a just-installed binary can stay invisible for up to
494// 30s unless resolved by explicit path.
495const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
496const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
497const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
498
499interface CommandResolutionCacheEntry {
500 readonly resolvedPath: string | null;
501 readonly expiresAtNanos: bigint;
502}
503
504export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
505 "@t3tools/shared/shell/CommandResolutionCache",
506 {
507 defaultValue: () => new Map(),
508 },
509);
510
511interface PathDirectoryListing {
512 readonly modified: number | null | undefined;
513 readonly names: ReadonlySet<string> | undefined;
514}
515
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
541export const withPathDirectoryListings =
542 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
543 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
544 const listings = yield* Cache.make({
545 capacity: 1024,
546 lookup: listPathDirectory,
547 requireServicesAt: "lookup",
548 });
549 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
550 });
551
552// An injected resolver may answer differently for the same search, so its
553// entries are kept apart from every other resolver's.
554let spawnResolverCacheIdCount = 0;
555const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
556function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
557 const known = spawnResolverCacheIds.get(resolver);
558 if (known !== undefined) return known;
559 const id = spawnResolverCacheIdCount++;
560 spawnResolverCacheIds.set(resolver, id);
561 return id;
562}
563
564function cacheCommandResolution(
565 cache: Map<string, CommandResolutionCacheEntry>,
566 cacheKey: string,
567 resolvedPath: string | null,
568 nowNanos: bigint,
569): void {
570 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
571 const oldestKey = cache.keys().next().value;
572 if (oldestKey !== undefined) {
573 cache.delete(oldestKey);
574 }
575 }
576 cache.set(cacheKey, {
577 resolvedPath,
578 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
579 });
580}
581
582const isExecutableFile = Effect.fnUntraced(function* (
583 filePath: string,
584 platform: NodeJS.Platform,
585 windowsPathExtensions: ReadonlyArray<string>,
586): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
587 const fileSystem = yield* FileSystem.FileSystem;
588 const path = yield* Path.Path;
589 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
590 if (stat === null || stat.type !== "File") return false;
591
592 if (platform === "win32") {
593 const extension = path.extname(filePath);
594 if (extension.length === 0) return false;
595 return windowsPathExtensions.includes(extension.toUpperCase());
596 }
597
598 return canExecuteFile(filePath);
599});
600
601const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
602 command: string,
603 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
604): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
605 const path = yield* Path.Path;
606 const platform = options.platform;
607 const env = options.env ?? process.env;
608 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
609 const commandCandidates = resolveCommandCandidates(
610 command,
611 platform,
612 windowsPathExtensions,
613 path.extname,
614 );
615
616 if (command.includes("/") || command.includes("\\")) {
617 for (const candidate of commandCandidates) {
618 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
619 return candidate;
620 }
621 }
622 return null;
623 }
624
625 const pathValue = resolvePathEnvironmentVariable(env);
626 if (pathValue.length === 0) {
627 return null;
628 }
629
630 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
631 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
632 );
633 const cache = yield* CommandResolutionCache;
634 const nowNanos = yield* Clock.monotonicTimeNanos;
635 const cached = cache.get(cacheKey);
636 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
637 return cached.resolvedPath;
638 }
639
640 // Keep case variants: Windows can make PATH directories case-sensitive.
641 const pathEntries: string[] = [];
642 const seenPathEntries = new Set<string>();
643 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
644 const pathEntry = stripWrappingQuotes(entry.trim());
645 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
646
647 seenPathEntries.add(pathEntry);
648 pathEntries.push(pathEntry);
649 }
650
651 const listings = yield* PathDirectoryListings;
652 for (const pathEntry of pathEntries) {
653 let listing = listings && (yield* Cache.get(listings, pathEntry));
654 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
655 yield* Cache.invalidate(listings, pathEntry);
656 listing = yield* Cache.get(listings, pathEntry);
657 }
658 for (const candidate of commandCandidates) {
659 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
660 const candidatePath = path.join(pathEntry, candidate);
661 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
662 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
663 return candidatePath;
664 }
665 }
666 }
667 cacheCommandResolution(cache, cacheKey, null, nowNanos);
668 return null;
669});
670
671export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
672 command: string,
673 options: CommandAvailabilityOptions = {},
674) {
675 return yield* resolveCommandPathForPlatform(command, {
676 env: options.env ?? (yield* HostProcess.Environment),
677 platform: yield* HostProcess.Platform,
678 });
679});
680
681// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
682// live in clangarm64 and 32-bit ones in mingw32.
683const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
684
685function isFileSync(filePath: string): boolean {
686 try {
687 return NodeFS.statSync(filePath).isFile();
688 } catch {
689 return false;
690 }
691}
692
693/**
694 * The launcher costs a second process on every git command, and each launch
695 * leaks a kernel token reference that slows process creation machine-wide until
696 * reboot. The real binary sets HOME itself, but adds its own folders to PATH
697 * for hooks, ssh and credential helpers only when MSYSTEM is unset, so the
698 * launcher stays when MSYSTEM is set.
699 */
700export function preferGitForWindowsBinary(
701 executable: string,
702 env: NodeJS.ProcessEnv,
703 isFile: (filePath: string) => boolean = isFileSync,
704): string {
705 if (env.MSYSTEM) return executable;
706 const path = NodePath.win32;
707 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
708 const launcherDirectory = path.dirname(executable);
709 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
710 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
711 const installRoot = path.dirname(launcherDirectory);
712 for (const build of GIT_FOR_WINDOWS_BUILDS) {
713 const candidate = path.join(installRoot, build, "bin", "git.exe");
714 if (isFile(candidate)) return candidate;
715 }
716 return executable;
717}
718
719// What npm's cmd-shim writes for a package whose bin is a native executable.
720const NPM_EXECUTABLE_SHIM_PREFIX = [
721 "@ECHO off",
722 "GOTO start",
723 ":find_dp0",
724 "SET dp0=%~dp0",
725 "EXIT /b",
726 ":start",
727 "SETLOCAL",
728 "CALL :find_dp0",
729];
730const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
731
732function readFileSyncOrUndefined(filePath: string): string | undefined {
733 try {
734 return NodeFS.readFileSync(filePath, "utf8");
735 } catch {
736 return undefined;
737 }
738}
739
740/**
741 * The executable an npm cmd-shim runs, when the shim does nothing else.
742 * Started through the shim, the executable is a child of `cmd.exe` and so
743 * escapes the kill-on-close job libuv puts every child in: it keeps running
744 * after this process is killed. Started directly it is in the job.
745 */
746export function npmShimExecutable(
747 shimPath: string,
748 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
749 isFile: (filePath: string) => boolean = isFileSync,
750): string | undefined {
751 const path = NodePath.win32;
752 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
753 // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would
754 // make it run a different file than the one found here.
755 const lines = readFile(shimPath)
756 ?.split(/\r?\n/)
757 .filter((line) => line.length > 0);
758 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
759 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
760 return undefined;
761 }
762 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
763 if (target === undefined) return undefined;
764 const executable = path.join(path.dirname(shimPath), target);
765 return isFile(executable) ? executable : undefined;
766}
767
768export interface SpawnCommandOptions extends CommandAvailabilityOptions {
769 /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
770 readonly bypassNpmShim?: boolean;
771}
772
773export const resolveSpawnCommand = Effect.fnUntraced(function* (
774 command: string,
775 args: ReadonlyArray<string>,
776 options: SpawnCommandOptions = {},
777): Effect.fn.Return<ResolvedSpawnCommand> {
778 const platform = yield* HostProcess.Platform;
779 if (platform !== "win32") {
780 return { command, args: [...args], shell: false };
781 }
782
783 const hostEnvironment = yield* HostProcess.Environment;
784 const env =
785 options.env === undefined
786 ? hostEnvironment
787 : options.extendEnv
788 ? { ...hostEnvironment, ...options.env }
789 : options.env;
790 const resolveExecutable = yield* SpawnExecutableResolution;
791 // The scan is synchronous and runs before every child process, so it shares
792 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
793 // and so do misses: a failed spawn is how providers report "not installed",
794 // and that has to clear the moment the binary appears.
795 const explicitPath = command.includes("/") || command.includes("\\");
796 const cache = yield* CommandResolutionCache;
797 const cacheKey = [
798 "spawn",
799 String(spawnResolverCacheId(resolveExecutable)),
800 platform,
801 resolvePathEnvironmentVariable(env),
802 resolveWindowsPathExtensions(env).join(";"),
803 env.MSYSTEM ? "msystem" : "",
804 command,
805 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
806 const nowNanos = yield* Clock.currentTimeNanos;
807 const cached = explicitPath ? undefined : cache.get(cacheKey);
808 let resolvedExecutable: string | null;
809 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
810 resolvedExecutable = cached.resolvedPath;
811 } else {
812 const found = resolveExecutable(command, platform, env);
813 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
814 if (!explicitPath && resolvedExecutable !== null) {
815 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
816 }
817 }
818 const resolvedCommand = resolvedExecutable ?? command;
819 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
820 if (extension !== ".cmd" && extension !== ".bat") {
821 return { command: resolvedCommand, args: [...args], shell: false };
822 }
823 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
824 if (shimExecutable !== undefined) {
825 return { command: shimExecutable, args: [...args], shell: false };
826 }
827
828 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
829 // passing args with `shell: true` prints DEP0190. Build the same escaped line
830 // here and pass no args.
831 return {
832 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
833 args: [],
834 shell: true,
835 };
836});
837
838export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
839 command: string,
840 options: CommandAvailabilityOptions = {},
841) {
842 return (yield* resolveCommandPath(command, options)) !== null;
843});
844
845export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
846 const appData = env.APPDATA?.trim();
847 const localAppData = env.LOCALAPPDATA?.trim();
848 const userProfile = env.USERPROFILE?.trim();
849
850 return [
851 ...(appData ? [`${appData}\\npm`] : []),
852 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
853 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
854 ...(userProfile
855 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
856 : []),
857 ];
858}
859
860function readWindowsEnvironmentSafely(
861 readEnvironment: WindowsShellEnvironmentReader,
862 names: ReadonlyArray<string>,
863 options?: WindowsEnvironmentProbeOptions,
864): Partial<Record<string, string>> {
865 try {
866 return readEnvironment(names, options);
867 } catch {
868 return {};
869 }
870}
871
872/** Keep one PATH spelling in copied Windows environment records. */
873export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
874 for (const key of Object.keys(env)) {
875 if (key.toUpperCase() === "PATH") {
876 delete env[key];
877 }
878 }
879 env.PATH = value;
880}
881
882function mergeWindowsEnv(
883 currentEnv: NodeJS.ProcessEnv,
884 patch: Partial<Record<string, string>>,
885): NodeJS.ProcessEnv {
886 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
887 for (const [key, value] of Object.entries(patch)) {
888 if (value === undefined) continue;
889 if (key === "PATH") {
890 setWindowsPath(nextEnv, value);
891 } else {
892 nextEnv[key] = value;
893 }
894 }
895 return nextEnv;
896}
897
898export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
899 env: NodeJS.ProcessEnv,
900): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
901 const readEnvironment = yield* WindowsShellEnvironment;
902 const commandAvailable = yield* CommandAvailability;
903 const inheritedPath = readEnvPath(env);
904 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
905 loadProfile: false,
906 }).PATH;
907 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
908 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
909 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
910 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
911 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
912
913 if (yield* commandAvailable("node", { env: baselineEnv })) {
914 return baselinePatch;
915 }
916
917 const profiledEnvironment = readWindowsEnvironmentSafely(
918 readEnvironment,
919 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
920 { loadProfile: true },
921 );
922 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
923 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
924 ...(profiledPath ? { PATH: profiledPath } : {}),
925 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
926 ...(profiledEnvironment.FNM_MULTISHELL_PATH
927 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
928 : {}),
929 };
930 return Object.keys(profiledPatch).length > 0
931 ? { ...baselinePatch, ...profiledPatch }
932 : baselinePatch;
933});