Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: fork cross-spawn to fix esbuild chaos #25

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
MIT License

Copyright (c) 2024 Tinylibs
Copyright (c) 2018 Made With MOXY Lda <[email protected]>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whats that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the license of cross-spawn. any usage of the original code needs to maintain the copyright


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
74 changes: 60 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,16 @@
"@eslint/js": "^9.0.0",
"@types/cross-spawn": "^6.0.6",
"@types/node": "^20.12.7",
"@types/shebang-command": "^1.2.2",
"@types/which": "^3.0.4",
"c8": "^9.1.0",
"cross-spawn": "^7.0.3",
"eslint-config-google": "^0.14.0",
"prettier": "^3.2.5",
"tsup": "^8.1.0",
"typescript": "^5.4.5",
"typescript-eslint": "^7.7.0"
"typescript-eslint": "^7.7.0",
"shebang-command": "^2.0.0",
"which": "^4.0.0"
},
"exports": {
".": {
Expand Down
105 changes: 105 additions & 0 deletions src/cross-spawn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import * as path from 'node:path';
import {env} from 'node:process';
import {type SpawnOptions} from 'node:child_process';
import {openSync, readSync, closeSync} from 'node:fs';
import {resolveCommand} from './resolve-command.js';
import {escapeArgument, escapeCommand} from './escape-command.js';
import {type ParsedShellOptions} from './shared-types.js';
import shebangCommand from 'shebang-command';

const isWin = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;

function readShebang(command: string): string | null {
// Read the first 150 bytes from the file
const size = 150;
const buffer = Buffer.alloc(size);

let fd;

try {
fd = openSync(command, 'r');
readSync(fd, buffer, 0, size, 0);
closeSync(fd);
} catch (e) {
/* Empty */
}

// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
}

module.exports = readShebang;

function detectShebang(parsed: ParsedShellOptions): string | undefined {
const file = resolveCommand(parsed);

const shebang = file && readShebang(file);

if (shebang) {
parsed.args.unshift(file);
parsed.command = shebang;

return resolveCommand(parsed);
}

return file;
}

function parseNonShell(parsed: ParsedShellOptions): ParsedShellOptions {
if (!isWin) {
return parsed;
}

// Detect & add support for shebangs
const commandFile = detectShebang(parsed) ?? parsed.command;

// We don't need a shell if the command filename is an executable
const needsShell = !isExecutableRegExp.test(commandFile);

// If a shell is required, use cmd.exe and take care of escaping everything correctly
if (needsShell) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);

// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
parsed.command = path.normalize(parsed.command);

// Escape command & arguments
parsed.command = escapeCommand(parsed.command);
parsed.args = parsed.args.map((arg) =>
escapeArgument(arg, needsDoubleEscapeMetaChars)
);

const shellCommand = [parsed.command].concat(parsed.args).join(' ');

parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.command = env.comspec || 'cmd.exe';
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
}

return parsed;
}

export function parse(command: string, args: string[], options: SpawnOptions) {
if (options.shell) {
return {command, args, options};
}

const argsCopy = args.slice(0);
const optionsCopy = {...options};

// Build our parsed object
const parsed: ParsedShellOptions = {
command,
args: argsCopy,
options: optionsCopy
};

return parseNonShell(parsed);
}
2 changes: 1 addition & 1 deletion src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface EnvPathInfo {
const isPathLikePattern = /^path$/i;
const defaultEnvPathInfo = {key: 'PATH', value: ''};

function getPathFromEnv(env: EnvLike): EnvPathInfo {
export function getPathFromEnv(env: EnvLike): EnvPathInfo {
for (const key in env) {
if (
!Object.prototype.hasOwnProperty.call(env, key) ||
Expand Down
38 changes: 38 additions & 0 deletions src/escape-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;

export function escapeCommand(arg: string) {
// Escape meta chars
return arg.replace(metaCharsRegExp, '^$1');
}

export function escapeArgument(arg: string, doubleEscapeMetaChars: boolean) {
// Convert to string
arg = `${arg}`;

// Algorithm below is based on https://qntm.org/cmd

// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(\\*)"/g, '$1$1\\"');

// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(\\*)$/, '$1$1');

// All other backslashes occur literally

// Quote the whole thing:
arg = `"${arg}"`;

// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');

// Double escape meta chars if necessary
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}

return arg;
}
63 changes: 63 additions & 0 deletions src/resolve-command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import * as path from 'node:path';
import {chdir} from 'node:process';
import which from 'which';
import {getPathFromEnv} from './env.js';
import {type ParsedShellOptions} from './shared-types.js';

function resolveCommandAttempt(
parsed: ParsedShellOptions,
withoutPathExt: boolean
): string | undefined {
const env = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd =
hasCustomCwd &&
chdir !== undefined &&
!(chdir as typeof chdir & {disabled?: boolean}).disabled;

// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (shouldSwitchCwd && typeof parsed.options.cwd === 'string') {
try {
chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}

let resolved;

try {
resolved = which.sync(parsed.command, {
path: getPathFromEnv(env).value,
pathExt: withoutPathExt ? path.delimiter : undefined
});
} catch (e) {
/* Empty */
} finally {
if (shouldSwitchCwd) {
chdir(cwd);
}
}

// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(
hasCustomCwd && typeof parsed.options.cwd === 'string'
? parsed.options.cwd
: '',
resolved
);
}

return resolved;
}

export function resolveCommand(parsed: ParsedShellOptions): string | undefined {
return (
resolveCommandAttempt(parsed, false) || resolveCommandAttempt(parsed, true)
);
}
7 changes: 7 additions & 0 deletions src/shared-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {type SpawnOptions} from 'node:child_process';

export interface ParsedShellOptions {
command: string;
args: string[];
options: SpawnOptions;
}
Loading