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 { describe, expect, it, vi } from "vite-plus/test";
6
7import {
8 extractPathFromShellOutput,
9 CommandAvailability,
10 type CommandAvailabilityChecker,
11 isCommandAvailable,
12 listLoginShellCandidates,
13 mergePathEntries,
14 mergePathValues,
15 readEnvironmentFromLoginShell,
16 readEnvironmentFromWindowsShell,
17 readPathFromLaunchctl,
18 readPathFromLoginShell,
19 resolveCommandPath,
20 resolveKnownWindowsCliDirs,
21 resolveSpawnCommand,
22 resolveWindowsEnvironment,
23 SpawnExecutableResolution,
24 WindowsShellEnvironment,
25 type WindowsShellEnvironmentReader,
26} from "./shell.ts";
27
28const withWindowsEnvironmentMocks = <A, E, R>(
29 effect: Effect.Effect<A, E, R>,
30 readEnvironment: WindowsShellEnvironmentReader,
31 commandAvailable: CommandAvailabilityChecker,
32) =>
33 effect.pipe(
34 Effect.provideService(WindowsShellEnvironment, readEnvironment),
35 Effect.provideService(CommandAvailability, commandAvailable),
36 );
37
38describe("extractPathFromShellOutput", () => {
39 it("extracts the path between capture markers", () => {
40 expect(
41 extractPathFromShellOutput(
42 "__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n",
43 ),
44 ).toBe("/opt/homebrew/bin:/usr/bin");
45 });
46
47 it("ignores shell startup noise around the capture markers", () => {
48 expect(
49 extractPathFromShellOutput(
50 "Welcome to fish\n__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\nBye\n",
51 ),
52 ).toBe("/opt/homebrew/bin:/usr/bin");
53 });
54
55 it("returns null when the markers are missing", () => {
56 expect(extractPathFromShellOutput("/opt/homebrew/bin /usr/bin")).toBeNull();
57 });
58});
59
60describe("readPathFromLoginShell", () => {
61 it("uses a shell-agnostic printenv PATH probe", () => {
62 const execFile = vi.fn<
63 (
64 file: string,
65 args: ReadonlyArray<string>,
66 options: { encoding: "utf8"; timeout: number },
67 ) => string
68 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
69
70 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
71 expect(execFile).toHaveBeenCalledTimes(1);
72
73 const firstCall = execFile.mock.calls[0] as
74 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
75 | undefined;
76 expect(firstCall).toBeDefined();
77 if (!firstCall) {
78 throw new Error("Expected execFile to be called");
79 }
80
81 const [shell, args, options] = firstCall;
82 expect(shell).toBe("/opt/homebrew/bin/fish");
83 expect(args).toHaveLength(2);
84 expect(args?.[0]).toBe("-ilc");
85 expect(args?.[1]).toContain("printenv PATH || true");
86 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
87 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
88 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
89 });
90});
91
92describe("readPathFromLaunchctl", () => {
93 it("returns a trimmed PATH value from launchctl", () => {
94 const execFile = vi.fn<
95 (
96 file: string,
97 args: ReadonlyArray<string>,
98 options: { encoding: "utf8"; timeout: number },
99 ) => string
100 >(() => " /opt/homebrew/bin:/usr/bin \n");
101
102 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
103 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
104 encoding: "utf8",
105 timeout: 2000,
106 });
107 });
108
109 it("returns undefined when launchctl is unavailable", () => {
110 const execFile = vi.fn<
111 (
112 file: string,
113 args: ReadonlyArray<string>,
114 options: { encoding: "utf8"; timeout: number },
115 ) => string
116 >(() => {
117 throw new Error("spawn /bin/launchctl ENOENT");
118 });
119
120 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
121 });
122});
123
124describe("readEnvironmentFromLoginShell", () => {
125 it("extracts multiple environment variables from a login shell command", () => {
126 const execFile = vi.fn<
127 (
128 file: string,
129 args: ReadonlyArray<string>,
130 options: { encoding: "utf8"; timeout: number },
131 ) => string
132 >(() =>
133 [
134 "__T3CODE_ENV_PATH_START__",
135 "/a:/b",
136 "__T3CODE_ENV_PATH_END__",
137 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
138 "/tmp/secretive.sock",
139 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
140 ].join("\n"),
141 );
142
143 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
144 PATH: "/a:/b",
145 SSH_AUTH_SOCK: "/tmp/secretive.sock",
146 });
147 expect(execFile).toHaveBeenCalledTimes(1);
148 });
149
150 it("omits environment variables that are missing or empty", () => {
151 const execFile = vi.fn<
152 (
153 file: string,
154 args: ReadonlyArray<string>,
155 options: { encoding: "utf8"; timeout: number },
156 ) => string
157 >(() =>
158 [
159 "__T3CODE_ENV_PATH_START__",
160 "/a:/b",
161 "__T3CODE_ENV_PATH_END__",
162 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
163 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
164 ].join("\n"),
165 );
166
167 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
168 PATH: "/a:/b",
169 });
170 });
171
172 it("preserves surrounding whitespace in captured values", () => {
173 const execFile = vi.fn<
174 (
175 file: string,
176 args: ReadonlyArray<string>,
177 options: { encoding: "utf8"; timeout: number },
178 ) => string
179 >(() =>
180 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
181 "\n",
182 ),
183 );
184
185 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
186 CUSTOM_VAR: " padded value ",
187 });
188 });
189});
190
191describe("listLoginShellCandidates", () => {
192 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
193 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
194 "/opt/homebrew/bin/nu",
195 "/bin/zsh",
196 ]);
197 });
198
199 it("falls back to the platform default when no shells are available", () => {
200 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
201 });
202});
203
204describe("mergePathEntries", () => {
205 it("prefers login-shell PATH entries and keeps inherited extras", () => {
206 expect(
207 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
208 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
209 });
210
211 it("uses the platform-specific delimiter", () => {
212 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
213 "C:\\Tools;C:\\Windows;C:\\Git",
214 );
215 });
216});
217
218describe("readEnvironmentFromWindowsShell", () => {
219 it("extracts environment variables from a PowerShell command", () => {
220 const execFile = vi.fn<
221 (
222 file: string,
223 args: ReadonlyArray<string>,
224 options: { encoding: "utf8"; timeout: number },
225 ) => string
226 >(
227 () =>
228 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
229 );
230
231 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
232 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
233 });
234 expect(execFile).toHaveBeenCalledWith(
235 "pwsh.exe",
236 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
237 { encoding: "utf8", timeout: 5000 },
238 );
239 });
240
241 it("strips CRLF delimiters from captured PowerShell values", () => {
242 const execFile = vi.fn<
243 (
244 file: string,
245 args: ReadonlyArray<string>,
246 options: { encoding: "utf8"; timeout: number },
247 ) => string
248 >(
249 () =>
250 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
251 );
252
253 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
254 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
255 });
256 });
257
258 it("omits -NoProfile when loadProfile is enabled", () => {
259 const execFile = vi.fn<
260 (
261 file: string,
262 args: ReadonlyArray<string>,
263 options: { encoding: "utf8"; timeout: number },
264 ) => string
265 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
266
267 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
268 PATH: "C:\\Tools",
269 });
270 expect(execFile).toHaveBeenCalledWith(
271 "pwsh.exe",
272 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
273 { encoding: "utf8", timeout: 5000 },
274 );
275 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
276 });
277
278 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
279 const execFile = vi.fn<
280 (
281 file: string,
282 args: ReadonlyArray<string>,
283 options: { encoding: "utf8"; timeout: number },
284 ) => string
285 >((file) => {
286 if (file === "pwsh.exe") {
287 throw new Error("spawn pwsh.exe ENOENT");
288 }
289 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
290 });
291
292 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
293 PATH: "C:\\Tools",
294 });
295 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
296 encoding: "utf8",
297 timeout: 5000,
298 });
299 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
300 encoding: "utf8",
301 timeout: 5000,
302 });
303 });
304});
305
306describe("mergePathValues", () => {
307 it("dedupes case-insensitively on Windows while preserving preferred order", () => {
308 expect(
309 mergePathValues(
310 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
311 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
312 "win32",
313 ),
314 ).toBe(
315 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs";C:\\Windows\\System32',
316 );
317 });
318
319 it("dedupes case-sensitively on POSIX", () => {
320 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
321 "/usr/local/bin:/usr/bin:/USR/BIN",
322 );
323 });
324});
325
326describe("resolveKnownWindowsCliDirs", () => {
327 it("returns known Windows CLI install directories in priority order", () => {
328 expect(
329 resolveKnownWindowsCliDirs({
330 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
331 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
332 USERPROFILE: "C:\\Users\\testuser",
333 }),
334 ).toEqual([
335 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
336 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
337 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
338 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
339 "C:\\Users\\testuser\\.local\\bin",
340 "C:\\Users\\testuser\\.bun\\bin",
341 "C:\\Users\\testuser\\scoop\\shims",
342 ]);
343 });
344});
345
346effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
347 it.effect("returns false when PATH is empty", () =>
348 Effect.gen(function* () {
349 expect(
350 yield* isCommandAvailable("definitely-not-installed", {
351 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
352 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
353 ).toBe(false);
354 }),
355 );
356});
357
358effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
359 it.effect("fails when PATH is empty", () =>
360 Effect.gen(function* () {
361 const result = yield* resolveCommandPath("definitely-not-installed", {
362 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
363 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
364
365 expect(result._tag).toBe("Failure");
366 }),
367 );
368});
369
370effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
371 it.effect("runs Windows executables directly without a shell", () =>
372 Effect.gen(function* () {
373 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
374 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
375 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
376
377 expect(command).toEqual({
378 command: "node.exe",
379 args: ["script.js", "hello & goodbye"],
380 shell: false,
381 });
382 }),
383 );
384
385 it.effect("escapes the executable and arguments for Windows command shims", () =>
386 Effect.gen(function* () {
387 const command = yield* resolveSpawnCommand(
388 "vp",
389 ["run", "value & calc", "%PATH%", 'quote"value'],
390 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
391 ).pipe(
392 Effect.provideService(HostProcessPlatform, "win32"),
393 Effect.provideService(
394 SpawnExecutableResolution,
395 () => "C:\\Program Files\\npm & tools\\vp.cmd",
396 ),
397 );
398
399 expect(command.shell).toBe(true);
400 expect(command.command).not.toContain(" & ");
401 expect(command.command).toContain("^&");
402 expect(command.args).toEqual([
403 '^"run^"',
404 '^"value^ ^&^ calc^"',
405 '^"^%PATH^%^"',
406 '^"quote\\^"value^"',
407 ]);
408 }),
409 );
410
411 it.effect("resolves against the effective environment when extending host env", () =>
412 Effect.gen(function* () {
413 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
414 yield* resolveSpawnCommand("codex", ["app-server"], {
415 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
416 extendEnv: true,
417 }).pipe(
418 Effect.provideService(HostProcessPlatform, "win32"),
419 Effect.provideService(HostProcessEnvironment, {
420 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
421 PATHEXT: ".COM;.EXE;.BAT;.CMD",
422 }),
423 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
424 resolvedEnvironment = env;
425 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
426 }),
427 );
428
429 expect(resolvedEnvironment).toEqual({
430 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
431 PATHEXT: ".COM;.EXE;.BAT;.CMD",
432 CODEX_HOME: "C:\\Users\\tester\\.codex",
433 });
434 }),
435 );
436
437 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
438 Effect.gen(function* () {
439 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
440 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
441 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
442
443 expect(command).toEqual({
444 command: "missing & calc",
445 args: ["unsafe & value"],
446 shell: false,
447 });
448 }),
449 );
450});
451
452effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
453 it.effect("returns the baseline no-profile PATH patch when node is already available", () =>
454 Effect.gen(function* () {
455 const readEnvironment = vi.fn(
456 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
457 options?.loadProfile
458 ? { PATH: "C:\\Profile\\Bin" }
459 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
460 );
461 const commandAvailable = vi.fn(() => Effect.succeed(true));
462
463 expect(
464 yield* withWindowsEnvironmentMocks(
465 resolveWindowsEnvironment({
466 PATH: "C:\\Windows\\System32",
467 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
468 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
469 USERPROFILE: "C:\\Users\\testuser",
470 }),
471 readEnvironment,
472 commandAvailable,
473 ),
474 ).toEqual({
475 PATH: [
476 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
477 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
478 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
479 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
480 "C:\\Users\\testuser\\.local\\bin",
481 "C:\\Users\\testuser\\.bun\\bin",
482 "C:\\Users\\testuser\\scoop\\shims",
483 "C:\\Shell\\Bin",
484 "C:\\Windows\\System32",
485 ].join(";"),
486 });
487 expect(readEnvironment).toHaveBeenCalledTimes(1);
488 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
489 expect(commandAvailable).toHaveBeenCalledWith(
490 "node",
491 expect.objectContaining({ env: expect.any(Object) }),
492 );
493 }),
494 );
495
496 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
497 Effect.gen(function* () {
498 const readEnvironment = vi.fn(
499 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
500 options?.loadProfile
501 ? {
502 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
503 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
504 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
505 }
506 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
507 );
508 const commandAvailable = vi.fn(() => Effect.succeed(false));
509
510 expect(
511 yield* withWindowsEnvironmentMocks(
512 resolveWindowsEnvironment({
513 PATH: "C:\\Windows\\System32",
514 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
515 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
516 USERPROFILE: "C:\\Users\\testuser",
517 }),
518 readEnvironment,
519 commandAvailable,
520 ),
521 ).toEqual({
522 PATH: [
523 "C:\\Profile\\Node",
524 "C:\\Windows\\System32",
525 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
526 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
527 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
528 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
529 "C:\\Users\\testuser\\.local\\bin",
530 "C:\\Users\\testuser\\.bun\\bin",
531 "C:\\Users\\testuser\\scoop\\shims",
532 "C:\\Shell\\Bin",
533 ].join(";"),
534 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
535 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
536 });
537 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
538 expect(readEnvironment).toHaveBeenNthCalledWith(
539 2,
540 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
541 {
542 loadProfile: true,
543 },
544 );
545 expect(commandAvailable).toHaveBeenCalledTimes(1);
546 }),
547 );
548
549 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
550 Effect.gen(function* () {
551 const readEnvironment = vi.fn(
552 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
553 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
554 );
555 const commandAvailable = vi.fn(() => Effect.succeed(false));
556
557 expect(
558 yield* withWindowsEnvironmentMocks(
559 resolveWindowsEnvironment({
560 PATH: "C:\\Windows\\System32",
561 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
562 USERPROFILE: "C:\\Users\\testuser",
563 }),
564 readEnvironment,
565 commandAvailable,
566 ),
567 ).toEqual({
568 PATH: [
569 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
570 "C:\\Users\\testuser\\.local\\bin",
571 "C:\\Users\\testuser\\.bun\\bin",
572 "C:\\Users\\testuser\\scoop\\shims",
573 "C:\\Windows\\System32",
574 ].join(";"),
575 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
576 });
577 expect(commandAvailable).toHaveBeenCalledTimes(1);
578 }),
579 );
580});