Fix Windows PATH hydration and repair (#1729)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Evan YuandJulius Marminge authored and GitHub committed 2026-04-17 06:12:17 +00:00
1 parent d8d329691a
commit a7a44d0662
11 files changed
+1049 -165

No files matched your search

+120 -2
View File
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing outside macOS and linux", () => {
it("does nothing on unsupported platforms", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -160,7 +160,7 @@ describe("syncShellEnvironment", () => {
}));
syncShellEnvironment(env, {
platform: "win32",
platform: "freebsd",
readEnvironment,
});
@@ -168,4 +168,122 @@ describe("syncShellEnvironment", () => {
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(() => ({
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
}));
const isWindowsCommandAvailable = vi.fn(() => true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
});
it("loads the PowerShell profile on Windows when node is not available", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
);
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
expect(env.FNM_MULTISHELL_PATH).toBe(
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
2,
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
{ loadProfile: true },
);
});
it("preserves baseline Windows env when the profile probe fails", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
if (options?.loadProfile) {
throw new Error("profile load failed");
}
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
},
);
const isWindowsCommandAvailable = vi.fn(() => false);
syncShellEnvironment(env, {
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
expect(env.SSH_AUTH_SOCK).toBeUndefined();
});
});
+32 -2
View File
@@ -3,8 +3,18 @@ import {
mergePathEntries,
readPathFromLaunchctl,
readEnvironmentFromLoginShell,
resolveWindowsEnvironment,
} from "@t3tools/shared/shell";
import type { ShellEnvironmentReader } from "@t3tools/shared/shell";
import type {
CommandAvailabilityOptions,
ShellEnvironmentReader,
WindowsShellEnvironmentReader,
} from "@t3tools/shared/shell";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
@@ -25,19 +35,39 @@ export function syncShellEnvironment(
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
readWindowsEnvironment?: WindowsShellEnvironmentReader;
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
readLaunchctlPath?: typeof readPathFromLaunchctl;
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
const shellEnvironment: Partial<Record<string, string>> = {};
try {
if (platform === "win32") {
const repairedEnvironment = resolveWindowsEnvironment(env, {
...(options.readWindowsEnvironment
? { readEnvironment: options.readWindowsEnvironment }
: {}),
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
: {}),
});
for (const [key, value] of Object.entries(repairedEnvironment)) {
if (value !== undefined) {
env[key] = value;
}
}
return;
}
if (platform !== "darwin" && platform !== "linux") return;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
+2 -112
View File
@@ -7,10 +7,9 @@
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import { Context, Effect, Layer } from "effect";
// ==============================
@@ -18,6 +17,7 @@ import { Context, Effect, Layer } from "effect";
// ==============================
export { OpenError };
export { isCommandAvailable } from "@t3tools/shared/shell";
export interface OpenInEditorInput {
readonly cwd: string;
@@ -29,11 +29,6 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function parseTargetPathAndPosition(target: string): {
@@ -106,111 +101,6 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
+115 -2
View File
@@ -53,7 +53,120 @@ describe("fixPath", () => {
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
});
it("does nothing outside macOS and linux even when SHELL is set", () => {
it("repairs PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(() => ({
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
}));
const isWindowsCommandAvailable = vi.fn(() => true);
fixPath({
env,
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
});
it("applies profile-derived fnm variables on Windows when node is missing", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
);
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
fixPath({
env,
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
].join(";"),
);
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
expect(env.FNM_MULTISHELL_PATH).toBe(
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
);
});
it("preserves baseline PATH on Windows when the profile probe fails", () => {
const env: NodeJS.ProcessEnv = {
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
};
const readWindowsEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
if (options?.loadProfile) {
throw new Error("profile load failed");
}
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
},
);
const isWindowsCommandAvailable = vi.fn(() => false);
fixPath({
env,
platform: "win32",
readWindowsEnvironment,
isWindowsCommandAvailable,
});
expect(env.PATH).toBe(
[
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
"C:\\Windows\\System32",
].join(";"),
);
});
it("does nothing on unsupported platforms", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
@@ -62,7 +175,7 @@ describe("fixPath", () => {
fixPath({
env,
platform: "win32",
platform: "freebsd",
readPath,
});
+29 -3
View File
@@ -1,12 +1,21 @@
import * as OS from "node:os";
import { Effect, Path } from "effect";
import {
readPathFromLoginShell,
readEnvironmentFromWindowsShell,
resolveWindowsEnvironment,
type CommandAvailabilityOptions,
type WindowsShellEnvironmentReader,
listLoginShellCandidates,
mergePathEntries,
readPathFromLaunchctl,
readPathFromLoginShell,
} from "@t3tools/shared/shell";
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => boolean;
function logPathHydrationWarning(message: string, error?: unknown): void {
console.warn(`[server] ${message}`, error instanceof Error ? error.message : (error ?? ""));
}
@@ -16,19 +25,36 @@ export function fixPath(
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
readPath?: typeof readPathFromLoginShell;
readWindowsEnvironment?: WindowsShellEnvironmentReader;
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
readLaunchctlPath?: typeof readPathFromLaunchctl;
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
const env = options.env ?? process.env;
const logWarning = options.logWarning ?? logPathHydrationWarning;
const readPath = options.readPath ?? readPathFromLoginShell;
try {
if (platform === "win32") {
const repairedEnvironment = resolveWindowsEnvironment(env, {
readEnvironment: options.readWindowsEnvironment ?? readEnvironmentFromWindowsShell,
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
: {}),
});
for (const [key, value] of Object.entries(repairedEnvironment)) {
if (value !== undefined) {
env[key] = value;
}
}
return;
}
if (platform !== "darwin" && platform !== "linux") return;
let shellPath: string | undefined;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
try {
@@ -194,6 +194,8 @@ function multiTerminalHistoryLogPath(
interface CreateManagerOptions {
shellResolver?: () => string;
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
@@ -228,6 +230,8 @@ const createManager = (
historyLineLimit,
ptyAdapter,
...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
...(options.platform !== undefined ? { platform: options.platform } : {}),
...(options.env !== undefined ? { env: options.env } : {}),
...(options.subprocessChecker !== undefined
? { subprocessChecker: options.subprocessChecker }
: {}),
@@ -297,6 +301,8 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("preserves non-notFound cwd stat failures", () =>
Effect.gen(function* () {
if (process.platform === "win32") return;
const { manager, baseDir } = yield* createManager();
const blockedRoot = path.join(baseDir, "blocked-root");
const blockedCwd = path.join(blockedRoot, "cwd");
@@ -827,8 +833,12 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("retries with fallback shells when preferred shell spawn fails", () =>
Effect.gen(function* () {
const missingShell =
process.platform === "win32"
? "C:\\definitely\\missing-shell.exe"
: "/definitely/missing-shell -l";
const { manager, ptyAdapter } = yield* createManager(5, {
shellResolver: () => "/definitely/missing-shell -l",
shellResolver: () => missingShell,
});
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
@@ -836,12 +846,17 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
assert.equal(snapshot.status, "running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
expect(ptyAdapter.spawnInputs[0]?.shell).toBe(
process.platform === "win32" ? missingShell : "/definitely/missing-shell",
);
if (process.platform === "win32") {
expect(
ptyAdapter.spawnInputs.some(
(input) => input.shell === "cmd.exe" || input.shell === "powershell.exe",
(input) =>
input.shell === "pwsh.exe" ||
input.shell === "powershell.exe" ||
input.shell === "cmd.exe",
),
).toBe(true);
} else {
@@ -854,6 +869,56 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("prefers PowerShell over ComSpec for Windows terminals", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
platform: "win32",
env: {
ComSpec: "C:\\Windows\\System32\\cmd.exe",
PATH: "C:\\Windows\\System32",
SystemRoot: "C:\\Windows",
},
});
yield* manager.open(openInput());
expect(ptyAdapter.spawnInputs[0]).toEqual(
expect.objectContaining({
shell: "pwsh.exe",
args: ["-NoLogo"],
}),
);
}),
);
it.effect("falls back to built-in PowerShell by absolute path on Windows", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
platform: "win32",
env: {
ComSpec: "C:\\Windows\\System32\\cmd.exe",
PATH: "C:\\Windows\\System32",
SystemRoot: "C:\\Windows",
},
shellResolver: () => "C:\\missing\\custom-shell.exe",
});
ptyAdapter.spawnFailures.push(
new Error("spawn custom-shell.exe ENOENT"),
new Error("spawn pwsh.exe ENOENT"),
);
yield* manager.open(openInput());
expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([
"C:\\missing\\custom-shell.exe",
"pwsh.exe",
"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
]);
expect(ptyAdapter.spawnInputs[1]?.args).toEqual(["-NoLogo"]);
expect(ptyAdapter.spawnInputs[2]?.args).toEqual(["-NoLogo"]);
}),
);
it.effect("filters app runtime env variables from terminal sessions", () =>
Effect.gen(function* () {
const originalValues = new Map<string, string | undefined>();
+72 -25
View File
@@ -186,19 +186,25 @@ function enqueueProcessEvent(
return true;
}
function defaultShellResolver(): string {
if (process.platform === "win32") {
return process.env.ComSpec ?? "cmd.exe";
function defaultShellResolver(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): string {
if (platform === "win32") {
return "pwsh.exe";
}
return process.env.SHELL ?? "bash";
return env.SHELL ?? "bash";
}
function normalizeShellCommand(value: string | undefined): string | null {
function normalizeShellCommand(
value: string | undefined,
platform: NodeJS.Platform = process.platform,
): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (process.platform === "win32") {
if (platform === "win32") {
return trimmed;
}
@@ -207,15 +213,42 @@ function normalizeShellCommand(value: string | undefined): string | null {
return firstToken.replace(/^['"]|['"]$/g, "");
}
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
function shellCandidateFromCommand(
command: string | null,
platform: NodeJS.Platform = process.platform,
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = path.basename(command).toLowerCase();
if (process.platform !== "win32" && shellName === "zsh") {
const shellName =
platform === "win32"
? path.win32.basename(command).toLowerCase()
: path.basename(command).toLowerCase();
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
return { shell: command, args: ["-NoLogo"] };
}
if (platform !== "win32" && shellName === "zsh") {
return { shell: command, args: ["-o", "nopromptsp"] };
}
return { shell: command };
}
function windowsSystemRoot(env: NodeJS.ProcessEnv): string {
return env.SystemRoot?.trim() || env.windir?.trim() || "C:\\Windows";
}
function windowsPowerShellPath(env: NodeJS.ProcessEnv): string {
return path.win32.join(
windowsSystemRoot(env),
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
);
}
function windowsCmdPath(env: NodeJS.ProcessEnv): string {
return path.win32.join(windowsSystemRoot(env), "System32", "cmd.exe");
}
function formatShellCandidate(candidate: ShellCandidate): string {
if (!candidate.args || candidate.args.length === 0) return candidate.shell;
return `${candidate.shell} ${candidate.args.join(" ")}`;
@@ -234,27 +267,37 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
function resolveShellCandidates(
shellResolver: () => string,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ShellCandidate[] {
const requested = shellCandidateFromCommand(
normalizeShellCommand(shellResolver(), platform),
platform,
);
if (process.platform === "win32") {
if (platform === "win32") {
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(process.env.ComSpec ?? null),
shellCandidateFromCommand("powershell.exe"),
shellCandidateFromCommand("cmd.exe"),
shellCandidateFromCommand("pwsh.exe", platform),
shellCandidateFromCommand(windowsPowerShellPath(env), platform),
shellCandidateFromCommand("powershell.exe", platform),
shellCandidateFromCommand(env.ComSpec ?? null, platform),
shellCandidateFromCommand(windowsCmdPath(env), platform),
shellCandidateFromCommand("cmd.exe", platform),
]);
}
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
shellCandidateFromCommand("/bin/zsh"),
shellCandidateFromCommand("/bin/bash"),
shellCandidateFromCommand("/bin/sh"),
shellCandidateFromCommand("zsh"),
shellCandidateFromCommand("bash"),
shellCandidateFromCommand("sh"),
shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform),
shellCandidateFromCommand("/bin/zsh", platform),
shellCandidateFromCommand("/bin/bash", platform),
shellCandidateFromCommand("/bin/sh", platform),
shellCandidateFromCommand("zsh", platform),
shellCandidateFromCommand("bash", platform),
shellCandidateFromCommand("sh", platform),
]);
}
@@ -651,6 +694,8 @@ interface TerminalManagerOptions {
historyLineLimit?: number;
ptyAdapter: PtyAdapterShape;
shellResolver?: () => string;
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
subprocessChecker?: TerminalSubprocessChecker;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
@@ -674,7 +719,9 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const shellResolver = options.shellResolver ?? defaultShellResolver;
const platform = options.platform ?? process.platform;
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
@@ -1337,8 +1384,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
Effect.andThen(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv);
const terminalEnv = createTerminalSpawnEnv(baseEnv, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
+21 -7
View File
@@ -2,7 +2,12 @@ import { createRequire } from "node:module";
import { Effect, FileSystem, Layer, Path } from "effect";
import { PtyAdapter } from "../Services/PTY.ts";
import type { PtyAdapterShape, PtyExitEvent, PtyProcess } from "../Services/PTY.ts";
import {
PtySpawnError,
type PtyAdapterShape,
type PtyExitEvent,
type PtyProcess,
} from "../Services/PTY.ts";
let didEnsureSpawnHelperExecutable = false;
@@ -108,12 +113,21 @@ export const layer = Layer.effect(
return {
spawn: Effect.fn(function* (input) {
yield* ensureNodePtySpawnHelperExecutableCached;
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
cwd: input.cwd,
cols: input.cols,
rows: input.rows,
env: input.env,
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
const ptyProcess = yield* Effect.try({
try: () =>
nodePty.spawn(input.shell, input.args ?? [], {
cwd: input.cwd,
cols: input.cols,
rows: input.rows,
env: input.env,
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
}),
catch: (cause) =>
new PtySpawnError({
adapter: "node-pty",
message: cause instanceof Error ? cause.message : "Failed to spawn PTY process",
cause,
}),
});
return new NodePtyProcess(ptyProcess);
}),
+268
View File
@@ -2,11 +2,16 @@ import { describe, expect, it, vi } from "vitest";
import {
extractPathFromShellOutput,
isCommandAvailable,
listLoginShellCandidates,
mergePathEntries,
mergePathValues,
readEnvironmentFromLoginShell,
readEnvironmentFromWindowsShell,
readPathFromLaunchctl,
readPathFromLoginShell,
resolveKnownWindowsCliDirs,
resolveWindowsEnvironment,
} from "./shell.ts";
describe("extractPathFromShellOutput", () => {
@@ -188,3 +193,266 @@ describe("mergePathEntries", () => {
);
});
});
describe("readEnvironmentFromWindowsShell", () => {
it("extracts environment variables from a PowerShell command", () => {
const execFile = vi.fn<
(
file: string,
args: ReadonlyArray<string>,
options: { encoding: "utf8"; timeout: number },
) => string
>(
() =>
"__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
);
expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
});
expect(execFile).toHaveBeenCalledWith(
"pwsh.exe",
expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
{ encoding: "utf8", timeout: 5000 },
);
});
it("strips CRLF delimiters from captured PowerShell values", () => {
const execFile = vi.fn<
(
file: string,
args: ReadonlyArray<string>,
options: { encoding: "utf8"; timeout: number },
) => string
>(
() =>
"__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
);
expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
});
});
it("omits -NoProfile when loadProfile is enabled", () => {
const execFile = vi.fn<
(
file: string,
args: ReadonlyArray<string>,
options: { encoding: "utf8"; timeout: number },
) => string
>(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
PATH: "C:\\Tools",
});
expect(execFile).toHaveBeenCalledWith(
"pwsh.exe",
expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
{ encoding: "utf8", timeout: 5000 },
);
expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
});
it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
const execFile = vi.fn<
(
file: string,
args: ReadonlyArray<string>,
options: { encoding: "utf8"; timeout: number },
) => string
>((file) => {
if (file === "pwsh.exe") {
throw new Error("spawn pwsh.exe ENOENT");
}
return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
});
expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
PATH: "C:\\Tools",
});
expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
encoding: "utf8",
timeout: 5000,
});
expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
encoding: "utf8",
timeout: 5000,
});
});
});
describe("mergePathValues", () => {
it("dedupes case-insensitively on Windows while preserving preferred order", () => {
expect(
mergePathValues(
'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
"c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
"win32",
),
).toBe(
'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs";C:\\Windows\\System32',
);
});
it("dedupes case-sensitively on POSIX", () => {
expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
"/usr/local/bin:/usr/bin:/USR/BIN",
);
});
});
describe("resolveKnownWindowsCliDirs", () => {
it("returns known Windows CLI install directories in priority order", () => {
expect(
resolveKnownWindowsCliDirs({
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
}),
).toEqual([
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
]);
});
});
describe("isCommandAvailable", () => {
it("returns false when PATH is empty", () => {
expect(
isCommandAvailable("definitely-not-installed", {
platform: "win32",
env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
}),
).toBe(false);
});
});
describe("resolveWindowsEnvironment", () => {
it("returns the baseline no-profile PATH patch when node is already available", () => {
const readEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? { PATH: "C:\\Profile\\Bin" }
: { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
);
const commandAvailable = vi.fn(() => true);
expect(
resolveWindowsEnvironment(
{
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
},
{
readEnvironment,
commandAvailable,
},
),
).toEqual({
PATH: [
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Shell\\Bin",
"C:\\Windows\\System32",
].join(";"),
});
expect(readEnvironment).toHaveBeenCalledTimes(1);
expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
expect(commandAvailable).toHaveBeenCalledWith(
"node",
expect.objectContaining({
platform: "win32",
}),
);
});
it("loads the PowerShell profile when baseline env cannot resolve node", () => {
const readEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile
? {
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
}
: { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
);
const commandAvailable = vi.fn(() => false);
expect(
resolveWindowsEnvironment(
{
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
USERPROFILE: "C:\\Users\\testuser",
},
{
readEnvironment,
commandAvailable,
},
),
).toEqual({
PATH: [
"C:\\Profile\\Node",
"C:\\Windows\\System32",
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Shell\\Bin",
].join(";"),
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
});
expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
expect(readEnvironment).toHaveBeenNthCalledWith(2, ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
loadProfile: true,
});
expect(commandAvailable).toHaveBeenCalledTimes(1);
});
it("keeps the baseline env when profiled probe still does not resolve node", () => {
const readEnvironment = vi.fn(
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
);
const commandAvailable = vi.fn(() => false);
expect(
resolveWindowsEnvironment(
{
PATH: "C:\\Windows\\System32",
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
USERPROFILE: "C:\\Users\\testuser",
},
{
readEnvironment,
commandAvailable,
},
),
).toEqual({
PATH: [
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Windows\\System32",
].join(";"),
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
});
expect(commandAvailable).toHaveBeenCalledTimes(1);
});
});
+317 -7
View File
@@ -1,9 +1,14 @@
import * as OS from "node:os";
import { execFileSync } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
const WINDOWS_PATH_DELIMITER = ";";
const POSIX_PATH_DELIMITER = ":";
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
type ExecFileSyncLike = (
file: string,
@@ -11,6 +16,15 @@ type ExecFileSyncLike = (
options: { encoding: "utf8"; timeout: number },
) => string;
export interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
export interface WindowsEnvironmentProbeOptions {
readonly loadProfile?: boolean;
}
function trimNonEmpty(value: string | null | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : undefined;
@@ -127,6 +141,24 @@ function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
.join("; ");
}
function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
return [
"$ErrorActionPreference = 'Stop'",
...names.flatMap((name) => {
if (!SHELL_ENV_NAME_PATTERN.test(name)) {
throw new Error(`Unsupported environment variable name: ${name}`);
}
return [
`Write-Output '${envCaptureStart(name)}'`,
`$value = [Environment]::GetEnvironmentVariable('${name}')`,
"if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
`Write-Output '${envCaptureEnd(name)}'`,
];
}),
].join("; ");
}
function extractEnvironmentValue(output: string, name: string): string | undefined {
const startMarker = envCaptureStart(name);
const endMarker = envCaptureEnd(name);
@@ -137,13 +169,10 @@ function extractEnvironmentValue(output: string, name: string): string | undefin
const endIndex = output.indexOf(endMarker, valueStartIndex);
if (endIndex === -1) return undefined;
let value = output.slice(valueStartIndex, endIndex);
if (value.startsWith("\n")) {
value = value.slice(1);
}
if (value.endsWith("\n")) {
value = value.slice(0, -1);
}
const value = output
.slice(valueStartIndex, endIndex)
.replace(/^\r?\n/, "")
.replace(/\r?\n$/, "");
return value.length > 0 ? value : undefined;
}
@@ -178,3 +207,284 @@ export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
return environment;
};
export type WindowsShellEnvironmentReader = (
names: ReadonlyArray<string>,
options?: WindowsEnvironmentProbeOptions,
) => Partial<Record<string, string>>;
export function readEnvironmentFromWindowsShell(
names: ReadonlyArray<string>,
execFile?: ExecFileSyncLike,
): Partial<Record<string, string>>;
export function readEnvironmentFromWindowsShell(
names: ReadonlyArray<string>,
options?: WindowsEnvironmentProbeOptions,
execFile?: ExecFileSyncLike,
): Partial<Record<string, string>>;
export function readEnvironmentFromWindowsShell(
names: ReadonlyArray<string>,
optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
maybeExecFile?: ExecFileSyncLike,
): Partial<Record<string, string>> {
if (names.length === 0) {
return {};
}
const options =
typeof optionsOrExecFile === "function"
? ({} satisfies WindowsEnvironmentProbeOptions)
: (optionsOrExecFile ?? {});
const execFile: ExecFileSyncLike =
typeof optionsOrExecFile === "function"
? optionsOrExecFile
: (maybeExecFile ?? (execFileSync as ExecFileSyncLike));
const command = buildWindowsEnvironmentCaptureCommand(names);
const args = [
"-NoLogo",
...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
"-NonInteractive",
"-Command",
command,
];
for (const shell of WINDOWS_SHELL_CANDIDATES) {
try {
const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
const environment: Partial<Record<string, string>> = {};
for (const name of names) {
const value = extractEnvironmentValue(output, name);
if (value !== undefined) {
environment[name] = value;
}
}
return environment;
} catch {
continue;
}
}
return {};
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
}
function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
const normalized = stripWrappingQuotes(entry.trim());
return platform === "win32" ? normalized.toLowerCase() : normalized;
}
export function mergePathValues(
preferredPath: string | undefined,
inheritedPath: string | undefined,
platform: NodeJS.Platform,
): string | undefined {
const delimiter = pathDelimiterForPlatform(platform);
const merged: string[] = [];
const seen = new Set<string>();
for (const rawValue of [preferredPath, inheritedPath]) {
if (!rawValue) continue;
for (const entry of rawValue.split(delimiter)) {
const trimmed = entry.trim();
if (trimmed.length === 0) continue;
const normalized = normalizePathEntryForComparison(trimmed, platform);
if (normalized.length === 0 || seen.has(normalized)) continue;
seen.add(normalized);
merged.push(trimmed);
}
}
return merged.length > 0 ? merged.join(delimiter) : undefined;
}
function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
return env.PATH ?? env.Path ?? env.path;
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return readEnvPath(env) ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const candidateExtension of windowsPathExtensions) {
candidates.push(`${command}${candidateExtension}`);
candidates.push(`${command}${candidateExtension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(pathDelimiterForPlatform(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const appData = env.APPDATA?.trim();
const localAppData = env.LOCALAPPDATA?.trim();
const userProfile = env.USERPROFILE?.trim();
return [
...(appData ? [`${appData}\\npm`] : []),
...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
...(localAppData ? [`${localAppData}\\pnpm`] : []),
...(userProfile ? [`${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`] : []),
];
}
export interface WindowsEnvironmentResolverOptions {
readonly readEnvironment?: WindowsShellEnvironmentReader;
readonly commandAvailable?: typeof isCommandAvailable;
}
function readWindowsEnvironmentSafely(
readEnvironment: WindowsShellEnvironmentReader,
names: ReadonlyArray<string>,
options?: WindowsEnvironmentProbeOptions,
): Partial<Record<string, string>> {
try {
return readEnvironment(names, options);
} catch {
return {};
}
}
function mergeWindowsEnv(
currentEnv: NodeJS.ProcessEnv,
patch: Partial<Record<string, string>>,
): NodeJS.ProcessEnv {
const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
for (const [key, value] of Object.entries(patch)) {
if (value !== undefined) {
nextEnv[key] = value;
}
}
return nextEnv;
}
export function resolveWindowsEnvironment(
env: NodeJS.ProcessEnv,
options: WindowsEnvironmentResolverOptions = {},
): Partial<NodeJS.ProcessEnv> {
const readEnvironment = options.readEnvironment ?? readEnvironmentFromWindowsShell;
const commandAvailable = options.commandAvailable ?? isCommandAvailable;
const inheritedPath = readEnvPath(env);
const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
loadProfile: false,
}).PATH;
const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
const baselineEnv = mergeWindowsEnv(env, baselinePatch);
if (commandAvailable("node", { platform: "win32", env: baselineEnv })) {
return baselinePatch;
}
const profiledEnvironment = readWindowsEnvironmentSafely(
readEnvironment,
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
{ loadProfile: true },
);
const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
const profiledPatch: Partial<NodeJS.ProcessEnv> = {
...(profiledPath ? { PATH: profiledPath } : {}),
...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
...(profiledEnvironment.FNM_MULTISHELL_PATH
? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
: {}),
};
return Object.keys(profiledPatch).length > 0
? { ...baselinePatch, ...profiledPatch }
: baselinePatch;
}
+5 -2
View File
@@ -610,12 +610,15 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* (
}
if (platform === "win") {
buildConfig.npmRebuild = false;
const winConfig: Record<string, unknown> = {
target: [target],
icon: "icon.ico",
};
if (signed) {
winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
} else {
winConfig.signAndEditExecutable = false;
}
buildConfig.win = winConfig;
}
@@ -811,7 +814,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`bun install --production`,
})`bun install --production --omit optional`,
);
const buildEnv: NodeJS.ProcessEnv = {
@@ -851,7 +854,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
...commandOutputOptions(options.verbose),
// Windows needs shell mode to resolve .cmd shims.
shell: process.platform === "win32",
})`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
})`bun x --install=fallback electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
);
const stageDistDir = path.join(stageAppDir, "dist");