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 Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14
15import type { ShellEnvironmentPatch } from "@t3tools/contracts";
16import * as HostProcess from "./HostProcess.ts";
17import * as Context from "effect/Context";
18import { routineSpan } from "./observability.ts";
19const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
20const WINDOWS_PATH_DELIMITER = ";";
21const POSIX_PATH_DELIMITER = ":";
22const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
23const WINDOWS_SHELL_PROBE_TIMEOUT_MS = 5000;
24// A shell stuck in the kernel survives the kill and holds stdout, so execFile's callback never fires.
25const WINDOWS_SHELL_PROBE_DEADLINE = Duration.millis(WINDOWS_SHELL_PROBE_TIMEOUT_MS + 1000);
26
27type ExecFileSyncLike = (
28 file: string,
29 args: ReadonlyArray<string>,
30 options: {
31 encoding: "utf8";
32 timeout: number;
33 killSignal?: NodeJS.Signals | number;
34 detached?: true;
35 stdio?: ["ignore", "pipe", "ignore"];
36 },
37) => string;
38
39function canExecuteFile(filePath: string): boolean {
40 try {
41 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
42 return true;
43 } catch {
44 return false;
45 }
46}
47
48export interface CommandAvailabilityOptions {
49 readonly env?: NodeJS.ProcessEnv;
50 readonly extendEnv?: boolean;
51}
52
53export type CommandAvailabilityChecker = (
54 command: string,
55 options?: CommandAvailabilityOptions,
56) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
57
58const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
59
60// Escape dynamic arguments for both cmd.exe and the target's CommandLineToArgvW parsing.
61function escapeWindowsShellArg(arg: string): string {
62 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
63 // Double up trailing backslashes so the closing quote is not escaped away.
64 escaped = escaped.replace(/(\\*)$/, "$1$1");
65 escaped = `"${escaped}"`;
66 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
67}
68
69export interface ResolvedSpawnCommand {
70 readonly command: string;
71 readonly args: ReadonlyArray<string>;
72 readonly shell: boolean;
73}
74
75export type SpawnExecutableResolver = (
76 command: string,
77 platform: NodeJS.Platform,
78 env: NodeJS.ProcessEnv,
79) => string | undefined | Promise<string | undefined>;
80
81async function resolveSpawnExecutableWithNode(
82 command: string,
83 platform: NodeJS.Platform,
84 env: NodeJS.ProcessEnv,
85): Promise<string | undefined> {
86 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
87 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
88 const candidates = resolveCommandCandidates(
89 command,
90 platform,
91 windowsPathExtensions,
92 path.extname,
93 );
94 const isExecutable = async (candidate: string) => {
95 try {
96 if (!(await NodeFS.promises.stat(candidate)).isFile()) return false;
97 if (platform === "win32") {
98 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
99 }
100 await NodeFS.promises.access(candidate, NodeFS.constants.X_OK);
101 return true;
102 } catch {
103 return false;
104 }
105 };
106
107 if (command.includes("/") || command.includes("\\")) {
108 for (const candidate of candidates) {
109 if (await isExecutable(candidate)) return candidate;
110 }
111 return undefined;
112 }
113
114 const pathValue = readEnvPath(env) ?? "";
115 for (const pathEntry of pathValue.split(pathDelimiterForPlatform(platform))) {
116 // A raw empty component of a nonempty POSIX PATH is the current directory.
117 const emptyComponent = pathEntry === "" && pathValue !== "" && platform !== "win32";
118 const normalizedPathEntry = emptyComponent ? "." : normalizePathEntry(pathEntry, platform);
119 if (normalizedPathEntry.length === 0) continue;
120 const names =
121 platform === "win32"
122 ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute)
123 : undefined;
124 for (const candidate of candidates) {
125 if (isAbsentFromListing(names, candidate)) continue;
126 const candidatePath = path.join(normalizedPathEntry, candidate);
127 // Anchored before the probe: callers may launch it from another cwd or through a wrapper,
128 // and the cwd can change while the probe waits.
129 let probePath = candidatePath;
130 if (emptyComponent) {
131 try {
132 probePath = path.resolve(candidatePath);
133 } catch {
134 continue;
135 }
136 }
137 if (await isExecutable(probePath)) return probePath;
138 }
139 }
140 return undefined;
141}
142
143export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
144 "@t3tools/shared/shell/SpawnExecutableResolution",
145 {
146 defaultValue: () => resolveSpawnExecutableWithNode,
147 },
148);
149
150export interface WindowsEnvironmentProbeOptions {
151 readonly loadProfile?: boolean;
152}
153
154function trimNonEmpty(value: string | null | undefined): string | undefined {
155 const trimmed = value?.trim();
156 return trimmed && trimmed.length > 0 ? trimmed : undefined;
157}
158
159export function readUserLoginShell(): string | undefined {
160 try {
161 return trimNonEmpty(NodeOS.userInfo().shell);
162 } catch {
163 return undefined;
164 }
165}
166
167export function listLoginShellCandidates(
168 platform: NodeJS.Platform,
169 shell: string | undefined,
170 userShell = readUserLoginShell(),
171): ReadonlyArray<string> {
172 const fallbackShell =
173 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
174 const seen = new Set<string>();
175 const candidates: string[] = [];
176
177 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
178 if (!candidate || seen.has(candidate)) {
179 continue;
180 }
181 seen.add(candidate);
182 candidates.push(candidate);
183 }
184
185 return candidates;
186}
187
188export function readPathFromLaunchctl(
189 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
190): string | undefined {
191 try {
192 return trimNonEmpty(
193 execFile("/bin/launchctl", ["getenv", "PATH"], {
194 encoding: "utf8",
195 timeout: 2000,
196 }),
197 );
198 } catch {
199 return undefined;
200 }
201}
202
203export function mergePathEntries(
204 preferredPath: string | undefined,
205 inheritedPath: string | undefined,
206 platform: NodeJS.Platform,
207): string | undefined {
208 const delimiter = platform === "win32" ? ";" : ":";
209 const merged: string[] = [];
210 const seen = new Set<string>();
211
212 for (const pathValue of [preferredPath, inheritedPath]) {
213 if (!pathValue) continue;
214 for (const entry of pathValue.split(delimiter)) {
215 const trimmedEntry = trimPathEntry(entry, platform);
216 if (!trimmedEntry || seen.has(trimmedEntry)) {
217 continue;
218 }
219 seen.add(trimmedEntry);
220 merged.push(trimmedEntry);
221 }
222 }
223
224 return merged.length > 0 ? merged.join(delimiter) : undefined;
225}
226
227function envCaptureStart(name: string): string {
228 return `__T3CODE_ENV_${name}_START__`;
229}
230
231function envCaptureEnd(name: string): string {
232 return `__T3CODE_ENV_${name}_END__`;
233}
234
235const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]);
236const POSIX_CAPTURE_SYNTAX = { assignment: "__T3CODE_PRINTENV=$(", orElse: " || " };
237const PRINTENV_CAPTURE_SYNTAX = new Map(
238 [...DEBUG_TRAP_SHELLS, "dash", "ash"].map((shell) => [shell, POSIX_CAPTURE_SYNTAX] as const),
239).set("fish", { assignment: "set -l __T3CODE_PRINTENV (", orElse: "; or " });
240// Network PATH entries must be probed inside the shell's deadline, away from the desktop thread.
241const PRINTENV_LOOKUP_COMMAND = `/bin/sh -c 'command -v printenv || { [ -n "$1" ] && PATH="$1" command -v printenv; } || printf %s /usr/bin/printenv' t3`;
242
243export function buildEnvironmentCaptureCommand(
244 shell: string,
245 names: ReadonlyArray<string>,
246): string {
247 const executableName = NodePath.basename(shell).toLowerCase();
248 const isNushell = executableName.startsWith("nu");
249 const syntax = PRINTENV_CAPTURE_SYNTAX.get(executableName);
250 const supportsFallback = syntax !== undefined;
251 const inheritedPath = resolvePathEnvironmentVariable(process.env)
252 .split(POSIX_PATH_DELIMITER)
253 .filter(Boolean)
254 .map((entry) => NodePath.posix.resolve(entry))
255 .join(POSIX_PATH_DELIMITER);
256 const lookupPrintenv = `${PRINTENV_LOOKUP_COMMAND} '${inheritedPath.replaceAll("'", "'\\''")}'`;
257 const { assignment, orElse } = syntax ?? POSIX_CAPTURE_SYNTAX;
258 const resolvePrintenv = `${assignment}${lookupPrintenv}); `;
259
260 const capture = names
261 .map((name) => {
262 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
263 throw new Error(`Unsupported environment variable name: ${name}`);
264 }
265
266 if (isNushell) {
267 // Without a configured conversion, Nu expands home paths only in a list PATH.
268 const defaultValue =
269 name === "PATH"
270 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
271 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
272 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
273 "} else { $env.PATH? | default '' }"
274 : `$env.${name}? | default ''`;
275 const value =
276 `if $env.${name}? == null { '' } else if ` +
277 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
278 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
279 `} else { ${defaultValue} }`;
280 return [
281 `print '${envCaptureStart(name)}'`,
282 `print (${value})`,
283 `print '${envCaptureEnd(name)}'`,
284 ].join("; ");
285 }
286
287 return [
288 `printf '%s\\n' '${envCaptureStart(name)}'`,
289 supportsFallback
290 ? `printenv ${name}${orElse}"$__T3CODE_PRINTENV" ${name}${orElse}true`
291 : `printenv ${name} || true`,
292 `printf '%s\\n' '${envCaptureEnd(name)}'`,
293 ].join("; ");
294 })
295 .join("; ");
296
297 // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers.
298 // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first.
299 const command = supportsFallback ? resolvePrintenv + capture : capture;
300 return DEBUG_TRAP_SHELLS.has(executableName)
301 ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${command}`
302 : command;
303}
304
305// Process first so profile prepends win; User and Machine add dirs missing from the launch snapshot.
306export function windowsEnvironmentValueCommand(name: string): string {
307 if (name === "PATH") {
308 return (
309 "$value = (@(" +
310 "[Environment]::GetEnvironmentVariable('PATH','Process')," +
311 "[Environment]::GetEnvironmentVariable('PATH','Machine')," +
312 "[Environment]::GetEnvironmentVariable('PATH','User')" +
313 ") | Where-Object { $_ }) -join ';'"
314 );
315 }
316 // A variable saved after this process started is only in the User or Machine registry scope.
317 return (
318 "$value = @(" +
319 `[Environment]::GetEnvironmentVariable('${name}','Process'),` +
320 `[Environment]::GetEnvironmentVariable('${name}','User'),` +
321 `[Environment]::GetEnvironmentVariable('${name}','Machine')` +
322 ") | Where-Object { $_ } | Select-Object -First 1"
323 );
324}
325
326function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
327 return [
328 "$ErrorActionPreference = 'Stop'",
329 // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths.
330 "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}",
331 ...names.flatMap((name) => {
332 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
333 throw new Error(`Unsupported environment variable name: ${name}`);
334 }
335
336 return [
337 `Write-Output '${envCaptureStart(name)}'`,
338 windowsEnvironmentValueCommand(name),
339 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
340 `Write-Output '${envCaptureEnd(name)}'`,
341 ];
342 }),
343 ].join("; ");
344}
345
346function extractEnvironmentValue(output: string, name: string): string | undefined {
347 const startMarker = envCaptureStart(name);
348 const endMarker = envCaptureEnd(name);
349 const startIndex = output.indexOf(startMarker);
350 if (startIndex === -1) return undefined;
351
352 const valueStartIndex = startIndex + startMarker.length;
353 const endIndex = output.indexOf(endMarker, valueStartIndex);
354 if (endIndex === -1) return undefined;
355
356 const value = output
357 .slice(valueStartIndex, endIndex)
358 .replace(/^\r?\n/, "")
359 .replace(/\r?\n$/, "");
360
361 return value.length > 0 ? value : undefined;
362}
363
364/** Reads the values `buildEnvironmentCaptureCommand` printed; unset or empty names are omitted. */
365export function extractEnvironmentValues(
366 output: string,
367 names: ReadonlyArray<string>,
368): Partial<Record<string, string>> {
369 const environment: Partial<Record<string, string>> = {};
370 for (const name of names) {
371 const value = extractEnvironmentValue(output, name);
372 if (value !== undefined) {
373 environment[name] = value;
374 }
375 }
376 return environment;
377}
378
379export type ShellEnvironmentReader = (
380 shell: string,
381 names: ReadonlyArray<string>,
382 execFile?: ExecFileSyncLike,
383) => Partial<Record<string, string>>;
384
385export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
386 shell,
387 names,
388 execFile = NodeChildProcess.execFileSync,
389) => {
390 if (names.length === 0) {
391 return {};
392 }
393
394 // Interactive startup loads PATH entries; detaching prevents job control on an
395 // inherited controlling TTY from stopping the probe while the parent waits.
396 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
397 encoding: "utf8",
398 timeout: 5000,
399 killSignal: "SIGKILL",
400 detached: true,
401 stdio: ["ignore", "pipe", "ignore"],
402 });
403
404 return extractEnvironmentValues(output, names);
405};
406
407export type WindowsShellEnvironmentReader = (
408 names: ReadonlyArray<string>,
409 options?: WindowsEnvironmentProbeOptions,
410) => Effect.Effect<Partial<Record<string, string>>>;
411
412export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
413 "@t3tools/shared/shell/WindowsShellEnvironment",
414 {
415 defaultValue: () => readEnvironmentFromWindowsShell,
416 },
417);
418
419export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
420 "@t3tools/shared/shell/CommandAvailability",
421 {
422 defaultValue: () => isCommandAvailable,
423 },
424);
425
426const execWindowsEnvironmentProbe = (
427 file: string,
428 args: ReadonlyArray<string>,
429 options: { encoding: "utf8"; timeout: number },
430) =>
431 Effect.callback<Option.Option<string>>((resume) => {
432 let child: NodeChildProcess.ChildProcess;
433 try {
434 child = NodeChildProcess.execFile(
435 file,
436 args,
437 { ...options, windowsHide: true },
438 (error, stdout) => {
439 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
440 },
441 );
442 } catch {
443 resume(Effect.succeedNone);
444 return;
445 }
446 return Effect.sync(() => {
447 child.kill();
448 child.stdout?.destroy();
449 child.stderr?.destroy();
450 child.unref();
451 });
452 });
453
454export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
455 function* (
456 names: ReadonlyArray<string>,
457 options: WindowsEnvironmentProbeOptions = {},
458 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
459 ) {
460 if (names.length === 0) return {};
461
462 const command = buildWindowsEnvironmentCaptureCommand(names);
463 const args = [
464 "-NoLogo",
465 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
466 "-NonInteractive",
467 "-Command",
468 command,
469 ];
470 for (const shell of WINDOWS_SHELL_CANDIDATES) {
471 const output = yield* execFile(shell, args, {
472 encoding: "utf8",
473 timeout: WINDOWS_SHELL_PROBE_TIMEOUT_MS,
474 }).pipe(Effect.timeoutOption(WINDOWS_SHELL_PROBE_DEADLINE), Effect.map(Option.flatten));
475 if (Option.isNone(output)) continue;
476
477 const environment: Partial<Record<string, string>> = {};
478 for (const name of names) {
479 const value = extractEnvironmentValue(output.value, name);
480 if (value !== undefined) environment[name] = value;
481 }
482 return environment;
483 }
484
485 return {};
486 },
487);
488
489function trimPathEntry(entry: string, platform: NodeJS.Platform): string {
490 return platform === "win32" ? entry.trim() : entry;
491}
492
493// POSIX PATH entries are literal: whitespace and quotes are part of the directory name.
494function normalizePathEntry(entry: string, platform: NodeJS.Platform): string {
495 return platform === "win32" ? entry.trim().replace(/^"+|"+$/g, "") : entry;
496}
497
498function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
499 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
500}
501
502function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
503 const normalized = normalizePathEntry(entry, platform);
504 return platform === "win32" ? normalized.toLowerCase() : normalized;
505}
506
507function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
508 return platform === "win32" ? entry.replaceAll('"', "") : entry;
509}
510
511export function mergePathValues(
512 preferredPath: string | undefined,
513 inheritedPath: string | undefined,
514 platform: NodeJS.Platform,
515): string | undefined {
516 const delimiter = pathDelimiterForPlatform(platform);
517 const merged: string[] = [];
518 const seen = new Set<string>();
519
520 for (const rawValue of [preferredPath, inheritedPath]) {
521 if (!rawValue) continue;
522
523 for (const entry of rawValue.split(delimiter)) {
524 const sanitized = sanitizePathEntry(trimPathEntry(entry, platform), platform);
525 if (sanitized.length === 0) continue;
526
527 const normalized = normalizePathEntryForComparison(sanitized, platform);
528 if (normalized.length === 0 || seen.has(normalized)) continue;
529
530 seen.add(normalized);
531 merged.push(sanitized);
532 }
533 }
534
535 return merged.length > 0 ? merged.join(delimiter) : undefined;
536}
537
538function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
539 return env.PATH ?? env.Path ?? env.path;
540}
541
542function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
543 return readEnvPath(env) ?? "";
544}
545
546function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
547 const rawValue =
548 env.PATHEXT ??
549 Object.entries(env).find(
550 ([key, value]) => key.toUpperCase() === "PATHEXT" && value !== undefined,
551 )?.[1];
552 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
553 if (!rawValue) return fallback;
554
555 const parsed: string[] = [];
556 for (const entry of rawValue.split(";")) {
557 const trimmed = entry.trim();
558 if (trimmed.length === 0) continue;
559 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
560 }
561 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
562}
563
564function resolveCommandCandidates(
565 command: string,
566 platform: NodeJS.Platform,
567 windowsPathExtensions: ReadonlyArray<string>,
568 extname: (path: string) => string,
569): ReadonlyArray<string> {
570 if (platform !== "win32") return [command];
571 const extension = extname(command);
572 const normalizedExtension = extension.toUpperCase();
573
574 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
575 const commandWithoutExtension = command.slice(0, -extension.length);
576 return Array.from(
577 new Set([
578 command,
579 `${commandWithoutExtension}${normalizedExtension}`,
580 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
581 ]),
582 );
583 }
584
585 const candidates: string[] = [];
586 for (const candidateExtension of windowsPathExtensions) {
587 candidates.push(`${command}${candidateExtension}`);
588 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
589 }
590 return Array.from(new Set(candidates));
591}
592
593// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
594const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
595const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
596const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
597
598interface CommandResolutionCacheEntry {
599 readonly resolvedPath: string | null;
600 readonly expiresAtNanos: bigint;
601}
602
603export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
604 "@t3tools/shared/shell/CommandResolutionCache",
605 {
606 defaultValue: () => new Map(),
607 },
608);
609
610interface PathDirectoryListing {
611 readonly modified: number | null | undefined;
612 /** Lowercased entry names; undefined when the directory cannot be listed. */
613 readonly names: ReadonlySet<string> | undefined;
614 readonly reusable: boolean;
615}
616
617const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024;
618// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again
619// without moving its mtime, so its listing serves the lookups waiting on it but is not kept.
620const PATH_DIRECTORY_SETTLE_MS = 2_000;
621const NO_DIRECTORY_NAMES: ReadonlySet<string> = new Set();
622
623// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases
624// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS.
625const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/;
626
627function isAbsentFromListing(names: ReadonlySet<string> | undefined, candidate: string): boolean {
628 return (
629 names !== undefined &&
630 LISTED_NAME_PATTERN.test(candidate) &&
631 !names.has(candidate.toLowerCase())
632 );
633}
634
635// The listing must start after the mtime's timestamp step has passed, and a relative entry
636// names another directory once the working directory changes.
637function isReusableListing(
638 directory: string,
639 modified: number,
640 listedAtMs: number,
641 isAbsolute: (path: string) => boolean,
642): boolean {
643 return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS;
644}
645
646const directoryMtime = (directory: string) =>
647 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
648 Effect.map((info) =>
649 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
650 ),
651 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
652 );
653
654// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
655const listPathDirectory = Effect.fnUntraced(function* (
656 directory: string,
657): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem | Path.Path> {
658 const path = yield* Path.Path;
659 const modified = yield* directoryMtime(directory);
660 if (modified === null) {
661 return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) };
662 }
663 if (modified === undefined) return { modified, names: undefined, reusable: false };
664 const listedAtMs = yield* Clock.currentTimeMillis;
665 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
666 fileSystem.readDirectory(directory),
667 ).pipe(Effect.orElseSucceed(() => undefined));
668 return {
669 modified,
670 names: entries && new Set(entries.map((entry) => entry.toLowerCase())),
671 reusable:
672 entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute),
673 };
674});
675
676export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, {
677 capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES,
678 timeToLive: (exit) =>
679 Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero,
680 requireServicesAt: "lookup",
681});
682
683/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */
684export const PathDirectoryListings = Context.Reference(
685 "@t3tools/shared/shell/PathDirectoryListings",
686 { defaultValue: () => Effect.runSync(makePathDirectoryListings) },
687);
688
689const resolverPathDirectoryListings = new Map<
690 string,
691 { readonly modified: number; readonly names: ReadonlySet<string> }
692>();
693
694// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules.
695async function listResolverPathDirectory(
696 directory: string,
697 isAbsolute: (path: string) => boolean,
698): Promise<ReadonlySet<string> | undefined> {
699 let modified: number;
700 try {
701 const stats = await NodeFS.promises.stat(directory);
702 if (!stats.isDirectory()) return undefined;
703 modified = stats.mtimeMs;
704 } catch (error) {
705 return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined;
706 }
707 const cached = resolverPathDirectoryListings.get(directory);
708 if (cached?.modified === modified) return cached.names;
709 resolverPathDirectoryListings.delete(directory);
710 // This resolver runs outside Effect, so it has no Clock to read.
711 // @effect-diagnostics-next-line globalDate:off
712 const listedAtMs = Date.now();
713 let names: ReadonlySet<string>;
714 try {
715 names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase()));
716 } catch {
717 return undefined;
718 }
719 if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) {
720 if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) {
721 const oldest = resolverPathDirectoryListings.keys().next().value;
722 if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest);
723 }
724 resolverPathDirectoryListings.set(directory, { modified, names });
725 }
726 return names;
727}
728
729// An injected resolver or locator may answer differently for the same search, so its
730// entries are kept apart from every other resolver's.
731let spawnResolverCacheIdCount = 0;
732const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
733function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
734 const known = spawnResolverCacheIds.get(resolver);
735 if (known !== undefined) return known;
736 const id = spawnResolverCacheIdCount++;
737 spawnResolverCacheIds.set(resolver, id);
738 return id;
739}
740
741function cacheCommandResolution(
742 cache: Map<string, CommandResolutionCacheEntry>,
743 cacheKey: string,
744 resolvedPath: string | null,
745 nowNanos: bigint,
746): void {
747 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
748 const oldestKey = cache.keys().next().value;
749 if (oldestKey !== undefined) {
750 cache.delete(oldestKey);
751 }
752 }
753 cache.set(cacheKey, {
754 resolvedPath,
755 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
756 });
757}
758
759const isExecutableFile = Effect.fnUntraced(function* (
760 filePath: string,
761 platform: NodeJS.Platform,
762 windowsPathExtensions: ReadonlyArray<string>,
763): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
764 const fileSystem = yield* FileSystem.FileSystem;
765 const path = yield* Path.Path;
766 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
767 if (stat === null || stat.type !== "File") return false;
768
769 if (platform === "win32") {
770 const extension = path.extname(filePath);
771 if (extension.length === 0) return false;
772 return windowsPathExtensions.includes(extension.toUpperCase());
773 }
774
775 return canExecuteFile(filePath);
776});
777
778// Keep case variants: Windows can make PATH directories case-sensitive.
779function pathEntriesForPlatform(pathValue: string, platform: NodeJS.Platform): string[] {
780 const pathEntries: string[] = [];
781 const seenPathEntries = new Set<string>();
782 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
783 // A raw empty component of a nonempty POSIX PATH is the current directory.
784 const pathEntry =
785 entry === "" && pathValue !== "" && platform !== "win32"
786 ? "."
787 : normalizePathEntry(entry, platform);
788 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
789
790 seenPathEntries.add(pathEntry);
791 pathEntries.push(pathEntry);
792 }
793 return pathEntries;
794}
795
796// Relative POSIX PATH entries resolve against the working directory, so caches keyed by them include it.
797// null: a relative entry is present but the working directory cannot be read, so nothing is cached.
798function pathSearchCwd(pathValue: string, platform: NodeJS.Platform): string | null | undefined {
799 if (platform === "win32") return undefined;
800 if (
801 pathEntriesForPlatform(pathValue, platform).every((entry) => NodePath.posix.isAbsolute(entry))
802 ) {
803 return undefined;
804 }
805 try {
806 return process.cwd();
807 } catch {
808 return null;
809 }
810}
811
812// Called within the traced command resolvers.
813const findOnPath = Effect.fnUntraced(function* (
814 pathValue: string,
815 commandCandidates: ReadonlyArray<string>,
816 platform: NodeJS.Platform,
817 windowsPathExtensions: ReadonlyArray<string>,
818 isLast: (match: string) => boolean,
819 // The caller's snapshot, so a cache key and the search it stores agree on the directory.
820 cwd: string | null | undefined,
821): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> {
822 const path = yield* Path.Path;
823 const pathEntries = pathEntriesForPlatform(pathValue, platform);
824
825 // A match through an empty component is anchored: callers may launch it from another cwd or
826 // through a wrapper. A literal "." keeps its relative spelling; the first of the two wins, as
827 // in the deduplicated walk.
828 const anchorsCwd =
829 typeof cwd === "string" &&
830 pathValue
831 .split(pathDelimiterForPlatform(platform))
832 .find((entry) => entry === "" || entry === ".") === "";
833
834 // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe.
835 const listings = platform === "win32" ? yield* PathDirectoryListings : undefined;
836 const matches: string[] = [];
837 for (const pathEntry of pathEntries) {
838 let listing = listings && (yield* Cache.get(listings, pathEntry));
839 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
840 yield* Cache.invalidate(listings, pathEntry);
841 listing = yield* Cache.get(listings, pathEntry);
842 }
843 for (const candidate of commandCandidates) {
844 if (isAbsentFromListing(listing?.names, candidate)) continue;
845 // Probe what is returned: other relative entries stay relative, since the cached cwd
846 // spelling goes stale when the directory is renamed.
847 const match =
848 anchorsCwd && pathEntry === "."
849 ? path.join(cwd, candidate)
850 : path.join(pathEntry, candidate);
851 if (yield* isExecutableFile(match, platform, windowsPathExtensions)) {
852 matches.push(match);
853 if (isLast(match)) return matches;
854 break;
855 }
856 }
857 }
858 return matches;
859});
860
861const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform", {
862 attributes: routineSpan,
863})(function* (
864 command: string,
865 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
866): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
867 const path = yield* Path.Path;
868 const platform = options.platform;
869 const env = options.env ?? process.env;
870 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
871 const commandCandidates = resolveCommandCandidates(
872 command,
873 platform,
874 windowsPathExtensions,
875 path.extname,
876 );
877
878 if (command.includes("/") || command.includes("\\")) {
879 for (const candidate of commandCandidates) {
880 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
881 return candidate;
882 }
883 }
884 return null;
885 }
886
887 const pathValue = resolvePathEnvironmentVariable(env);
888 if (pathValue.length === 0) {
889 return null;
890 }
891
892 const cwd = pathSearchCwd(pathValue, platform);
893 const cacheKey = [
894 platform,
895 pathValue,
896 windowsPathExtensions.join(";"),
897 command,
898 ...(cwd === undefined ? [] : [cwd]),
899 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
900 const cache = yield* CommandResolutionCache;
901 const nowNanos = yield* Clock.monotonicTimeNanos;
902 const cached = cwd === null ? undefined : cache.get(cacheKey);
903 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
904 return cached.resolvedPath;
905 }
906
907 const [resolvedPath = null] = yield* findOnPath(
908 pathValue,
909 commandCandidates,
910 platform,
911 windowsPathExtensions,
912 () => true,
913 cwd,
914 );
915 if (cwd !== null) cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos);
916 return resolvedPath;
917});
918
919export const resolveCommandPath = Effect.fn("shell.resolveCommandPath", {
920 attributes: routineSpan,
921})(function* (command: string, options: CommandAvailabilityOptions = {}) {
922 return yield* resolveCommandPathForPlatform(command, {
923 env: options.env ?? (yield* HostProcess.Environment),
924 platform: yield* HostProcess.Platform,
925 });
926});
927
928// Matches for a bare command in PATH order, up to the first one `until` accepts; not cached.
929export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths", {
930 attributes: routineSpan,
931})(function* (
932 command: string,
933 options: CommandAvailabilityOptions & { readonly until: (match: string) => boolean },
934) {
935 const path = yield* Path.Path;
936 const platform = yield* HostProcess.Platform;
937 const env = options.env ?? (yield* HostProcess.Environment);
938 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
939 const pathValue = resolvePathEnvironmentVariable(env);
940 return yield* findOnPath(
941 pathValue,
942 resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname),
943 platform,
944 windowsPathExtensions,
945 options.until,
946 pathSearchCwd(pathValue, platform),
947 );
948});
949
950// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
951const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
952
953function isFileSync(filePath: string): boolean {
954 try {
955 return NodeFS.statSync(filePath).isFile();
956 } catch {
957 return false;
958 }
959}
960
961/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
962export function preferGitForWindowsBinary(
963 executable: string,
964 env: NodeJS.ProcessEnv,
965 isFile: (filePath: string) => boolean = isFileSync,
966): string {
967 if (env.MSYSTEM) return executable;
968 const path = NodePath.win32;
969 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
970 const launcherDirectory = path.dirname(executable);
971 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
972 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
973 const installRoot = path.dirname(launcherDirectory);
974 for (const build of GIT_FOR_WINDOWS_BUILDS) {
975 const candidate = path.join(installRoot, build, "bin", "git.exe");
976 if (isFile(candidate)) return candidate;
977 }
978 return executable;
979}
980
981/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */
982export function gitForWindowsBash(
983 gitExecutable: string,
984 isFile: (filePath: string) => boolean = isFileSync,
985): string | undefined {
986 const path = NodePath.win32;
987 if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined;
988 // git.exe lives in <root>\cmd, <root>\bin, or <root>\<build>\bin.
989 const launcherRoot = path.dirname(path.dirname(gitExecutable));
990 return [launcherRoot, path.dirname(launcherRoot)]
991 .map((root) => path.join(root, "bin", "bash.exe"))
992 .find(isFile);
993}
994
995// npm cmd-shim format for native executables.
996const NPM_EXECUTABLE_SHIM_PREFIX = [
997 "@ECHO off",
998 "GOTO start",
999 ":find_dp0",
1000 "SET dp0=%~dp0",
1001 "EXIT /b",
1002 ":start",
1003 "SETLOCAL",
1004 "CALL :find_dp0",
1005];
1006const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
1007
1008function readFileSyncOrUndefined(filePath: string): string | undefined {
1009 try {
1010 return NodeFS.readFileSync(filePath, "utf8");
1011 } catch {
1012 return undefined;
1013 }
1014}
1015
1016/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
1017export function npmShimExecutable(
1018 shimPath: string,
1019 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
1020 isFile: (filePath: string) => boolean = isFileSync,
1021): string | undefined {
1022 const path = NodePath.win32;
1023 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
1024 // Match exactly because preserved SET whitespace can select a different file.
1025 const lines = readFile(shimPath)
1026 ?.split(/\r?\n/)
1027 .filter((line) => line.length > 0);
1028 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
1029 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
1030 return undefined;
1031 }
1032 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
1033 if (target === undefined) return undefined;
1034 const executable = path.join(path.dirname(shimPath), target);
1035 return isFile(executable) ? executable : undefined;
1036}
1037
1038export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
1039
1040// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
1041function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
1042 try {
1043 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
1044 encoding: "utf8",
1045 env,
1046 timeout: 5_000,
1047 stdio: ["ignore", "pipe", "ignore"],
1048 }).trim();
1049 return NodePath.isAbsolute(located) ? located : undefined;
1050 } catch {
1051 return undefined;
1052 }
1053}
1054
1055export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
1056 "@t3tools/shared/shell/XcodeGitLocation",
1057 { defaultValue: () => locateXcodeGitWithXcrun },
1058);
1059
1060const MACOS_GIT_SHIM = "/usr/bin/git";
1061
1062/**
1063 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
1064 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
1065 */
1066const resolveMacosGit = Effect.fnUntraced(function* (
1067 env: NodeJS.ProcessEnv,
1068 resolveExecutable: SpawnExecutableResolver,
1069) {
1070 const locateXcodeGit = yield* XcodeGitLocation;
1071 const cache = yield* CommandResolutionCache;
1072 const pathValue = resolvePathEnvironmentVariable(env);
1073 const nowNanos = yield* Clock.currentTimeNanos;
1074 // Read after the clock, so the lookup below starts in the directory the key names.
1075 const cwd = pathSearchCwd(pathValue, "darwin");
1076 const cacheKey = [
1077 "xcode-git",
1078 String(spawnResolverCacheId(resolveExecutable)),
1079 String(spawnResolverCacheId(locateXcodeGit)),
1080 pathValue,
1081 env.DEVELOPER_DIR ?? "",
1082 ...(cwd === undefined ? [] : [cwd]),
1083 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1084 const cached = cwd === null ? undefined : cache.get(cacheKey);
1085 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
1086 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1087 const cachedPath = cached.resolvedPath;
1088 if (
1089 cachedPath === null ||
1090 (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !==
1091 undefined
1092 ) {
1093 return cachedPath ?? "git";
1094 }
1095 }
1096 const pathGit = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env));
1097 const located = pathGit === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
1098 const realGit =
1099 located !== undefined &&
1100 (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined
1101 ? located
1102 : // A match anchored to the cwd came through an empty PATH entry, which a child would search
1103 // again from its own cwd; launch the file that was checked instead of bare `git`.
1104 typeof cwd === "string" && pathGit === NodePath.posix.join(cwd, "git")
1105 ? pathGit
1106 : null;
1107 // The lookups above await and the cwd can move meanwhile; cache only what the key's cwd found.
1108 if (cwd !== null && pathSearchCwd(pathValue, "darwin") === cwd) {
1109 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
1110 }
1111 return realGit ?? "git";
1112});
1113
1114export interface SpawnCommandOptions extends CommandAvailabilityOptions {
1115 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
1116 readonly bypassNpmShim?: boolean;
1117}
1118
1119// `*` is one argument that is not an option. These forms read refs or config
1120// only, so git starts no hook, helper, pager, editor or lazy fetch for them.
1121const CONSOLE_FREE_GIT_READS = [
1122 "rev-parse --git-path index",
1123 "rev-parse --git-common-dir",
1124 "rev-parse --show-toplevel",
1125 "rev-parse --git-common-dir --show-toplevel",
1126 "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel",
1127 "rev-parse --symbolic-full-name HEAD",
1128 "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
1129 "symbolic-ref --quiet HEAD",
1130 "symbolic-ref *",
1131 "remote",
1132 "remote get-url *",
1133 "remote get-url -- *",
1134 "config --get *",
1135].map((form) => form.split(" "));
1136
1137export function runsGitWithoutConsole(
1138 platform: NodeJS.Platform,
1139 executable: string,
1140 args: ReadonlyArray<string>,
1141): boolean {
1142 if (platform !== "win32") return false;
1143 const { basename, dirname } = NodePath.win32;
1144 const bin = dirname(executable);
1145 const build = basename(dirname(bin)).toLowerCase();
1146 if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") {
1147 return false;
1148 }
1149 if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false;
1150 const rest =
1151 args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-")
1152 ? args.slice(2)
1153 : args;
1154 return CONSOLE_FREE_GIT_READS.some(
1155 (form) =>
1156 form.length === rest.length &&
1157 form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))),
1158 );
1159}
1160
1161export const resolveSpawnCommand = Effect.fnUntraced(function* (
1162 command: string,
1163 args: ReadonlyArray<string>,
1164 options: SpawnCommandOptions = {},
1165): Effect.fn.Return<ResolvedSpawnCommand> {
1166 const platform = yield* HostProcess.Platform;
1167 const isMacosGit = platform === "darwin" && command === "git";
1168 if (platform !== "win32" && !isMacosGit) {
1169 return { command, args: [...args], shell: false };
1170 }
1171
1172 const hostEnvironment = yield* HostProcess.Environment;
1173 const env =
1174 options.env === undefined
1175 ? hostEnvironment
1176 : options.extendEnv
1177 ? { ...hostEnvironment, ...options.env }
1178 : options.env;
1179 const resolveExecutable = yield* SpawnExecutableResolution;
1180 if (isMacosGit) {
1181 return {
1182 command: yield* resolveMacosGit(env, resolveExecutable),
1183 args: [...args],
1184 shell: false,
1185 };
1186 }
1187 // Cache successful PATH lookups. Explicit paths and misses stay uncached so
1188 // newly installed executables are discoverable immediately.
1189 const explicitPath = command.includes("/") || command.includes("\\");
1190 const cache = yield* CommandResolutionCache;
1191 const cacheKey = [
1192 "spawn",
1193 String(spawnResolverCacheId(resolveExecutable)),
1194 platform,
1195 resolvePathEnvironmentVariable(env),
1196 resolveWindowsPathExtensions(env).join(";"),
1197 env.MSYSTEM ? "msystem" : "",
1198 command,
1199 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1200 const nowNanos = yield* Clock.currentTimeNanos;
1201 const cached = explicitPath ? undefined : cache.get(cacheKey);
1202 let resolvedExecutable: string | null;
1203 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1204 resolvedExecutable = cached.resolvedPath;
1205 } else {
1206 const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env));
1207 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
1208 if (!explicitPath && resolvedExecutable !== null) {
1209 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
1210 }
1211 }
1212 const resolvedCommand = resolvedExecutable ?? command;
1213 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
1214 if (extension !== ".cmd" && extension !== ".bat") {
1215 return { command: resolvedCommand, args: [...args], shell: false };
1216 }
1217 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
1218 if (shimExecutable !== undefined) {
1219 return { command: shimExecutable, args: [...args], shell: false };
1220 }
1221
1222 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
1223 return {
1224 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
1225 args: [],
1226 shell: true,
1227 };
1228});
1229
1230export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
1231 command: string,
1232 options: CommandAvailabilityOptions = {},
1233) {
1234 return (yield* resolveCommandPath(command, options)) !== null;
1235});
1236
1237function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
1238 const appData = env.APPDATA?.trim();
1239 const localAppData = env.LOCALAPPDATA?.trim();
1240 const userProfile = env.USERPROFILE?.trim();
1241
1242 return [
1243 ...(appData ? [`${appData}\\npm`] : []),
1244 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
1245 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
1246 ...(userProfile
1247 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
1248 : []),
1249 ];
1250}
1251
1252/** Keep one PATH spelling in copied Windows environment records. */
1253export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
1254 for (const key of Object.keys(env)) {
1255 if (key.toUpperCase() === "PATH") {
1256 delete env[key];
1257 }
1258 }
1259 if (value !== null) env.PATH = value;
1260}
1261
1262function mergeWindowsEnv(
1263 currentEnv: NodeJS.ProcessEnv,
1264 patch: Partial<Record<string, string>>,
1265): NodeJS.ProcessEnv {
1266 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
1267 for (const [key, value] of Object.entries(patch)) {
1268 if (value === undefined) continue;
1269 if (key === "PATH") {
1270 setWindowsPath(nextEnv, value);
1271 } else {
1272 nextEnv[key] = value;
1273 }
1274 }
1275 return nextEnv;
1276}
1277
1278export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
1279 env: NodeJS.ProcessEnv,
1280): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
1281 const readEnvironment = yield* WindowsShellEnvironment;
1282 const commandAvailable = yield* CommandAvailability;
1283 const inheritedPath = readEnvPath(env);
1284 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
1285 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
1286 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
1287 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
1288 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
1289 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
1290
1291 if (yield* commandAvailable("node", { env: baselineEnv })) {
1292 return baselinePatch;
1293 }
1294
1295 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
1296 loadProfile: true,
1297 });
1298 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
1299 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
1300 ...(profiledPath ? { PATH: profiledPath } : {}),
1301 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
1302 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1303 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1304 : {}),
1305 };
1306 return Object.keys(profiledPatch).length > 0
1307 ? { ...baselinePatch, ...profiledPatch }
1308 : baselinePatch;
1309});
1310
1311export function applyShellEnvironment(
1312 env: NodeJS.ProcessEnv,
1313 patch: ShellEnvironmentPatch,
1314 platform: NodeJS.Platform,
1315): void {
1316 for (const [key, value] of Object.entries(patch)) {
1317 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
1318 else if (value === null) delete env[key];
1319 else env[key] = value;
1320 }
1321}
1322
1323interface PathSetupInput {
1324 readonly directory: string;
1325 readonly home: string;
1326 readonly shell: string | undefined;
1327 readonly platform: NodeJS.Platform;
1328 /** `XDG_CONFIG_HOME`, where fish reads its startup file when set. */
1329 readonly configHome?: string | undefined;
1330 /** `ZDOTDIR`, where zsh reads `.zshrc` when set. */
1331 readonly zdotdir?: string | undefined;
1332}
1333
1334/**
1335 * The startup file (`~/...`, or absolute under `configHome`) and line that put `directory` last on
1336 * PATH for new zsh, bash, or fish terminals, so it never shadows another `t3`. Undefined on Windows (writing PATH there would flatten the registry's
1337 * `%VAR%` entries), for other shells, macOS bash, or unsafe paths.
1338 */
1339export function pathSetup(
1340 input: PathSetupInput,
1341): { readonly file: string; readonly line: string } | undefined {
1342 // A relative folder on PATH would follow the working directory into any checkout.
1343 if (input.platform === "win32" || !input.directory.startsWith("/")) return undefined;
1344 const underHome = input.directory.startsWith(`${input.home}/`);
1345 const rest = underHome ? input.directory.slice(input.home.length) : input.directory;
1346 if (!/^[\w./-]+$/.test(rest)) return undefined;
1347 const directory = underHome ? `$HOME${rest}` : rest;
1348 const shell = input.shell?.split("/").pop();
1349 // A set folder the shell reads from replaces the default; one unsafe to write means no setup,
1350 // since the default file would never be read.
1351 const readFrom = (value: string | undefined, fallback: string) =>
1352 !value ? fallback : value.startsWith("/") && /^[\w./-]+$/.test(value) ? value : undefined;
1353 if (shell === "fish") {
1354 const configHome = readFrom(input.configHome, "~/.config");
1355 if (configHome === undefined) return undefined;
1356 // --path changes $PATH itself; fish_user_paths would go ahead of the system folders.
1357 return {
1358 file: `${configHome}/fish/config.fish`,
1359 line: `fish_add_path --append --path ${directory}`,
1360 };
1361 }
1362 // macOS bash reads only the first of .bash_profile, .bash_login, and .profile; no file is safe.
1363 const zdotdir = readFrom(input.zdotdir, "~");
1364 const file =
1365 shell === "zsh"
1366 ? zdotdir && `${zdotdir}/.zshrc`
1367 : shell === "bash" && input.platform !== "darwin"
1368 ? "~/.bashrc"
1369 : undefined;
1370 return file === undefined ? undefined : { file, line: `export PATH="$PATH:${directory}"` };
1371}
1372
1373/** A command to paste that does what {@link pathSetup} describes. */
1374export function pathSetupCommand(input: PathSetupInput): string | undefined {
1375 const setup = pathSetup(input);
1376 if (!setup) return undefined;
1377 // The leading newline keeps the line out of a final comment with no newline after it.
1378 const append = `printf '\\n%s\\n' '${setup.line}' >> ${setup.file}`;
1379 // fish's config folder may not exist yet; `&&` works in fish 3 too.
1380 return setup.file.endsWith(".fish")
1381 ? `mkdir -p ${setup.file.slice(0, setup.file.lastIndexOf("/"))} && ${append}`
1382 : append;
1383}