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