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

shell.test.ts

574 lines19.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import { HostProcessEnvironment, HostProcessPlatform } from "@v12/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 "__V12_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__V12_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__V12_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__V12_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 >(() => "__V12_ENV_PATH_START__\n/a:/b\n__V12_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("__V12_ENV_PATH_START__");
87 expect(args?.[1]).toContain("__V12_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 "__V12_ENV_PATH_START__",
135 "/a:/b",
136 "__V12_ENV_PATH_END__",
137 "__V12_ENV_SSH_AUTH_SOCK_START__",
138 "/tmp/secretive.sock",
139 "__V12_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 "__V12_ENV_PATH_START__",
160 "/a:/b",
161 "__V12_ENV_PATH_END__",
162 "__V12_ENV_SSH_AUTH_SOCK_START__",
163 "__V12_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 ["__V12_ENV_CUSTOM_VAR_START__", " padded value ", "__V12_ENV_CUSTOM_VAR_END__"].join("\n"),
181 );
182​
183 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
184 CUSTOM_VAR: " padded value ",
185 });
186 });
187});
188​
189describe("listLoginShellCandidates", () => {
190 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
191 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
192 "/opt/homebrew/bin/nu",
193 "/bin/zsh",
194 ]);
195 });
196​
197 it("falls back to the platform default when no shells are available", () => {
198 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
199 });
200});
201​
202describe("mergePathEntries", () => {
203 it("prefers login-shell PATH entries and keeps inherited extras", () => {
204 expect(
205 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
206 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
207 });
208​
209 it("uses the platform-specific delimiter", () => {
210 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
211 "C:\\Tools;C:\\Windows;C:\\Git",
212 );
213 });
214});
215​
216describe("readEnvironmentFromWindowsShell", () => {
217 it("extracts environment variables from a PowerShell command", () => {
218 const execFile = vi.fn<
219 (
220 file: string,
221 args: ReadonlyArray<string>,
222 options: { encoding: "utf8"; timeout: number },
223 ) => string
224 >(
225 () =>
226 "__V12_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__V12_ENV_PATH_END__\n",
227 );
228​
229 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
230 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
231 });
232 expect(execFile).toHaveBeenCalledWith(
233 "pwsh.exe",
234 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
235 { encoding: "utf8", timeout: 5000 },
236 );
237 });
238​
239 it("strips CRLF delimiters from captured PowerShell values", () => {
240 const execFile = vi.fn<
241 (
242 file: string,
243 args: ReadonlyArray<string>,
244 options: { encoding: "utf8"; timeout: number },
245 ) => string
246 >(
247 () =>
248 "__V12_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__V12_ENV_FNM_DIR_END__\r\n",
249 );
250​
251 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
252 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
253 });
254 });
255​
256 it("omits -NoProfile when loadProfile is enabled", () => {
257 const execFile = vi.fn<
258 (
259 file: string,
260 args: ReadonlyArray<string>,
261 options: { encoding: "utf8"; timeout: number },
262 ) => string
263 >(() => "__V12_ENV_PATH_START__\nC:\\Tools\n__V12_ENV_PATH_END__\n");
264​
265 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
266 PATH: "C:\\Tools",
267 });
268 expect(execFile).toHaveBeenCalledWith(
269 "pwsh.exe",
270 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
271 { encoding: "utf8", timeout: 5000 },
272 );
273 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
274 });
275​
276 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
277 const execFile = vi.fn<
278 (
279 file: string,
280 args: ReadonlyArray<string>,
281 options: { encoding: "utf8"; timeout: number },
282 ) => string
283 >((file) => {
284 if (file === "pwsh.exe") {
285 throw new Error("spawn pwsh.exe ENOENT");
286 }
287 return "__V12_ENV_PATH_START__\nC:\\Tools\n__V12_ENV_PATH_END__\n";
288 });
289​
290 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
291 PATH: "C:\\Tools",
292 });
293 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
294 encoding: "utf8",
295 timeout: 5000,
296 });
297 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
298 encoding: "utf8",
299 timeout: 5000,
300 });
301 });
302});
303​
304describe("mergePathValues", () => {
305 it("dedupes case-insensitively on Windows while preserving preferred order", () => {
306 expect(
307 mergePathValues(
308 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
309 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
310 "win32",
311 ),
312 ).toBe(
313 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs";C:\\Windows\\System32',
314 );
315 });
316​
317 it("dedupes case-sensitively on POSIX", () => {
318 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
319 "/usr/local/bin:/usr/bin:/USR/BIN",
320 );
321 });
322});
323​
324describe("resolveKnownWindowsCliDirs", () => {
325 it("returns known Windows CLI install directories in priority order", () => {
326 expect(
327 resolveKnownWindowsCliDirs({
328 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
329 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
330 USERPROFILE: "C:\\Users\\testuser",
331 }),
332 ).toEqual([
333 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
334 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
335 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
336 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
337 "C:\\Users\\testuser\\.bun\\bin",
338 "C:\\Users\\testuser\\scoop\\shims",
339 ]);
340 });
341});
342​
343effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
344 it.effect("returns false when PATH is empty", () =>
345 Effect.gen(function* () {
346 expect(
347 yield* isCommandAvailable("definitely-not-installed", {
348 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
349 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
350 ).toBe(false);
351 }),
352 );
353});
354​
355effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
356 it.effect("fails when PATH is empty", () =>
357 Effect.gen(function* () {
358 const result = yield* resolveCommandPath("definitely-not-installed", {
359 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
360 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
361​
362 expect(result._tag).toBe("Failure");
363 }),
364 );
365});
366​
367effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
368 it.effect("runs Windows executables directly without a shell", () =>
369 Effect.gen(function* () {
370 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
371 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
372 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
373​
374 expect(command).toEqual({
375 command: "node.exe",
376 args: ["script.js", "hello & goodbye"],
377 shell: false,
378 });
379 }),
380 );
381​
382 it.effect("escapes the executable and arguments for Windows command shims", () =>
383 Effect.gen(function* () {
384 const command = yield* resolveSpawnCommand(
385 "vp",
386 ["run", "value & calc", "%PATH%", 'quote"value'],
387 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
388 ).pipe(
389 Effect.provideService(HostProcessPlatform, "win32"),
390 Effect.provideService(
391 SpawnExecutableResolution,
392 () => "C:\\Program Files\\npm & tools\\vp.cmd",
393 ),
394 );
395​
396 expect(command.shell).toBe(true);
397 expect(command.command).not.toContain(" & ");
398 expect(command.command).toContain("^&");
399 expect(command.args).toEqual([
400 '^"run^"',
401 '^"value^ ^&^ calc^"',
402 '^"^%PATH^%^"',
403 '^"quote\\^"value^"',
404 ]);
405 }),
406 );
407​
408 it.effect("resolves against the effective environment when extending host env", () =>
409 Effect.gen(function* () {
410 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
411 yield* resolveSpawnCommand("codex", ["app-server"], {
412 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
413 extendEnv: true,
414 }).pipe(
415 Effect.provideService(HostProcessPlatform, "win32"),
416 Effect.provideService(HostProcessEnvironment, {
417 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
418 PATHEXT: ".COM;.EXE;.BAT;.CMD",
419 }),
420 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
421 resolvedEnvironment = env;
422 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
423 }),
424 );
425​
426 expect(resolvedEnvironment).toEqual({
427 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
428 PATHEXT: ".COM;.EXE;.BAT;.CMD",
429 CODEX_HOME: "C:\\Users\\tester\\.codex",
430 });
431 }),
432 );
433​
434 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
435 Effect.gen(function* () {
436 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
437 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
438 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
439​
440 expect(command).toEqual({
441 command: "missing & calc",
442 args: ["unsafe & value"],
443 shell: false,
444 });
445 }),
446 );
447});
448​
449effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
450 it.effect("returns the baseline no-profile PATH patch when node is already available", () =>
451 Effect.gen(function* () {
452 const readEnvironment = vi.fn(
453 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
454 options?.loadProfile
455 ? { PATH: "C:\\Profile\\Bin" }
456 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
457 );
458 const commandAvailable = vi.fn(() => Effect.succeed(true));
459​
460 expect(
461 yield* withWindowsEnvironmentMocks(
462 resolveWindowsEnvironment({
463 PATH: "C:\\Windows\\System32",
464 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
465 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
466 USERPROFILE: "C:\\Users\\testuser",
467 }),
468 readEnvironment,
469 commandAvailable,
470 ),
471 ).toEqual({
472 PATH: [
473 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
474 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
475 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
476 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
477 "C:\\Users\\testuser\\.bun\\bin",
478 "C:\\Users\\testuser\\scoop\\shims",
479 "C:\\Shell\\Bin",
480 "C:\\Windows\\System32",
481 ].join(";"),
482 });
483 expect(readEnvironment).toHaveBeenCalledTimes(1);
484 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
485 expect(commandAvailable).toHaveBeenCalledWith(
486 "node",
487 expect.objectContaining({ env: expect.any(Object) }),
488 );
489 }),
490 );
491​
492 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
493 Effect.gen(function* () {
494 const readEnvironment = vi.fn(
495 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
496 options?.loadProfile
497 ? {
498 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
499 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
500 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
501 }
502 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
503 );
504 const commandAvailable = vi.fn(() => Effect.succeed(false));
505​
506 expect(
507 yield* withWindowsEnvironmentMocks(
508 resolveWindowsEnvironment({
509 PATH: "C:\\Windows\\System32",
510 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
511 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
512 USERPROFILE: "C:\\Users\\testuser",
513 }),
514 readEnvironment,
515 commandAvailable,
516 ),
517 ).toEqual({
518 PATH: [
519 "C:\\Profile\\Node",
520 "C:\\Windows\\System32",
521 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
522 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
523 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
524 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
525 "C:\\Users\\testuser\\.bun\\bin",
526 "C:\\Users\\testuser\\scoop\\shims",
527 "C:\\Shell\\Bin",
528 ].join(";"),
529 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
530 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
531 });
532 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
533 expect(readEnvironment).toHaveBeenNthCalledWith(
534 2,
535 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
536 {
537 loadProfile: true,
538 },
539 );
540 expect(commandAvailable).toHaveBeenCalledTimes(1);
541 }),
542 );
543​
544 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
545 Effect.gen(function* () {
546 const readEnvironment = vi.fn(
547 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
548 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
549 );
550 const commandAvailable = vi.fn(() => Effect.succeed(false));
551​
552 expect(
553 yield* withWindowsEnvironmentMocks(
554 resolveWindowsEnvironment({
555 PATH: "C:\\Windows\\System32",
556 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
557 USERPROFILE: "C:\\Users\\testuser",
558 }),
559 readEnvironment,
560 commandAvailable,
561 ),
562 ).toEqual({
563 PATH: [
564 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
565 "C:\\Users\\testuser\\.bun\\bin",
566 "C:\\Users\\testuser\\scoop\\shims",
567 "C:\\Windows\\System32",
568 ].join(";"),
569 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
570 });
571 expect(commandAvailable).toHaveBeenCalledTimes(1);
572 }),
573 );
574});