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