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

shell.test.ts

688 lines23.6 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as TestClock from "effect/testing/TestClock";
8import { describe, expect, it, vi } from "vite-plus/test";
9​
10import {
11 CommandAvailability,
12 CommandResolutionCache,
13 type CommandAvailabilityChecker,
14 isCommandAvailable,
15 listLoginShellCandidates,
16 mergePathEntries,
17 mergePathValues,
18 readEnvironmentFromLoginShell,
19 readEnvironmentFromWindowsShell,
20 readPathFromLaunchctl,
21 readPathFromLoginShell,
22 resolveCommandPath,
23 resolveKnownWindowsCliDirs,
24 resolveSpawnCommand,
25 resolveWindowsEnvironment,
26 SpawnExecutableResolution,
27 WindowsShellEnvironment,
28 type WindowsShellEnvironmentReader,
29} from "./shell.ts";
30​
31const withWindowsEnvironmentMocks = <A, E, R>(
32 effect: Effect.Effect<A, E, R>,
33 readEnvironment: WindowsShellEnvironmentReader,
34 commandAvailable: CommandAvailabilityChecker,
35) =>
36 effect.pipe(
37 Effect.provideService(WindowsShellEnvironment, readEnvironment),
38 Effect.provideService(CommandAvailability, commandAvailable),
39 );
40​
41describe("readPathFromLoginShell", () => {
42 it("uses a shell-agnostic printenv PATH probe", () => {
43 const execFile = vi.fn<
44 (
45 file: string,
46 args: ReadonlyArray<string>,
47 options: { encoding: "utf8"; timeout: number },
48 ) => string
49 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
50​
51 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
52 expect(execFile).toHaveBeenCalledTimes(1);
53​
54 const firstCall = execFile.mock.calls[0] as
55 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
56 | undefined;
57 expect(firstCall).toBeDefined();
58 if (!firstCall) {
59 throw new Error("Expected execFile to be called");
60 }
61​
62 const [shell, args, options] = firstCall;
63 expect(shell).toBe("/opt/homebrew/bin/fish");
64 expect(args).toHaveLength(2);
65 expect(args?.[0]).toBe("-ilc");
66 expect(args?.[1]).toContain("printenv PATH || true");
67 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
68 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
69 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
70 });
71});
72​
73describe("readPathFromLaunchctl", () => {
74 it("returns a trimmed PATH value from launchctl", () => {
75 const execFile = vi.fn<
76 (
77 file: string,
78 args: ReadonlyArray<string>,
79 options: { encoding: "utf8"; timeout: number },
80 ) => string
81 >(() => " /opt/homebrew/bin:/usr/bin \n");
82​
83 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
84 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
85 encoding: "utf8",
86 timeout: 2000,
87 });
88 });
89​
90 it("returns undefined when launchctl is unavailable", () => {
91 const execFile = vi.fn<
92 (
93 file: string,
94 args: ReadonlyArray<string>,
95 options: { encoding: "utf8"; timeout: number },
96 ) => string
97 >(() => {
98 throw new Error("spawn /bin/launchctl ENOENT");
99 });
100​
101 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
102 });
103});
104​
105describe("readEnvironmentFromLoginShell", () => {
106 it("extracts multiple environment variables from a login shell command", () => {
107 const execFile = vi.fn<
108 (
109 file: string,
110 args: ReadonlyArray<string>,
111 options: { encoding: "utf8"; timeout: number },
112 ) => string
113 >(() =>
114 [
115 "__T3CODE_ENV_PATH_START__",
116 "/a:/b",
117 "__T3CODE_ENV_PATH_END__",
118 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
119 "/tmp/secretive.sock",
120 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
121 ].join("\n"),
122 );
123​
124 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
125 PATH: "/a:/b",
126 SSH_AUTH_SOCK: "/tmp/secretive.sock",
127 });
128 expect(execFile).toHaveBeenCalledTimes(1);
129 });
130​
131 it("omits environment variables that are missing or empty", () => {
132 const execFile = vi.fn<
133 (
134 file: string,
135 args: ReadonlyArray<string>,
136 options: { encoding: "utf8"; timeout: number },
137 ) => string
138 >(() =>
139 [
140 "__T3CODE_ENV_PATH_START__",
141 "/a:/b",
142 "__T3CODE_ENV_PATH_END__",
143 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
144 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
145 ].join("\n"),
146 );
147​
148 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
149 PATH: "/a:/b",
150 });
151 });
152​
153 it("preserves surrounding whitespace in captured values", () => {
154 const execFile = vi.fn<
155 (
156 file: string,
157 args: ReadonlyArray<string>,
158 options: { encoding: "utf8"; timeout: number },
159 ) => string
160 >(() =>
161 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
162 "\n",
163 ),
164 );
165​
166 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
167 CUSTOM_VAR: " padded value ",
168 });
169 });
170});
171​
172describe("listLoginShellCandidates", () => {
173 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
174 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
175 "/opt/homebrew/bin/nu",
176 "/bin/zsh",
177 ]);
178 });
179​
180 it("falls back to the platform default when no shells are available", () => {
181 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
182 });
183});
184​
185describe("mergePathEntries", () => {
186 it("prefers login-shell PATH entries and keeps inherited extras", () => {
187 expect(
188 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
189 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
190 });
191​
192 it("uses the platform-specific delimiter", () => {
193 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
194 "C:\\Tools;C:\\Windows;C:\\Git",
195 );
196 });
197});
198​
199describe("readEnvironmentFromWindowsShell", () => {
200 it("extracts environment variables from a PowerShell command", () => {
201 const execFile = vi.fn<
202 (
203 file: string,
204 args: ReadonlyArray<string>,
205 options: { encoding: "utf8"; timeout: number },
206 ) => string
207 >(
208 () =>
209 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
210 );
211​
212 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
213 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
214 });
215 expect(execFile).toHaveBeenCalledWith(
216 "pwsh.exe",
217 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
218 { encoding: "utf8", timeout: 5000 },
219 );
220 });
221​
222 it("strips CRLF delimiters from captured PowerShell values", () => {
223 const execFile = vi.fn<
224 (
225 file: string,
226 args: ReadonlyArray<string>,
227 options: { encoding: "utf8"; timeout: number },
228 ) => string
229 >(
230 () =>
231 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
232 );
233​
234 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
235 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
236 });
237 });
238​
239 it("omits -NoProfile when loadProfile is enabled", () => {
240 const execFile = vi.fn<
241 (
242 file: string,
243 args: ReadonlyArray<string>,
244 options: { encoding: "utf8"; timeout: number },
245 ) => string
246 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
247​
248 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
249 PATH: "C:\\Tools",
250 });
251 expect(execFile).toHaveBeenCalledWith(
252 "pwsh.exe",
253 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
254 { encoding: "utf8", timeout: 5000 },
255 );
256 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
257 });
258​
259 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
260 const execFile = vi.fn<
261 (
262 file: string,
263 args: ReadonlyArray<string>,
264 options: { encoding: "utf8"; timeout: number },
265 ) => string
266 >((file) => {
267 if (file === "pwsh.exe") {
268 throw new Error("spawn pwsh.exe ENOENT");
269 }
270 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
271 });
272​
273 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
274 PATH: "C:\\Tools",
275 });
276 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
277 encoding: "utf8",
278 timeout: 5000,
279 });
280 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
281 encoding: "utf8",
282 timeout: 5000,
283 });
284 });
285});
286​
287describe("mergePathValues", () => {
288 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
289 expect(
290 mergePathValues(
291 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
292 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
293 "win32",
294 ),
295 ).toBe(
296 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
297 );
298 });
299​
300 it("removes stray quotes from Windows entries", () => {
301 expect(
302 mergePathValues(
303 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
304 undefined,
305 "win32",
306 ),
307 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
308 });
309​
310 it("dedupes case-sensitively on POSIX", () => {
311 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
312 "/usr/local/bin:/usr/bin:/USR/BIN",
313 );
314 });
315});
316​
317describe("resolveKnownWindowsCliDirs", () => {
318 it("returns known Windows CLI install directories in priority order", () => {
319 expect(
320 resolveKnownWindowsCliDirs({
321 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
322 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
323 USERPROFILE: "C:\\Users\\testuser",
324 }),
325 ).toEqual([
326 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
327 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
328 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
329 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
330 "C:\\Users\\testuser\\.local\\bin",
331 "C:\\Users\\testuser\\.bun\\bin",
332 "C:\\Users\\testuser\\scoop\\shims",
333 ]);
334 });
335});
336​
337effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
338 it.effect("returns false when PATH is empty", () =>
339 Effect.gen(function* () {
340 expect(
341 yield* isCommandAvailable("definitely-not-installed", {
342 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
343 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
344 ).toBe(false);
345 }),
346 );
347});
348​
349effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
350 it.effect("fails when PATH is empty", () =>
351 Effect.gen(function* () {
352 const result = yield* resolveCommandPath("definitely-not-installed", {
353 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
354 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
355​
356 expect(result._tag).toBe("Failure");
357 }),
358 );
359​
360 // Records every path the scan stats, without ever reporting a match, so the
361 // walk runs to exhaustion and the probe set can be inspected. Assertions
362 // below count probes rather than naming paths: `Path` is the host's, so the
363 // separator differs between a Windows and a Linux CI runner.
364 const recordProbes = (env: NodeJS.ProcessEnv) =>
365 Effect.gen(function* () {
366 const probed: Array<string> = [];
367 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
368 Effect.provideService(HostProcessPlatform, "win32"),
369 Effect.provideService(CommandResolutionCache, new Map()),
370 Effect.provide(
371 FileSystem.layerNoop({
372 stat: (filePath) =>
373 Effect.sync(() => {
374 probed.push(filePath);
375 return { type: "Directory" } as FileSystem.File.Info;
376 }),
377 }),
378 ),
379 Effect.result,
380 );
381​
382 expect(result._tag).toBe("Failure");
383 return probed;
384 });
385​
386 it.effect("visits a repeated PATH directory only once", () =>
387 Effect.gen(function* () {
388 const probed = yield* recordProbes({
389 PATH: "C:\\bin;C:\\other;C:\\bin;C:\\other",
390 PATHEXT: ".COM;.EXE",
391 });
392​
393 // Two directories, two extensions, upper and lowercase spellings.
394 expect(probed).toHaveLength(8);
395 expect(new Set(probed).size).toBe(probed.length);
396 }),
397 );
398​
399 it.effect("still visits a PATH entry that differs only in case", () =>
400 Effect.gen(function* () {
401 const probed = yield* recordProbes({
402 PATH: "C:\\bin;C:\\BIN",
403 PATHEXT: ".COM;.EXE",
404 });
405​
406 // Deliberately not folded together. Windows 10+ can mark a directory
407 // case-sensitive, so the two spellings are not provably one directory and
408 // skipping the second could hide a command that is really there.
409 expect(probed).toHaveLength(8);
410 }),
411 );
412​
413 it.effect.each(["audit-command", "audit-command.CMD"])(
414 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
415 (command) =>
416 Effect.gen(function* () {
417 const fs = yield* FileSystem.FileSystem;
418 const path = yield* Path.Path;
419 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
420 const executable = path.join(cwd, "audit-command.cmd");
421 yield* fs.writeFileString(executable, "@echo off\n");
422​
423 const resolved = yield* resolveCommandPath(command, {
424 env: { PATH: cwd, PATHEXT: ".CMD" },
425 }).pipe(
426 Effect.provideService(HostProcessPlatform, "win32"),
427 Effect.provideService(CommandResolutionCache, new Map()),
428 Effect.provideService(FileSystem.FileSystem, {
429 ...fs,
430 // Keep this case-sensitive fixture portable to case-insensitive hosts.
431 stat: (filePath) =>
432 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
433 }),
434 );
435​
436 expect(resolved).toBe(executable);
437 }),
438 );
439​
440 it.effect("keeps cached misses until expiry while allowing explicit paths", () =>
441 Effect.gen(function* () {
442 const fs = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-path-cache-" });
445 const executable = path.join(cwd, "appeared.CMD");
446 const options = { env: { PATH: `${cwd};${cwd}`, PATHEXT: ".CMD" } };
447​
448 expect((yield* resolveCommandPath("appeared", options).pipe(Effect.result))._tag).toBe(
449 "Failure",
450 );
451 yield* fs.writeFileString(executable, "@echo off\n");
452 expect((yield* resolveCommandPath("appeared", options).pipe(Effect.result))._tag).toBe(
453 "Failure",
454 );
455 expect(yield* resolveCommandPath(executable, options)).toBe(executable);
456 yield* TestClock.adjust("30 seconds");
457 expect(yield* resolveCommandPath("appeared", options)).toBe(executable);
458 }).pipe(
459 Effect.provideService(HostProcessPlatform, "win32"),
460 Effect.provideService(CommandResolutionCache, new Map()),
461 ),
462 );
463​
464 it.effect("keeps upper and lowercase PATHEXT candidates", () =>
465 Effect.gen(function* () {
466 const probed = yield* recordProbes({
467 PATH: "C:\\bin",
468 PATHEXT: ".COM;.EXE;.BAT;.CMD",
469 });
470​
471 expect(probed).toHaveLength(8);
472 expect(probed.filter((filePath) => /\.(COM|EXE|BAT|CMD)$/.test(filePath))).toHaveLength(4);
473 expect(probed.filter((filePath) => /\.(com|exe|bat|cmd)$/.test(filePath))).toHaveLength(4);
474 }),
475 );
476});
477​
478effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
479 it.effect("runs Windows executables directly without a shell", () =>
480 Effect.gen(function* () {
481 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
482 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
483 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
484​
485 expect(command).toEqual({
486 command: "node.exe",
487 args: ["script.js", "hello & goodbye"],
488 shell: false,
489 });
490 }),
491 );
492​
493 it.effect("escapes the executable and arguments for Windows command shims", () =>
494 Effect.gen(function* () {
495 const command = yield* resolveSpawnCommand(
496 "vp",
497 ["run", "value & calc", "%PATH%", 'quote"value'],
498 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
499 ).pipe(
500 Effect.provideService(HostProcessPlatform, "win32"),
501 Effect.provideService(
502 SpawnExecutableResolution,
503 () => "C:\\Program Files\\npm & tools\\vp.cmd",
504 ),
505 );
506​
507 expect(command.shell).toBe(true);
508 expect(command.command).not.toContain(" & ");
509 expect(command.command).toContain("^&");
510 expect(command.args).toEqual([
511 '^"run^"',
512 '^"value^ ^&^ calc^"',
513 '^"^%PATH^%^"',
514 '^"quote\\^"value^"',
515 ]);
516 }),
517 );
518​
519 it.effect("resolves against the effective environment when extending host env", () =>
520 Effect.gen(function* () {
521 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
522 yield* resolveSpawnCommand("codex", ["app-server"], {
523 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
524 extendEnv: true,
525 }).pipe(
526 Effect.provideService(HostProcessPlatform, "win32"),
527 Effect.provideService(HostProcessEnvironment, {
528 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
529 PATHEXT: ".COM;.EXE;.BAT;.CMD",
530 }),
531 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
532 resolvedEnvironment = env;
533 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
534 }),
535 );
536​
537 expect(resolvedEnvironment).toEqual({
538 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
539 PATHEXT: ".COM;.EXE;.BAT;.CMD",
540 CODEX_HOME: "C:\\Users\\tester\\.codex",
541 });
542 }),
543 );
544​
545 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
546 Effect.gen(function* () {
547 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
548 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
549 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
550​
551 expect(command).toEqual({
552 command: "missing & calc",
553 args: ["unsafe & value"],
554 shell: false,
555 });
556 }),
557 );
558});
559​
560effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
561 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
562 Effect.gen(function* () {
563 const readEnvironment = vi.fn(
564 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
565 options?.loadProfile
566 ? { PATH: "C:\\Profile\\Bin" }
567 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
568 );
569 const commandAvailable = vi.fn(() => Effect.succeed(true));
570​
571 expect(
572 yield* withWindowsEnvironmentMocks(
573 resolveWindowsEnvironment({
574 PATH: "C:\\Windows\\System32",
575 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
576 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
577 USERPROFILE: "C:\\Users\\testuser",
578 }),
579 readEnvironment,
580 commandAvailable,
581 ),
582 ).toEqual({
583 PATH: [
584 "C:\\Shell\\Bin",
585 "C:\\Windows\\System32",
586 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
587 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
588 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
589 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
590 "C:\\Users\\testuser\\.local\\bin",
591 "C:\\Users\\testuser\\.bun\\bin",
592 "C:\\Users\\testuser\\scoop\\shims",
593 ].join(";"),
594 });
595 expect(readEnvironment).toHaveBeenCalledTimes(1);
596 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
597 expect(commandAvailable).toHaveBeenCalledWith(
598 "node",
599 expect.objectContaining({ env: expect.any(Object) }),
600 );
601 }),
602 );
603​
604 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
605 Effect.gen(function* () {
606 const readEnvironment = vi.fn(
607 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
608 options?.loadProfile
609 ? {
610 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
611 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
612 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
613 }
614 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
615 );
616 const commandAvailable = vi.fn(() => Effect.succeed(false));
617​
618 expect(
619 yield* withWindowsEnvironmentMocks(
620 resolveWindowsEnvironment({
621 PATH: "C:\\Windows\\System32",
622 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
623 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
624 USERPROFILE: "C:\\Users\\testuser",
625 }),
626 readEnvironment,
627 commandAvailable,
628 ),
629 ).toEqual({
630 PATH: [
631 "C:\\Profile\\Node",
632 "C:\\Windows\\System32",
633 "C:\\Shell\\Bin",
634 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
635 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
636 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
637 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
638 "C:\\Users\\testuser\\.local\\bin",
639 "C:\\Users\\testuser\\.bun\\bin",
640 "C:\\Users\\testuser\\scoop\\shims",
641 ].join(";"),
642 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
643 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
644 });
645 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
646 expect(readEnvironment).toHaveBeenNthCalledWith(
647 2,
648 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
649 {
650 loadProfile: true,
651 },
652 );
653 expect(commandAvailable).toHaveBeenCalledTimes(1);
654 }),
655 );
656​
657 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
658 Effect.gen(function* () {
659 const readEnvironment = vi.fn(
660 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
661 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
662 );
663 const commandAvailable = vi.fn(() => Effect.succeed(false));
664​
665 expect(
666 yield* withWindowsEnvironmentMocks(
667 resolveWindowsEnvironment({
668 PATH: "C:\\Windows\\System32",
669 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
670 USERPROFILE: "C:\\Users\\testuser",
671 }),
672 readEnvironment,
673 commandAvailable,
674 ),
675 ).toEqual({
676 PATH: [
677 "C:\\Windows\\System32",
678 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
679 "C:\\Users\\testuser\\.local\\bin",
680 "C:\\Users\\testuser\\.bun\\bin",
681 "C:\\Users\\testuser\\scoop\\shims",
682 ].join(";"),
683 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
684 });
685 expect(commandAvailable).toHaveBeenCalledTimes(1);
686 }),
687 );
688});