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