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

shell.test.ts

878 lines30.4 KB

1// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as NodeChildProcess from "node:child_process";
9import * as NodeFS from "node:fs";
10import * as NodeOS from "node:os";
11import * as NodePath from "node:path";
12import { describe, expect, it, vi } from "vite-plus/test";
13​
14import {
15 CommandAvailability,
16 CommandResolutionCache,
17 type CommandAvailabilityChecker,
18 isCommandAvailable,
19 listLoginShellCandidates,
20 mergePathEntries,
21 mergePathValues,
22 npmShimExecutable,
23 preferGitForWindowsBinary,
24 readEnvironmentFromLoginShell,
25 readEnvironmentFromWindowsShell,
26 resolveCommandPath,
27 resolveSpawnCommand,
28 resolveWindowsEnvironment,
29 SpawnExecutableResolution,
30 WindowsShellEnvironment,
31 withPathDirectoryListings,
32 type WindowsShellEnvironmentReader,
33 XcodeGitLocation,
34} from "./shell.ts";
35​
36const withWindowsEnvironmentMocks = <A, E, R>(
37 effect: Effect.Effect<A, E, R>,
38 readEnvironment: WindowsShellEnvironmentReader,
39 commandAvailable: CommandAvailabilityChecker,
40) =>
41 effect.pipe(
42 Effect.provideService(WindowsShellEnvironment, readEnvironment),
43 Effect.provideService(CommandAvailability, commandAvailable),
44 );
45​
46describe("readEnvironmentFromLoginShell", () => {
47 // Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
48 it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
49 "captures Nushell PATH and multiline values without external tools",
50 () => {
51 const shell = process.env.T3_TEST_NU_PATH!;
52 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
53 try {
54 const toolPath = NodePath.join(home, "nu tools", "bin");
55 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
56 NodeFS.mkdirSync(toolPath, { recursive: true });
57 NodeFS.mkdirSync(extraToolPath, { recursive: true });
58 const config = NodePath.join(home, "config.nu");
59 const envConfig = NodePath.join(home, "env.nu");
60 NodeFS.writeFileSync(envConfig, "");
61 NodeFS.writeFileSync(
62 config,
63 [
64 `$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
65 '$env.CUSTOM_VAR = " first\\nsecond "',
66 '$env.EMPTY_VAR = ""',
67 'print "startup noise"',
68 ].join("\n"),
69 );
70​
71 expect(
72 readEnvironmentFromLoginShell(
73 shell,
74 ["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
75 (file, args, options) =>
76 NodeChildProcess.execFileSync(
77 file,
78 ["--no-history", "--config", config, "--env-config", envConfig, ...args],
79 {
80 ...options,
81 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
82 },
83 ),
84 ),
85 ).toEqual({
86 PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
87 CUSTOM_VAR: " first\nsecond ",
88 });
89 } finally {
90 NodeFS.rmSync(home, { recursive: true, force: true });
91 }
92 },
93 );
94​
95 it("extracts multiple environment variables from a login shell command", () => {
96 const execFile = vi.fn<
97 (
98 file: string,
99 args: ReadonlyArray<string>,
100 options: { encoding: "utf8"; timeout: number },
101 ) => string
102 >(() =>
103 [
104 "__T3CODE_ENV_PATH_START__",
105 "/a:/b",
106 "__T3CODE_ENV_PATH_END__",
107 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
108 "/tmp/secretive.sock",
109 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
110 ].join("\n"),
111 );
112​
113 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
114 PATH: "/a:/b",
115 SSH_AUTH_SOCK: "/tmp/secretive.sock",
116 });
117 expect(execFile).toHaveBeenCalledTimes(1);
118 });
119​
120 it("omits environment variables that are missing or empty", () => {
121 const execFile = vi.fn<
122 (
123 file: string,
124 args: ReadonlyArray<string>,
125 options: { encoding: "utf8"; timeout: number },
126 ) => string
127 >(() =>
128 [
129 "__T3CODE_ENV_PATH_START__",
130 "/a:/b",
131 "__T3CODE_ENV_PATH_END__",
132 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
133 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
134 ].join("\n"),
135 );
136​
137 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
138 PATH: "/a:/b",
139 });
140 });
141​
142 it("preserves multiline values and surrounding whitespace", () => {
143 const execFile = vi.fn<
144 (
145 file: string,
146 args: ReadonlyArray<string>,
147 options: { encoding: "utf8"; timeout: number },
148 ) => string
149 >(() =>
150 [
151 "__T3CODE_ENV_CUSTOM_VAR_START__",
152 " first\nsecond ",
153 "__T3CODE_ENV_CUSTOM_VAR_END__",
154 ].join("\n"),
155 );
156​
157 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
158 CUSTOM_VAR: " first\nsecond ",
159 });
160 });
161});
162​
163describe("listLoginShellCandidates", () => {
164 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
165 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
166 "/opt/homebrew/bin/nu",
167 "/bin/zsh",
168 ]);
169 });
170});
171​
172describe("mergePathEntries", () => {
173 it("prefers login-shell PATH entries and keeps inherited extras", () => {
174 expect(
175 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
176 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
177 });
178});
179​
180describe("readEnvironmentFromWindowsShell", () => {
181 it("strips CRLF delimiters from captured PowerShell values", () => {
182 const execFile = vi.fn<
183 (
184 file: string,
185 args: ReadonlyArray<string>,
186 options: { encoding: "utf8"; timeout: number },
187 ) => string
188 >(
189 () =>
190 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
191 );
192​
193 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
194 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
195 });
196 });
197​
198 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
199 const execFile = vi.fn<
200 (
201 file: string,
202 args: ReadonlyArray<string>,
203 options: { encoding: "utf8"; timeout: number },
204 ) => string
205 >((file) => {
206 if (file === "pwsh.exe") {
207 throw new Error("spawn pwsh.exe ENOENT");
208 }
209 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
210 });
211​
212 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
213 PATH: "C:\\Tools",
214 });
215 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
216 encoding: "utf8",
217 timeout: 5000,
218 });
219 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
220 encoding: "utf8",
221 timeout: 5000,
222 });
223 });
224});
225​
226describe("mergePathValues", () => {
227 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
228 expect(
229 mergePathValues(
230 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
231 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
232 "win32",
233 ),
234 ).toBe(
235 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
236 );
237 });
238​
239 it("removes stray quotes from Windows entries", () => {
240 expect(
241 mergePathValues(
242 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
243 undefined,
244 "win32",
245 ),
246 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
247 });
248​
249 it("dedupes case-sensitively on POSIX", () => {
250 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
251 "/usr/local/bin:/usr/bin:/USR/BIN",
252 );
253 });
254});
255​
256effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
257 const recordProbes = (env: NodeJS.ProcessEnv) =>
258 Effect.gen(function* () {
259 const probed: Array<string> = [];
260 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
261 Effect.provideService(HostProcess.Platform, "win32"),
262 Effect.provideService(CommandResolutionCache, new Map()),
263 Effect.provide(
264 FileSystem.layerNoop({
265 stat: (filePath) =>
266 Effect.sync(() => {
267 probed.push(filePath);
268 return { type: "Directory" } as FileSystem.File.Info;
269 }),
270 }),
271 ),
272 );
273​
274 expect(result).toBeNull();
275 return probed;
276 });
277​
278 it.effect("still visits a PATH entry that differs only in case", () =>
279 Effect.gen(function* () {
280 const probed = yield* recordProbes({
281 PATH: "C:\\bin;C:\\BIN",
282 PATHEXT: ".COM;.EXE",
283 });
284​
285 // Windows 10+ can mark a directory case-sensitive, so the two spellings
286 // are not provably one directory and skipping the second could hide a
287 // command that is really there.
288 expect(probed).toHaveLength(8);
289 }),
290 );
291​
292 it.effect.each(["audit-command", "audit-command.CMD"])(
293 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
294 (command) =>
295 Effect.gen(function* () {
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
299 const executable = path.join(cwd, "audit-command.cmd");
300 yield* fs.writeFileString(executable, "@echo off\n");
301​
302 const resolved = yield* resolveCommandPath(command, {
303 env: { PATH: cwd, PATHEXT: ".CMD" },
304 }).pipe(
305 Effect.provideService(HostProcess.Platform, "win32"),
306 Effect.provideService(CommandResolutionCache, new Map()),
307 Effect.provideService(FileSystem.FileSystem, {
308 ...fs,
309 stat: (filePath) =>
310 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
311 }),
312 );
313​
314 expect(resolved).toBe(executable);
315 }),
316 );
317​
318 it.effect("probes only listed PATH names and relists a directory that changes", () =>
319 Effect.gen(function* () {
320 const fs = yield* FileSystem.FileSystem;
321 const path = yield* Path.Path;
322 const first = yield* fs.makeTempDirectoryScoped();
323 const second = yield* fs.makeTempDirectoryScoped();
324 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
325 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
326 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
327 const probed: Array<string> = [];
328 yield* Effect.gen(function* () {
329 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
330 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
331 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
332 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
333 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
334 }).pipe(
335 withPathDirectoryListings,
336 Effect.provideService(FileSystem.FileSystem, {
337 ...fs,
338 stat: (file) => {
339 if (file !== first && file !== second) probed.push(file);
340 return fs.stat(file);
341 },
342 }),
343 );
344 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
345 }).pipe(
346 Effect.provideService(HostProcess.Platform, "win32"),
347 Effect.provideService(CommandResolutionCache, new Map()),
348 ),
349 );
350});
351​
352describe("preferGitForWindowsBinary", () => {
353 const files =
354 (...paths: Array<string>) =>
355 (filePath: string) =>
356 paths.includes(filePath);
357​
358 it("runs the git.exe Git for Windows' launcher would start", () => {
359 expect(
360 preferGitForWindowsBinary(
361 "C:\\Program Files\\Git\\cmd\\git.EXE",
362 {},
363 files(
364 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
365 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
366 ),
367 ),
368 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
369 expect(
370 preferGitForWindowsBinary(
371 "D:\\PortableGit\\bin\\git.exe",
372 {},
373 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
374 ),
375 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
376 expect(
377 preferGitForWindowsBinary(
378 "C:\\Program Files\\Git\\cmd\\git.exe",
379 {},
380 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
381 ),
382 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
383 });
384​
385 it("keeps the launcher when MSYSTEM is set", () => {
386 // The real git.exe only adds its own folders to PATH when MSYSTEM is unset;
387 // without them a `#!/bin/sh` hook cannot start.
388 expect(
389 preferGitForWindowsBinary(
390 "C:\\Program Files\\Git\\cmd\\git.exe",
391 { MSYSTEM: "MINGW64" },
392 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
393 ),
394 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
395 });
396​
397 it("leaves other gits and other launchers alone", () => {
398 const everything = () => true;
399 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
400 "C:\\Users\\me\\scoop\\shims\\git.exe",
401 );
402 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
403 "C:\\Program Files\\Git\\cmd\\gitk.exe",
404 );
405 });
406});
407​
408// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
409const NPM_OPENCODE_SHIM = [
410 "@ECHO off",
411 "GOTO start",
412 ":find_dp0",
413 "SET dp0=%~dp0",
414 "EXIT /b",
415 ":start",
416 "SETLOCAL",
417 "CALL :find_dp0",
418 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
419 "",
420].join("\r\n");
421​
422describe("npmShimExecutable", () => {
423 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
424 const executable =
425 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
426 const exists = (filePath: string) => filePath === executable;
427​
428 it("finds the executable npm's shim runs", () => {
429 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
430 expect(
431 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
432 ).toBe(executable);
433 });
434​
435 it("keeps a shim that does more than run the executable", () => {
436 const withSetting = NPM_OPENCODE_SHIM.replace(
437 "SETLOCAL",
438 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
439 );
440 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
441 const nodeScript = NPM_OPENCODE_SHIM.replace(
442 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
443 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
444 );
445 expect(
446 npmShimExecutable(
447 shimPath,
448 () => nodeScript,
449 () => true,
450 ),
451 ).toBeUndefined();
452 });
453​
454 it("keeps a shim CMD would read differently", () => {
455 // CMD keeps trailing characters in an unquoted `SET` value, so these point
456 // `dp0`, and with it the executable, somewhere else.
457 for (const suffix of ["\u00a0", "\t", " "]) {
458 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
459 expect(
460 npmShimExecutable(
461 shimPath,
462 () => altered,
463 () => true,
464 ),
465 ).toBeUndefined();
466 }
467 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
468 'opencode.exe" %*',
469 'opencode.exe"\u00a0%*',
470 );
471 expect(
472 npmShimExecutable(
473 shimPath,
474 () => nonBreakingSeparator,
475 () => true,
476 ),
477 ).toBeUndefined();
478 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
479 expect(
480 npmShimExecutable(
481 shimPath,
482 () => indented,
483 () => true,
484 ),
485 ).toBeUndefined();
486 });
487​
488 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
489 expect(
490 npmShimExecutable(
491 shimPath,
492 () => NPM_OPENCODE_SHIM,
493 () => false,
494 ),
495 ).toBeUndefined();
496 expect(
497 npmShimExecutable(
498 shimPath,
499 () => undefined,
500 () => true,
501 ),
502 ).toBeUndefined();
503 expect(
504 npmShimExecutable(
505 shimPath.replace(".cmd", ".bat"),
506 () => NPM_OPENCODE_SHIM,
507 () => true,
508 ),
509 ).toBeUndefined();
510 });
511});
512​
513effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
514 it.effect("runs Windows executables directly without a shell", () =>
515 Effect.gen(function* () {
516 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
517 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
518 }).pipe(
519 Effect.provideService(HostProcess.Platform, "win32"),
520 Effect.provideService(CommandResolutionCache, new Map()),
521 );
522​
523 expect(command).toEqual({
524 command: "node.exe",
525 args: ["script.js", "hello & goodbye"],
526 shell: false,
527 });
528 }),
529 );
530​
531 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
532 "runs the executable behind an npm shim directly when asked",
533 () =>
534 Effect.scoped(
535 Effect.gen(function* () {
536 const fs = yield* FileSystem.FileSystem;
537 const path = yield* Path.Path;
538 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
539 const shim = path.join(prefix, "opencode.cmd");
540 const executable = path.join(
541 prefix,
542 "node_modules",
543 "opencode-ai",
544 "bin",
545 "opencode.exe",
546 );
547 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
548 yield* fs.writeFileString(executable, "");
549 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
550 const resolve = (bypassNpmShim: boolean) =>
551 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
552 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
553 bypassNpmShim,
554 }).pipe(
555 Effect.provideService(HostProcess.Platform, "win32"),
556 Effect.provideService(CommandResolutionCache, new Map()),
557 Effect.provideService(SpawnExecutableResolution, () => shim),
558 );
559​
560 expect(yield* resolve(true)).toEqual({
561 command: executable,
562 args: ["serve", "--port=4096"],
563 shell: false,
564 });
565 expect((yield* resolve(false)).shell).toBe(true);
566 }),
567 ),
568 );
569​
570 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
571 Effect.gen(function* () {
572 const command = yield* resolveSpawnCommand(
573 "vp",
574 [
575 "run",
576 "value & calc",
577 "%PATH%",
578 'quote"value',
579 "C:\\dir with space\\",
580 'slash\\"quote',
581 "x|y<z>^",
582 ],
583 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
584 ).pipe(
585 Effect.provideService(HostProcess.Platform, "win32"),
586 Effect.provideService(CommandResolutionCache, new Map()),
587 Effect.provideService(
588 SpawnExecutableResolution,
589 () => "C:\\Program Files\\npm & tools\\vp.cmd",
590 ),
591 );
592​
593 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
594 expect(command).toEqual({
595 command: [
596 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
597 String.raw`^"run^"`,
598 String.raw`^"value^ ^&^ calc^"`,
599 String.raw`^"^%PATH^%^"`,
600 String.raw`^"quote\^"value^"`,
601 String.raw`^"C:\dir^ with^ space\\^"`,
602 String.raw`^"slash\\\^"quote^"`,
603 String.raw`^"x^|y^<z^>^^^"`,
604 ].join(" "),
605 args: [],
606 shell: true,
607 });
608 }),
609 );
610​
611 it.effect("resolves against the effective environment when extending host env", () =>
612 Effect.gen(function* () {
613 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
614 yield* resolveSpawnCommand("codex", ["app-server"], {
615 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
616 extendEnv: true,
617 }).pipe(
618 Effect.provideService(HostProcess.Platform, "win32"),
619 Effect.provideService(CommandResolutionCache, new Map()),
620 Effect.provideService(HostProcess.Environment, {
621 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
622 PATHEXT: ".COM;.EXE;.BAT;.CMD",
623 }),
624 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
625 resolvedEnvironment = env;
626 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
627 }),
628 );
629​
630 expect(resolvedEnvironment).toEqual({
631 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
632 PATHEXT: ".COM;.EXE;.BAT;.CMD",
633 CODEX_HOME: "C:\\Users\\tester\\.codex",
634 });
635 }),
636 );
637​
638 describe("macOS git", () => {
639 // Files that exist, the git first on PATH, and what `xcrun --find git` prints.
640 const setup = (options: {
641 readonly platform?: NodeJS.Platform;
642 readonly gitOnPath: string;
643 readonly xcrunGit: string | undefined;
644 }) => {
645 const files = new Set([options.gitOnPath, ...(options.xcrunGit ? [options.xcrunGit] : [])]);
646 const host = { xcrunGit: options.xcrunGit, xcrunCalls: 0 };
647 const resolve = resolveSpawnCommand("git", ["status"], { env: { PATH: "/fake/bin" } }).pipe(
648 Effect.map((resolved) => resolved.command),
649 Effect.provideService(HostProcess.Platform, options.platform ?? "darwin"),
650 Effect.provideService(SpawnExecutableResolution, (command) =>
651 command === "git" ? options.gitOnPath : files.has(command) ? command : undefined,
652 ),
653 Effect.provideService(XcodeGitLocation, () => {
654 host.xcrunCalls += 1;
655 return host.xcrunGit;
656 }),
657 );
658 return { files, host, resolve };
659 };
660​
661 const XCODE_GIT = "/Applications/Xcode.app/Contents/Developer/usr/bin/git";
662​
663 it.effect("runs the git behind the xcrun shim and looks it up once", () =>
664 Effect.gen(function* () {
665 const { host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
666 expect(yield* resolve).toBe(XCODE_GIT);
667 expect(yield* resolve).toBe(XCODE_GIT);
668 expect(host.xcrunCalls).toBe(1);
669 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
670 );
671​
672 it.effect("keeps git when PATH has another git or the host is not macOS", () =>
673 Effect.gen(function* () {
674 const homebrew = setup({ gitOnPath: "/opt/homebrew/bin/git", xcrunGit: XCODE_GIT });
675 expect(yield* homebrew.resolve).toBe("git");
676 expect(homebrew.host.xcrunCalls).toBe(0);
677​
678 const linux = setup({ platform: "linux", gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
679 expect(yield* linux.resolve).toBe("git");
680 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
681 );
682​
683 it.effect("keeps git when xcrun fails or names a missing file", () =>
684 Effect.gen(function* () {
685 const failed = setup({ gitOnPath: "/usr/bin/git", xcrunGit: undefined });
686 expect(yield* failed.resolve).toBe("git");
687​
688 const missing = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
689 missing.files.delete(XCODE_GIT);
690 expect(yield* missing.resolve).toBe("git");
691 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
692 );
693​
694 it.effect("looks again when the resolved git disappears", () =>
695 Effect.gen(function* () {
696 const betaGit = "/Applications/Xcode-beta.app/Contents/Developer/usr/bin/git";
697 const { files, host, resolve } = setup({ gitOnPath: "/usr/bin/git", xcrunGit: XCODE_GIT });
698 expect(yield* resolve).toBe(XCODE_GIT);
699​
700 files.delete(XCODE_GIT);
701 files.add(betaGit);
702 host.xcrunGit = betaGit;
703 expect(yield* resolve).toBe(betaGit);
704 expect(host.xcrunCalls).toBe(2);
705 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
706 );
707 });
708​
709 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
710 Effect.gen(function* () {
711 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
712 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
713 }).pipe(
714 Effect.provideService(HostProcess.Platform, "win32"),
715 Effect.provideService(CommandResolutionCache, new Map()),
716 );
717​
718 expect(command).toEqual({
719 command: "missing & calc",
720 args: ["unsafe & value"],
721 shell: false,
722 });
723 }),
724 );
725});
726​
727effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
728 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
729 Effect.gen(function* () {
730 const readEnvironment = vi.fn(
731 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
732 options?.loadProfile
733 ? { PATH: "C:\\Profile\\Bin" }
734 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
735 );
736 const commandAvailable = vi.fn(() => Effect.succeed(true));
737​
738 expect(
739 yield* withWindowsEnvironmentMocks(
740 resolveWindowsEnvironment({
741 PATH: "C:\\Windows\\System32",
742 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
743 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
744 USERPROFILE: "C:\\Users\\testuser",
745 }),
746 readEnvironment,
747 commandAvailable,
748 ),
749 ).toEqual({
750 PATH: [
751 "C:\\Shell\\Bin",
752 "C:\\Windows\\System32",
753 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
754 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
755 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
756 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
757 "C:\\Users\\testuser\\.local\\bin",
758 "C:\\Users\\testuser\\.bun\\bin",
759 "C:\\Users\\testuser\\scoop\\shims",
760 ].join(";"),
761 });
762 expect(readEnvironment).toHaveBeenCalledTimes(1);
763 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
764 expect(commandAvailable).toHaveBeenCalledWith(
765 "node",
766 expect.objectContaining({ env: expect.any(Object) }),
767 );
768 }),
769 );
770​
771 it.effect(
772 "probes node with one PATH key when inherited environment records have mixed casing",
773 () =>
774 Effect.gen(function* () {
775 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
776​
777 yield* withWindowsEnvironmentMocks(
778 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
779 () => ({ PATH: "C:\\Shell\\Bin" }),
780 (_command, options) =>
781 Effect.sync(() => {
782 probedEnvironments.push(options?.env);
783 return true;
784 }),
785 );
786​
787 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
788 ([key]) => key.toUpperCase() === "PATH",
789 );
790 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
791 }),
792 );
793​
794 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
795 Effect.gen(function* () {
796 const readEnvironment = vi.fn(
797 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
798 options?.loadProfile
799 ? {
800 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
801 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
802 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
803 }
804 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
805 );
806 const commandAvailable = vi.fn(() => Effect.succeed(false));
807​
808 expect(
809 yield* withWindowsEnvironmentMocks(
810 resolveWindowsEnvironment({
811 PATH: "C:\\Windows\\System32",
812 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
813 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
814 USERPROFILE: "C:\\Users\\testuser",
815 }),
816 readEnvironment,
817 commandAvailable,
818 ),
819 ).toEqual({
820 PATH: [
821 "C:\\Profile\\Node",
822 "C:\\Windows\\System32",
823 "C:\\Shell\\Bin",
824 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
825 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
826 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
827 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
828 "C:\\Users\\testuser\\.local\\bin",
829 "C:\\Users\\testuser\\.bun\\bin",
830 "C:\\Users\\testuser\\scoop\\shims",
831 ].join(";"),
832 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
833 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
834 });
835 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
836 expect(readEnvironment).toHaveBeenNthCalledWith(
837 2,
838 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
839 {
840 loadProfile: true,
841 },
842 );
843 expect(commandAvailable).toHaveBeenCalledTimes(1);
844 }),
845 );
846​
847 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
848 Effect.gen(function* () {
849 const readEnvironment = vi.fn(
850 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
851 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
852 );
853 const commandAvailable = vi.fn(() => Effect.succeed(false));
854​
855 expect(
856 yield* withWindowsEnvironmentMocks(
857 resolveWindowsEnvironment({
858 PATH: "C:\\Windows\\System32",
859 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
860 USERPROFILE: "C:\\Users\\testuser",
861 }),
862 readEnvironment,
863 commandAvailable,
864 ),
865 ).toEqual({
866 PATH: [
867 "C:\\Windows\\System32",
868 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
869 "C:\\Users\\testuser\\.local\\bin",
870 "C:\\Users\\testuser\\.bun\\bin",
871 "C:\\Users\\testuser\\scoop\\shims",
872 ].join(";"),
873 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
874 });
875 expect(commandAvailable).toHaveBeenCalledTimes(1);
876 }),
877 );
878});