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