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