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