Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell.ts

840 lines28.5 KB

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 Data from "effect/Data";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13​
14import * as HostProcess from "./HostProcess.ts";
15import * as Context from "effect/Context";
16const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
17const WINDOWS_PATH_DELIMITER = ";";
18const POSIX_PATH_DELIMITER = ":";
19const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
20​
21type ExecFileSyncLike = (
22 file: string,
23 args: ReadonlyArray<string>,
24 options: { encoding: "utf8"; timeout: number },
25) => string;
26​
27function canExecuteFile(filePath: string): boolean {
28 try {
29 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
30 return true;
31 } catch {
32 return false;
33 }
35​
36export interface CommandAvailabilityOptions {
37 readonly env?: NodeJS.ProcessEnv;
38 readonly extendEnv?: boolean;
40​
41export type CommandAvailabilityChecker = (
42 command: string,
43 options?: CommandAvailabilityOptions,
44) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
45​
46export class CommandResolutionError extends Data.TaggedError("CommandResolutionError")<{
47 readonly command: string;
48 readonly reason: "not-found";
49}> {}
50​
51const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
52​
53/**
54 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
55 * on Windows). Node joins the command and arguments with spaces and hands the
56 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
57 * must be escaped to survive both cmd.exe parsing and the target program's
58 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
59 */
60function escapeWindowsShellArg(arg: string): string {
61 // Double up backslashes that precede a double quote, then escape the quote
62 // itself so it survives CommandLineToArgvW.
63 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
64 // Double up trailing backslashes so the closing quote is not escaped away.
65 escaped = escaped.replace(/(\\*)$/, "$1$1");
66 // Quote the whole argument so embedded whitespace is preserved.
67 escaped = `"${escaped}"`;
68 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
69 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
71​
72/**
73 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
74 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
75 * and returns the arguments untouched everywhere else.
76 */
77function sanitizeShellModeArgsForPlatform(
78 args: ReadonlyArray<string>,
79 platform: NodeJS.Platform,
80): Array<string> {
81 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
83​
84export interface ResolvedSpawnCommand {
85 readonly command: string;
86 readonly args: ReadonlyArray<string>;
87 readonly shell: boolean;
89​
90export type SpawnExecutableResolver = (
91 command: string,
92 platform: NodeJS.Platform,
93 env: NodeJS.ProcessEnv,
94) => string | undefined;
95​
96function resolveSpawnExecutableWithNode(
97 command: string,
98 platform: NodeJS.Platform,
99 env: NodeJS.ProcessEnv,
100): string | undefined {
101 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
102 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
103 const candidates = resolveCommandCandidates(
104 command,
105 platform,
106 windowsPathExtensions,
107 path.extname,
108 );
109 const isExecutable = (candidate: string) => {
110 try {
111 if (!NodeFS.statSync(candidate).isFile()) return false;
112 if (platform === "win32") {
113 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
114 }
115 return canExecuteFile(candidate);
116 } catch {
117 return false;
118 }
119 };
120​
121 if (command.includes("/") || command.includes("\\")) {
122 return candidates.find(isExecutable);
123 }
124​
125 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
126 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
127 if (normalizedPathEntry.length === 0) continue;
128 for (const candidate of candidates) {
129 const candidatePath = path.join(normalizedPathEntry, candidate);
130 if (isExecutable(candidatePath)) return candidatePath;
131 }
132 }
133 return undefined;
135​
136export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
137 "@t3tools/shared/shell/SpawnExecutableResolution",
138 {
139 defaultValue: () => resolveSpawnExecutableWithNode,
140 },
141);
142​
143export interface WindowsEnvironmentProbeOptions {
144 readonly loadProfile?: boolean;
146​
147function trimNonEmpty(value: string | null | undefined): string | undefined {
148 const trimmed = value?.trim();
149 return trimmed && trimmed.length > 0 ? trimmed : undefined;
151​
152function readUserLoginShell(): string | undefined {
153 try {
154 return trimNonEmpty(NodeOS.userInfo().shell);
155 } catch {
156 return undefined;
157 }
159​
160export function listLoginShellCandidates(
161 platform: NodeJS.Platform,
162 shell: string | undefined,
163 userShell = readUserLoginShell(),
164): ReadonlyArray<string> {
165 const fallbackShell =
166 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
167 const seen = new Set<string>();
168 const candidates: string[] = [];
169​
170 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
171 if (!candidate || seen.has(candidate)) {
172 continue;
173 }
174 seen.add(candidate);
175 candidates.push(candidate);
176 }
177​
178 return candidates;
180​
181export function readPathFromLoginShell(
182 shell: string,
183 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
184): string | undefined {
185 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
187​
188export function readPathFromLaunchctl(
189 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
190): string | undefined {
191 try {
192 return trimNonEmpty(
193 execFile("/bin/launchctl", ["getenv", "PATH"], {
194 encoding: "utf8",
195 timeout: 2000,
196 }),
197 );
198 } catch {
199 return undefined;
200 }
202​
203export function mergePathEntries(
204 preferredPath: string | undefined,
205 inheritedPath: string | undefined,
206 platform: NodeJS.Platform,
207): string | undefined {
208 const delimiter = platform === "win32" ? ";" : ":";
209 const merged: string[] = [];
210 const seen = new Set<string>();
211​
212 for (const pathValue of [preferredPath, inheritedPath]) {
213 if (!pathValue) continue;
214 for (const entry of pathValue.split(delimiter)) {
215 const trimmedEntry = entry.trim();
216 if (!trimmedEntry || seen.has(trimmedEntry)) {
217 continue;
218 }
219 seen.add(trimmedEntry);
220 merged.push(trimmedEntry);
221 }
222 }
223​
224 return merged.length > 0 ? merged.join(delimiter) : undefined;
226​
227function envCaptureStart(name: string): string {
228 return `__T3CODE_ENV_${name}_START__`;
230​
231function envCaptureEnd(name: string): string {
232 return `__T3CODE_ENV_${name}_END__`;
234​
235function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
236 return names
237 .map((name) => {
238 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
239 throw new Error(`Unsupported environment variable name: ${name}`);
240 }
241​
242 return [
243 `printf '%s\\n' '${envCaptureStart(name)}'`,
244 `printenv ${name} || true`,
245 `printf '%s\\n' '${envCaptureEnd(name)}'`,
246 ].join("; ");
247 })
248 .join("; ");
250​
251function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
252 return [
253 "$ErrorActionPreference = 'Stop'",
254 ...names.flatMap((name) => {
255 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
256 throw new Error(`Unsupported environment variable name: ${name}`);
257 }
258​
259 return [
260 `Write-Output '${envCaptureStart(name)}'`,
261 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
262 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
263 `Write-Output '${envCaptureEnd(name)}'`,
264 ];
265 }),
266 ].join("; ");
268​
269function extractEnvironmentValue(output: string, name: string): string | undefined {
270 const startMarker = envCaptureStart(name);
271 const endMarker = envCaptureEnd(name);
272 const startIndex = output.indexOf(startMarker);
273 if (startIndex === -1) return undefined;
274​
275 const valueStartIndex = startIndex + startMarker.length;
276 const endIndex = output.indexOf(endMarker, valueStartIndex);
277 if (endIndex === -1) return undefined;
278​
279 const value = output
280 .slice(valueStartIndex, endIndex)
281 .replace(/^\r?\n/, "")
282 .replace(/\r?\n$/, "");
283​
284 return value.length > 0 ? value : undefined;
286​
287export type ShellEnvironmentReader = (
288 shell: string,
289 names: ReadonlyArray<string>,
290 execFile?: ExecFileSyncLike,
291) => Partial<Record<string, string>>;
292​
293export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
294 shell,
295 names,
296 execFile = NodeChildProcess.execFileSync,
297) => {
298 if (names.length === 0) {
299 return {};
300 }
301​
302 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
303 encoding: "utf8",
304 timeout: 5000,
305 });
306​
307 const environment: Partial<Record<string, string>> = {};
308 for (const name of names) {
309 const value = extractEnvironmentValue(output, name);
310 if (value !== undefined) {
311 environment[name] = value;
312 }
313 }
314​
315 return environment;
316};
317​
318export type WindowsShellEnvironmentReader = (
319 names: ReadonlyArray<string>,
320 options?: WindowsEnvironmentProbeOptions,
321) => Partial<Record<string, string>>;
322​
323export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
324 "@t3tools/shared/shell/WindowsShellEnvironment",
325 {
326 defaultValue: () => readEnvironmentFromWindowsShell,
327 },
328);
329​
330export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
331 "@t3tools/shared/shell/CommandAvailability",
332 {
333 defaultValue: () => isCommandAvailable,
334 },
335);
336​
337export function readEnvironmentFromWindowsShell(
338 names: ReadonlyArray<string>,
339 execFile?: ExecFileSyncLike,
340): Partial<Record<string, string>>;
341export function readEnvironmentFromWindowsShell(
342 names: ReadonlyArray<string>,
343 options?: WindowsEnvironmentProbeOptions,
344 execFile?: ExecFileSyncLike,
345): Partial<Record<string, string>>;
346export function readEnvironmentFromWindowsShell(
347 names: ReadonlyArray<string>,
348 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
349 maybeExecFile?: ExecFileSyncLike,
350): Partial<Record<string, string>> {
351 if (names.length === 0) {
352 return {};
353 }
354​
355 const options =
356 typeof optionsOrExecFile === "function"
357 ? ({} satisfies WindowsEnvironmentProbeOptions)
358 : (optionsOrExecFile ?? {});
359 const execFile: ExecFileSyncLike =
360 typeof optionsOrExecFile === "function"
361 ? optionsOrExecFile
362 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
363 const command = buildWindowsEnvironmentCaptureCommand(names);
364 const args = [
365 "-NoLogo",
366 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
367 "-NonInteractive",
368 "-Command",
369 command,
370 ];
371 for (const shell of WINDOWS_SHELL_CANDIDATES) {
372 try {
373 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
374​
375 const environment: Partial<Record<string, string>> = {};
376 for (const name of names) {
377 const value = extractEnvironmentValue(output, name);
378 if (value !== undefined) {
379 environment[name] = value;
380 }
381 }
382 return environment;
383 } catch {
384 continue;
385 }
386 }
387​
388 return {};
390​
391function stripWrappingQuotes(value: string): string {
392 return value.replace(/^"+|"+$/g, "");
394​
395function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
396 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
398​
399function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
400 const normalized = stripWrappingQuotes(entry.trim());
401 return platform === "win32" ? normalized.toLowerCase() : normalized;
403​
404function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
405 return platform === "win32" ? entry.replaceAll('"', "") : entry;
407​
408export function mergePathValues(
409 preferredPath: string | undefined,
410 inheritedPath: string | undefined,
411 platform: NodeJS.Platform,
412): string | undefined {
413 const delimiter = pathDelimiterForPlatform(platform);
414 const merged: string[] = [];
415 const seen = new Set<string>();
416​
417 for (const rawValue of [preferredPath, inheritedPath]) {
418 if (!rawValue) continue;
419​
420 for (const entry of rawValue.split(delimiter)) {
421 const sanitized = sanitizePathEntry(entry.trim(), platform);
422 if (sanitized.length === 0) continue;
423​
424 const normalized = normalizePathEntryForComparison(sanitized, platform);
425 if (normalized.length === 0 || seen.has(normalized)) continue;
426​
427 seen.add(normalized);
428 merged.push(sanitized);
429 }
430 }
431​
432 return merged.length > 0 ? merged.join(delimiter) : undefined;
434​
435function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
436 return env.PATH ?? env.Path ?? env.path;
438​
439function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
440 return readEnvPath(env) ?? "";
442​
443function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
444 const rawValue = env.PATHEXT;
445 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
446 if (!rawValue) return fallback;
447​
448 const parsed: string[] = [];
449 for (const entry of rawValue.split(";")) {
450 const trimmed = entry.trim();
451 if (trimmed.length === 0) continue;
452 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
453 }
454 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
456​
457function resolveCommandCandidates(
458 command: string,
459 platform: NodeJS.Platform,
460 windowsPathExtensions: ReadonlyArray<string>,
461 extname: (path: string) => string,
462): ReadonlyArray<string> {
463 if (platform !== "win32") return [command];
464 const extension = extname(command);
465 const normalizedExtension = extension.toUpperCase();
466​
467 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
468 const commandWithoutExtension = command.slice(0, -extension.length);
469 return Array.from(
470 new Set([
471 command,
472 `${commandWithoutExtension}${normalizedExtension}`,
473 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
474 ]),
475 );
476 }
477​
478 const candidates: string[] = [];
479 for (const candidateExtension of windowsPathExtensions) {
480 candidates.push(`${command}${candidateExtension}`);
481 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
482 }
483 return Array.from(new Set(candidates));
485​
486// Session bootstrap resolves the same commands over and over, each PATH scan
487// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of
488// thousands per connect). Memoize the scan outcome per
489// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the
490// cache while any change to the search environment invalidates immediately.
491// Explicit-path resolution is never cached - callers probe paths they have
492// just written (e.g. managed binary installs). A "not-found" outcome is also
493// cached for the TTL, so a just-installed binary can stay invisible for up to
494// 30s unless resolved by explicit path.
495// TTL expiry uses the monotonic clock (Clock.monotonicTimeNanos) so backward
496// wall-clock adjustments cannot keep expired entries alive.
497const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
498const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
499const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
500​
501interface CommandResolutionCacheEntry {
502 readonly resolvedPath: string | null;
503 readonly expiresAtNanos: bigint;
505​
506// The cache lives in the Effect environment (like HostProcess.Platform above)
507// so tests and embedders can provide an isolated instance; the default is a
508// single process-wide map shared by all consumers.
509export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
510 "@t3tools/shared/shell/CommandResolutionCache",
511 {
512 defaultValue: () => new Map(),
513 },
514);
515​
516interface PathDirectoryListing {
517 readonly modified: number | null | undefined;
518 readonly names: ReadonlySet<string> | undefined;
520​
521// mtime of a PATH directory; null when missing, undefined when unreadable.
522const directoryMtime = (directory: string) =>
523 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
524 Effect.map((info) =>
525 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
526 ),
527 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
528 );
529​
530// Dated before it is read, so an entry added in between changes the mtime seen
531// on the next check. Without names, lookups probe candidates directly.
532const listPathDirectory = Effect.fnUntraced(function* (
533 directory: string,
534): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
535 const modified = yield* directoryMtime(directory);
536 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
537 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
538 fileSystem.readDirectory(directory),
539 ).pipe(Effect.orElseSucceed(() => undefined));
540 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
541});
542​
543const PathDirectoryListings = Context.Reference<
544 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
545>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
546​
547/**
548 * Run a batch of command lookups (e.g. editor discovery) that lists each PATH
549 * directory once, relisting it if its mtime changes, and probes only listed
550 * names instead of every PATH x PATHEXT candidate per command.
551 */
552export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
553 Effect.gen(function* () {
554 const listings = yield* Cache.make({
555 capacity: 1024,
556 lookup: listPathDirectory,
557 requireServicesAt: "lookup",
558 });
559 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
560 });
561​
562// An injected resolver may answer differently for the same search, so its
563// entries are kept apart from every other resolver's.
564let spawnResolverCacheIdCount = 0;
565const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
566function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
567 const known = spawnResolverCacheIds.get(resolver);
568 if (known !== undefined) return known;
569 const id = spawnResolverCacheIdCount++;
570 spawnResolverCacheIds.set(resolver, id);
571 return id;
573​
574function cacheCommandResolution(
575 cache: Map<string, CommandResolutionCacheEntry>,
576 cacheKey: string,
577 resolvedPath: string | null,
578 nowNanos: bigint,
579): void {
580 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
581 const oldestKey = cache.keys().next().value;
582 if (oldestKey !== undefined) {
583 cache.delete(oldestKey);
584 }
585 }
586 cache.set(cacheKey, {
587 resolvedPath,
588 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
589 });
591​
592// Trace each command lookup, not every candidate file it probes.
593const isExecutableFile = Effect.fnUntraced(function* (
594 filePath: string,
595 platform: NodeJS.Platform,
596 windowsPathExtensions: ReadonlyArray<string>,
597): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
598 const fileSystem = yield* FileSystem.FileSystem;
599 const path = yield* Path.Path;
600 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
601 if (stat === null || stat.type !== "File") return false;
602​
603 if (platform === "win32") {
604 const extension = path.extname(filePath);
605 if (extension.length === 0) return false;
606 return windowsPathExtensions.includes(extension.toUpperCase());
607 }
608​
609 return canExecuteFile(filePath);
610});
611​
612const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
613 command: string,
614 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
615): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {
616 const path = yield* Path.Path;
617 const platform = options.platform;
618 const env = options.env ?? process.env;
619 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
620 const commandCandidates = resolveCommandCandidates(
621 command,
622 platform,
623 windowsPathExtensions,
624 path.extname,
625 );
626​
627 if (command.includes("/") || command.includes("\\")) {
628 for (const candidate of commandCandidates) {
629 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
630 return candidate;
631 }
632 }
633 return yield* new CommandResolutionError({ command, reason: "not-found" });
634 }
635​
636 const pathValue = resolvePathEnvironmentVariable(env);
637 if (pathValue.length === 0) {
638 return yield* new CommandResolutionError({ command, reason: "not-found" });
639 }
640​
641 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
642 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
643 );
644 const cache = yield* CommandResolutionCache;
645 const nowNanos = yield* Clock.monotonicTimeNanos;
646 const cached = cache.get(cacheKey);
647 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
648 if (cached.resolvedPath === null) {
649 return yield* new CommandResolutionError({ command, reason: "not-found" });
650 }
651 return cached.resolvedPath;
652 }
653​
654 // Keep case variants: Windows can make PATH directories case-sensitive.
655 const pathEntries: string[] = [];
656 const seenPathEntries = new Set<string>();
657 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
658 const pathEntry = stripWrappingQuotes(entry.trim());
659 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
660​
661 seenPathEntries.add(pathEntry);
662 pathEntries.push(pathEntry);
663 }
664​
665 const listings = yield* PathDirectoryListings;
666 for (const pathEntry of pathEntries) {
667 let listing = listings && (yield* Cache.get(listings, pathEntry));
668 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
669 yield* Cache.invalidate(listings, pathEntry);
670 listing = yield* Cache.get(listings, pathEntry);
671 }
672 for (const candidate of commandCandidates) {
673 // The stat below still checks exact case and rejects non-files.
674 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
675 const candidatePath = path.join(pathEntry, candidate);
676 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
677 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
678 return candidatePath;
679 }
680 }
681 }
682 cacheCommandResolution(cache, cacheKey, null, nowNanos);
683 return yield* new CommandResolutionError({ command, reason: "not-found" });
684});
685​
686export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
687 command: string,
688 options: CommandAvailabilityOptions = {},
689) {
690 return yield* resolveCommandPathForPlatform(command, {
691 env: options.env ?? (yield* HostProcess.Environment),
692 platform: yield* HostProcess.Platform,
693 });
694});
695​
696// Untraced because it runs before most spawns and returns at once off Windows.
697export const resolveSpawnCommand = Effect.fnUntraced(function* (
698 command: string,
699 args: ReadonlyArray<string>,
700 options: CommandAvailabilityOptions = {},
701): Effect.fn.Return<ResolvedSpawnCommand> {
702 const platform = yield* HostProcess.Platform;
703 if (platform !== "win32") {
704 return { command, args: [...args], shell: false };
705 }
706​
707 const hostEnvironment = yield* HostProcess.Environment;
708 const env =
709 options.env === undefined
710 ? hostEnvironment
711 : options.extendEnv
712 ? { ...hostEnvironment, ...options.env }
713 : options.env;
714 const resolveExecutable = yield* SpawnExecutableResolution;
715 // The scan is synchronous and runs before every child process, so it shares
716 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
717 // and so do misses: a failed spawn is how providers report "not installed",
718 // and that has to clear the moment the binary appears.
719 const explicitPath = command.includes("/") || command.includes("\\");
720 const cache = yield* CommandResolutionCache;
721 const cacheKey = [
722 "spawn",
723 String(spawnResolverCacheId(resolveExecutable)),
724 platform,
725 resolvePathEnvironmentVariable(env),
726 resolveWindowsPathExtensions(env).join(";"),
727 command,
728 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
729 const nowNanos = yield* Clock.currentTimeNanos;
730 const cached = explicitPath ? undefined : cache.get(cacheKey);
731 let resolvedExecutable: string | null;
732 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
733 resolvedExecutable = cached.resolvedPath;
734 } else {
735 resolvedExecutable = resolveExecutable(command, platform, env) ?? null;
736 if (!explicitPath && resolvedExecutable !== null) {
737 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
738 }
739 }
740 const resolvedCommand = resolvedExecutable ?? command;
741 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
742 if (extension !== ".cmd" && extension !== ".bat") {
743 return { command: resolvedCommand, args: [...args], shell: false };
744 }
745​
746 return {
747 command: escapeWindowsShellArg(resolvedCommand),
748 args: sanitizeShellModeArgsForPlatform(args, platform),
749 shell: true,
750 };
751});
752​
753export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
754 command: string,
755 options: CommandAvailabilityOptions = {},
756) {
757 return yield* resolveCommandPath(command, options).pipe(
758 Effect.as(true),
759 Effect.catchTags({ CommandResolutionError: () => Effect.succeed(false) }),
760 );
761});
762​
763export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
764 const appData = env.APPDATA?.trim();
765 const localAppData = env.LOCALAPPDATA?.trim();
766 const userProfile = env.USERPROFILE?.trim();
767​
768 return [
769 ...(appData ? [`${appData}\\npm`] : []),
770 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
771 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
772 ...(userProfile
773 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
774 : []),
775 ];
777​
778function readWindowsEnvironmentSafely(
779 readEnvironment: WindowsShellEnvironmentReader,
780 names: ReadonlyArray<string>,
781 options?: WindowsEnvironmentProbeOptions,
782): Partial<Record<string, string>> {
783 try {
784 return readEnvironment(names, options);
785 } catch {
786 return {};
787 }
789​
790function mergeWindowsEnv(
791 currentEnv: NodeJS.ProcessEnv,
792 patch: Partial<Record<string, string>>,
793): NodeJS.ProcessEnv {
794 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
795 for (const [key, value] of Object.entries(patch)) {
796 if (value !== undefined) {
797 nextEnv[key] = value;
798 }
799 }
800 return nextEnv;
802​
803export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
804 env: NodeJS.ProcessEnv,
805): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
806 const readEnvironment = yield* WindowsShellEnvironment;
807 const commandAvailable = yield* CommandAvailability;
808 const inheritedPath = readEnvPath(env);
809 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
810 loadProfile: false,
811 }).PATH;
812 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
813 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
814 // Preserve the order a user's shell uses. These directories fill gaps when
815 // desktop apps launch without the full interactive-shell PATH.
816 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
817 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
818 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
819​
820 if (yield* commandAvailable("node", { env: baselineEnv })) {
821 return baselinePatch;
822 }
823​
824 const profiledEnvironment = readWindowsEnvironmentSafely(
825 readEnvironment,
826 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
827 { loadProfile: true },
828 );
829 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
830 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
831 ...(profiledPath ? { PATH: profiledPath } : {}),
832 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
833 ...(profiledEnvironment.FNM_MULTISHELL_PATH
834 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
835 : {}),
836 };
837 return Object.keys(profiledPatch).length > 0
838 ? { ...baselinePatch, ...profiledPatch }
839 : baselinePatch;
840});