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