Fix template strings, `parseCommandString()` and `execaNode()` edge cases
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent d9a5689 · Browse files · 6 files·+187 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+187 added−27 removed
- tests:+136 added−0 removed
- other:+51 added−27 removed
Provenance
- Commit
fb92da1- Tree
e6c8d99- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
d9a5689
6 files changed+187 added−27 removed
modified:lib/methods/command.js+9 added-18 removed
2 unmodified lines34567891078910121314151617181920212211122413141516171826272 unmodified lines if (typeof command !== 'string') { throw new TypeError(`The command must be a string: ${String(command)}.`); }
const trimmedCommand = command.trim(); if (trimmedCommand === '') { return []; } // Allow spaces to be escaped by a backslash if not meant as a delimiter return trimCommand(command).match(TOKEN_REGEXP)?.map(token => token.replaceAll('\\ ', ' ')) ?? [];};
const tokens = []; for (const token of trimmedCommand.split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens.at(-1); if (previousToken && previousToken.endsWith('\\')) { // Merge previous token with current one tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; } else { tokens.push(token); } }const TOKEN_REGEXP = /(?:\\ |[^ ])+/g;
return tokens;// Like `string.trim()`, but keeps a trailing escaped spaceconst trimCommand = command => { const trimmedCommand = command.trim(); const trimmedEnd = command.trimEnd(); return trimmedEnd.endsWith('\\') && command[trimmedEnd.length] === ' ' ? `${trimmedCommand} ` : trimmedCommand;};
const SPACES_REGEXP = / +/g;modified:lib/methods/node.js+24 added-1 removed
9 unmodified lines10111213141516171819202122232425262728293031323334353637383940414220434445464739 unmodified lines9 unmodified lines
return {options: {__proto__: null, ...options, node: true}};};
// The subprocess must not reuse the current process' `--inspect` port.// It must not run the current process' `node --eval` or `node --print` code either, instead of its file. Like `child_process.fork()`, this prevents fork bombs.const getDefaultNodeOptions = () => { const nodeOptions = []; for (let index = 0; index < execArgv.length; index += 1) { const nodeOption = execArgv[index]; if (REMOVED_OPTIONS_WITH_VALUE.has(nodeOption)) { // `-p` and `--print` do not take a value when followed by another flag, e.g. `node -p -e code`. With the other options, Node.js fails when their value starts with `-`. if (!execArgv[index + 1]?.startsWith('-')) { index += 1; } } else if (!IGNORED_OPTIONS_REGEXP.test(nodeOption)) { nodeOptions.push(nodeOption); } }
return nodeOptions;};
// Those options are followed by a separate value, which is removed tooconst REMOVED_OPTIONS_WITH_VALUE = new Set(['-e', '--eval', '-p', '--print', '-pe', '--input-type', '--inspect-port']);const IGNORED_OPTIONS_REGEXP = /^--(?:inspect|eval=|input-type=)/;
// Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.// Modifies the file commands/arguments to ensure the same Node binary and flags are re-used.// Also adds `ipc: true` and `shell: false`.export const handleNodeOption = (file, commandArguments, { node: shouldHandleNode = false, nodePath = execPath, nodeOptions = execArgv.filter(nodeOption => !nodeOption.startsWith('--inspect')), nodeOptions = getDefaultNodeOptions(), cwd, execPath: formerNodePath, ...options}) => {39 unmodified linesmodified:lib/methods/template.js+18 added-8 removed
1 import {ChildProcess} from 'node:child_process';2 import isPlainObject from 'is-plain-obj';3 import {ASTRAL_START} from '../arguments/escape.js';4 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';5+import {isExecaError} from '../return/final-error.js';6 7 // Check whether the template string syntax is being used8 export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);9 10 // Convert execa`file ...commandArguments` to execa(file, commandArguments)11 export const parseTemplates = (templates, expressions) => {12 let tokens = [];13+ // Whether whitespaces separate the last token from the next one14+ let isSeparated = false;15 16 for (const [index, template] of templates.entries()) {14- tokens = parseTemplate({17+ ({tokens, isSeparated} = parseTemplate({18 templates,19 expressions,20 tokens,21+ isSeparated,22 index,23 template,20- });24+ }));25 }26 27 if (tokens.length === 0) {28 throw new TypeError('Template script must not be empty');2 unmodified lines31 const [file, ...commandArguments] = tokens;32 return [file, commandArguments, {}];33 };34 31-const parseTemplate = ({templates, expressions, tokens, index, template}) => {35+const parseTemplate = ({templates, expressions, tokens, isSeparated, index, template}) => {36 if (template === undefined) {37 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);38 }39 40 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);37- const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);41+ const newTokens = concatTokens(tokens, nextTokens, isSeparated || leadingWhitespaces);42+ // When the template has no tokens, the whitespaces before it still separate the next token, e.g. after an empty array expression43+ const isTemplateSeparated = trailingWhitespaces || (nextTokens.length === 0 && isSeparated);44 45 if (index === expressions.length) {40- return newTokens;46+ return {tokens: newTokens, isSeparated: isTemplateSeparated};47 }48 49 const expression = expressions[index];50 const expressionTokens = Array.isArray(expression)51 ? expression.map(expression => parseExpression(expression))52 : [parseExpression(expression)];47- return concatTokens(newTokens, expressionTokens, trailingWhitespaces);53+ return {54+ tokens: concatTokens(newTokens, expressionTokens, isTemplateSeparated),55+ isSeparated: expressionTokens.length === 0 && isTemplateSeparated,56+ };57 };58 59 // Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:60 // - ignored when input as a backslash sequence like: `echo foo\n bar`87 unmodified lines148 if (typeOfExpression === 'number') {149 return String(expression);150 }151 143- // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result144- if (isPlainObject(expression) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {152+ // Only own properties are checked: a polluted `Object.prototype.stdout` must not turn any plain object into a subprocess result.153+ // A failed subprocess result is an error instance instead.154+ if ((isPlainObject(expression) || isExecaError(expression)) && (Object.hasOwn(expression, 'stdout') || Object.hasOwn(expression, 'isMaxBuffer'))) {155 return getSubprocessResult(expression);156 }157 158 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {24 unmodified linesmodified:test/methods/command.js+53 added
98 unmodified lines99 test('parseCommandString() allows escaping backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand));100 test('parseCommandString() allows escaping multiple backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand));101 test('parseCommandString() allows escaping backslashes not before spaces', () => testParseCommandOutput('echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand));102 103+// An escaped space must not be merged with the space delimiter after it104+test('parseCommandString() allows escaping spaces before a space delimiter', () => {105+ assert.deepEqual(parseCommandString('echo foo\\ bar'), ['echo', 'foo ', 'bar']);106+});107+108+test('parseCommandString() allows escaping spaces before consecutive space delimiters', () => {109+ assert.deepEqual(parseCommandString('echo foo\\ bar'), ['echo', 'foo ', 'bar']);110+});111+112+test('parseCommandString() allows escaping consecutive spaces', () => {113+ assert.deepEqual(parseCommandString('echo foo\\ \\ bar'), ['echo', 'foo bar']);114+});115+116+test('parseCommandString() allows escaped spaces as the only characters of an argument', () => {117+ assert.deepEqual(parseCommandString('echo \\ bar'), ['echo', ' ', 'bar']);118+});119+120+test('parseCommandString() allows escaping a trailing space', () => {121+ assert.deepEqual(parseCommandString('echo foo\\ '), ['echo', 'foo ']);122+});123+124+test('parseCommandString() allows escaping a trailing space followed by other spaces', () => {125+ assert.deepEqual(parseCommandString('echo foo\\ '), ['echo', 'foo ']);126+});127+128+test('parseCommandString() allows escaping a trailing space followed by other whitespaces', () => {129+ assert.deepEqual(parseCommandString('echo foo\\ \n'), ['echo', 'foo ']);130+});131+132+test('parseCommandString() does not escape trailing whitespaces other than spaces', () => {133+ assert.deepEqual(parseCommandString('echo foo\\\n'), ['echo', 'foo\\']);134+});135+136+test('parseCommandString() trims whitespaces other than spaces', () => {137+ assert.deepEqual(parseCommandString('\t echo foo \n'), ['echo', 'foo']);138+});139+140+test('parseCommandString() allows escaping a leading space', () => {141+ assert.deepEqual(parseCommandString('echo \\ foo'), ['echo', ' foo']);142+});143+144+test('parseCommandString() allows escaping a space in the first token', () => {145+ assert.deepEqual(parseCommandString('foo\\ bar baz'), ['foo bar', 'baz']);146+});147+148+test('parseCommandString() allows only an escaped space', () => {149+ assert.deepEqual(parseCommandString('\\ '), [' ']);150+});151+152+test('parseCommandString() keeps tabs inside tokens with escaped spaces', () => {153+ assert.deepEqual(parseCommandString('echo foo\tbar\\ baz'), ['echo', 'foo\tbar baz']);154+});155+156 test('parseCommandString() can get empty strings', () => {157 assert.deepEqual(parseCommandString(''), []);158 });159 4 unmodified linesmodified:test/methods/node.js+50 added
222 unmodified lines223 test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk', 'nodeOption'));224 test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk=9223', 'execaNode'));225 test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk=9223', 'nodeOption'));226 227+// When the current process runs `node --eval` or `node --print`, `process.execArgv` contains that code, which must not be run by the subprocess instead of its file.228+// The environment variable prevents a fork bomb, if that code is run.229+const indexUrl = pathToFileURL(path.resolve(FIXTURES_DIRECTORY, '../../index.js')).href;230+const evalCode = `if (process.env.EXECA_TEST_EVAL) {231+ console.log('eval code was run by the subprocess');232+} else {233+ import(${JSON.stringify(indexUrl)}).then(async execaModule => {234+ const {stdout} = await execaModule.execaNode('noop.js', [${JSON.stringify(foobarString)}], {env: {EXECA_TEST_EVAL: '1'}});235+ console.log(stdout);236+ });237+}`;238+239+const testEvalRemoval = async nodeArguments => {240+ const {stdout} = await execa('node', nodeArguments, {cwd: FIXTURES_DIRECTORY});241+ // With `--print`, the value of the code is printed too242+ assert.ok(stdout.split('\n').includes(foobarString));243+ assert.ok(!stdout.includes('eval code was run'));244+};245+246+test('The "nodeOptions" option removes -e when defined by current process', () => testEvalRemoval(['-e', evalCode]));247+test('The "nodeOptions" option removes --eval when defined by current process', () => testEvalRemoval(['--eval', evalCode]));248+test('The "nodeOptions" option removes --eval= when defined by current process', () => testEvalRemoval([`--eval=${evalCode}`]));249+test('The "nodeOptions" option removes -p when defined by current process', () => testEvalRemoval(['-p', evalCode]));250+test('The "nodeOptions" option removes --print when defined by current process', () => testEvalRemoval(['--print', evalCode]));251+test('The "nodeOptions" option removes -pe when defined by current process', () => testEvalRemoval(['-pe', evalCode]));252+test('The "nodeOptions" option removes -p -e when defined by current process', () => testEvalRemoval(['-p', '-e', evalCode]));253+test('The "nodeOptions" option removes --print --eval when defined by current process', () => testEvalRemoval(['--print', '--eval', evalCode]));254+test('The "nodeOptions" option removes -e -p when defined by current process', () => testEvalRemoval(['-e', evalCode, '-p']));255+test('The "nodeOptions" option removes --input-type= when defined by current process', () => testEvalRemoval(['--input-type=commonjs', '-e', evalCode]));256+test('The "nodeOptions" option removes --input-type when defined by current process', () => testEvalRemoval(['--input-type', 'commonjs', '-e', evalCode]));257+// `--inspect-port` does not start the inspector by itself, so this does not need a free port258+test('The "nodeOptions" option removes --inspect-port with a separate value when defined by current process', () => testEvalRemoval(['--inspect-port', '9339', '-e', evalCode]));259+test('The "nodeOptions" option removes --inspect-port= when defined by current process', () => testEvalRemoval(['--inspect-port=9339', '-e', evalCode]));260+261+const testKeptFlags = async (keptFlags, removedFlags = []) => {262+ const {stdout} = await execa('node', [...keptFlags, ...removedFlags, '-e', `import(${JSON.stringify(indexUrl)}).then(async execaModule => {263+ const {stdout} = await execaModule.execaNode('-p', ['process.execArgv.join(" ")']);264+ console.log(stdout);265+ });`], {cwd: FIXTURES_DIRECTORY});266+ assert.equal(stdout, [...keptFlags, '-p', 'process.execArgv.join(" ")'].join(' '));267+};268+269+test('The "nodeOptions" option keeps other flags when -e is defined by current process', () => testKeptFlags(['--no-warnings']));270+test('The "nodeOptions" option keeps the value of other flags when -e is defined by current process', () => testKeptFlags(['-r', './empty.js'], ['--input-type', 'commonjs']));271+272+test('The "nodeOptions" option is not filtered when passed explicitly', async () => {273+ const {stdout} = await execaNode('-p', ['process.execArgv.join(" ")'], {nodeOptions: ['--input-type=commonjs', '--inspect-port=9339']});274+ assert.equal(stdout, '--input-type=commonjs --inspect-port=9339 -p process.execArgv.join(" ")');275+});276+277 const testInspectDifferentPort = async execaMethod => {278 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');279 assert.equal(stdout, foobarString);280 assert.ok(stdio[3].includes('Debugger listening'));77 unmodified linesmodified:test/methods/template.js+33 added
3 unmodified lines4 import {assertThrows} from '../helpers/assert.js';5 import {$} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {majorNodeVersion} from '../helpers/node-version.js';8+import {foobarString} from '../helpers/input.js';9 10 setFixtureDirectory();11 12 const isWindows = process.platform === 'win32';55 unmodified lines68 test('$ allows escaping spaces in commands with interpolation', () => testScriptStdout(() => $`${'command with space.js'} foo bar`, 'foo\nbar'));69 test('$ trims', () => testScriptStdout(() => $` echo.js foo bar `, 'foo\nbar'));70 test('$ allows array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}`, 'foo\nbar'));71 test('$ allows empty array interpolation', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));72+// An empty array must not remove the whitespace before it73+test('$ allows empty array interpolation followed by a token', () => testScriptStdout(() => $`echo.js foo ${[]}bar`, 'foo\nbar'));74+test('$ allows empty array interpolation followed by an expression', () => testScriptStdout(() => $`echo.js foo ${[]}${'bar'}`, 'foo\nbar'));75+test('$ allows multiple empty array interpolations followed by a token', () => testScriptStdout(() => $`echo.js foo ${[]}${[]}bar`, 'foo\nbar'));76+test('$ allows empty array interpolation after an expression and before a token', () => testScriptStdout(() => $`echo.js ${'foo'} ${[]}bar`, 'foo\nbar'));77+test('$ allows empty array interpolation without whitespaces', () => testScriptStdout(() => $`echo.js foo${[]}bar`, 'foobar'));78+test('$ allows empty array interpolation without whitespaces after it', () => testScriptStdout(() => $`echo.js foo${[]} bar`, 'foo\nbar'));79+test('$ allows empty array interpolation between expressions without whitespaces', () => testScriptStdout(() => $`echo.js ${'foo'}${[]}${'bar'}`, 'foobar'));80+test('$ allows empty array interpolation at the start of an argument', () => testScriptStdout(() => $`echo.js ${[]}foo bar`, 'foo\nbar'));81+test('$ allows empty array interpolation at the end', () => testScriptStdout(() => $`echo.js foo ${[]}`, 'foo'));82+test('$ allows empty array interpolation as the only argument', () => testScriptStdout(() => $`echo.js ${[]}`, ''));83+test('$ allows empty array interpolation between tabs', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));84+test('$ allows empty array interpolation followed by an empty string', () => testScriptStdout(() => $`echo.js foo ${[]}${''} bar`, 'foo\n\nbar'));85+test('$ allows empty array interpolation after escaped newlines', () => testScriptStdout(() => $`echo.js foo \86+${[]}bar`, 'foo\nbar'));87 test('$ allows space escaped values in array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz'));88 test('$ can concatenate at the end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo'));89 test('$ can concatenate at the start of tokens followed by an array', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo'));90 test('$ can concatenate at the start and end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar'));242 unmodified lines333 test('$.sync allows execa return value buffer interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));334 test('$.sync allows execa return value array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar'));335 test('$.sync allows execa return value buffer array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));336 337+// A failed result is an error instance, not a plain object338+const testErrorInterpolate = async (getError, getSubprocess) => {339+ const error = await getError();340+ assert.equal(error.failed, true);341+ const {stdout} = await getSubprocess(error);342+ assert.equal(stdout, `${foobarString}\nbar`);343+};344+345+test('$ allows execa error interpolation, reject: false', () => testErrorInterpolate(() => $({reject: false})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${error} bar`));346+test('$ allows execa error interpolation, rejected', () => testErrorInterpolate(() => $`noop-fail.js 1 ${foobarString}`.catch(error => error), error => $`echo.js ${error} bar`));347+test('$ allows execa error array interpolation', () => testErrorInterpolate(() => $({reject: false})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${[error, 'bar']}`));348+test('$ allows execa error buffer interpolation', () => testErrorInterpolate(() => $({reject: false, encoding: 'buffer'})`noop-fail.js 1 ${foobarString}`, error => $`echo.js ${error} bar`));349+test('$.sync allows execa error interpolation, reject: false', () => testErrorInterpolate(() => $({reject: false}).sync`noop-fail.js 1 ${foobarString}`, error => $.sync`echo.js ${error} bar`));350+test('$.sync allows execa error interpolation, thrown', () => testErrorInterpolate(() => assertThrows(() => $.sync`noop-fail.js 1 ${foobarString}`), error => $.sync`echo.js ${error} bar`));351+352 const testInvalidSequence = getSubprocess => {353 assertThrows(getSubprocess, {message: /Invalid backslash sequence/});354 };355 40 unmodified lines396 test('$ throws on invalid expression - [true]', () => testInvalidExpression([true]));397 test('$ throws on invalid expression - [{}]', () => testInvalidExpression([{}]));398 test('$ throws on invalid expression - [{foo: "bar"}]', () => testInvalidExpression([{foo: 'bar'}]));399 test('$ throws on invalid expression - [{stdout: 1}]', () => testInvalidExpression([{stdout: 1}]));400+test('$ throws on invalid expression - new Error()', () => testInvalidExpression(new Error(foobarString)));401+test('$ throws on invalid expression - Object.assign(new Error(), {stdout})', () => testInvalidExpression(Object.assign(new Error(foobarString), {stdout: foobarString})));402 403 const testMissingOutput = invalidExpression => {404 assertThrows(405 () => $`echo.js ${invalidExpression()}`,22 unmodified lines