Skip to content
Myr

Split files (#837)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 1a47ea2 · Browse files · 100 files+4963 added−4795 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

100 files+4963 added−4795 removed

  • tests:+3564 added−3420 removed
  • other:+1399 added−1375 removed

100 files+4963 added−4795 removed

added:lib/arguments/cwd.js+49 added
added:lib/arguments/escape.js+12 added
added:lib/arguments/node.js+46 added
added:lib/arguments/options.js+91 added
1import {basename} from 'node:path';2import process from 'node:process';3import crossSpawn from 'cross-spawn';4import {npmRunPathEnv} from 'npm-run-path';5import {normalizeForceKillAfterDelay} from '../exit/kill.js';6import {validateTimeout} from '../exit/timeout.js';7import {handleNodeOption} from './node.js';8import {logCommand, verboseDefault} from './verbose.js';9import {joinCommand} from './escape.js';10import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './cwd.js';1112export const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)13 ? [args, options]14 : [[], args];1516export const handleArguments = (rawFile, rawArgs, rawOptions) => {17 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');18 const {command, escapedCommand} = joinCommand(filePath, rawArgs);1920 rawOptions.cwd = normalizeCwd(rawOptions.cwd);21 const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);2223 const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);2425 const options = addDefaultOptions(initialOptions);26 validateTimeout(options);27 options.shell = normalizeFileUrl(options.shell);28 options.env = getEnv(options);29 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);3031 if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {32 // #11633 args.unshift('/q');34 }3536 logCommand(escapedCommand, options);3738 return {file, args, command, escapedCommand, options};39};4041const addDefaultOptions = ({42 maxBuffer = DEFAULT_MAX_BUFFER,43 buffer = true,44 stripFinalNewline = true,45 extendEnv = true,46 preferLocal = false,47 cwd,48 localDir = cwd,49 encoding = 'utf8',50 reject = true,51 cleanup = true,52 all = false,53 windowsHide = true,54 verbose = verboseDefault,55 killSignal = 'SIGTERM',56 forceKillAfterDelay = true,57 lines = false,58 ipc = false,59 ...options60}) => ({61 ...options,62 maxBuffer,63 buffer,64 stripFinalNewline,65 extendEnv,66 preferLocal,67 cwd,68 localDir,69 encoding,70 reject,71 cleanup,72 all,73 windowsHide,74 verbose,75 killSignal,76 forceKillAfterDelay,77 lines,78 ipc,79});8081const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;8283const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {84 const env = extendEnv ? {...process.env, ...envOption} : envOption;8586 if (preferLocal) {87 return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});88 }8990 return env;91};
added:lib/arguments/verbose.js+22 added
added:lib/exit/cleanup.js+16 added
added:lib/exit/code.js+14 added
added:lib/exit/kill.js+76 added
added:lib/exit/timeout.js+20 added
modified:lib/pipe/streaming.js+1 added-1 removed
1import {finished} from 'node:stream/promises';2import mergeStreams from '@sindresorhus/merge-streams';3import {incrementMaxListeners} from '../stdio/utils.js';3import {incrementMaxListeners} from '../utils.js';45// The piping behavior is like Bash.6// In particular, when one process exits, the other is not terminated by a signal.7// Instead, its stdout (for the source) or stdin (for the destination) closes.
62 unmodified lines
modified:lib/pipe/validate.js+2 added-2 removed
1import {ChildProcess} from 'node:child_process';2import {STANDARD_STREAMS_ALIASES} from '../stdio/utils.js';3import {makeEarlyError} from '../error.js';2import {STANDARD_STREAMS_ALIASES} from '../utils.js';3import {makeEarlyError} from '../return/error.js';4import {abortSourceStream, endDestinationStream} from './streaming.js';56export const normalizePipeArguments = (destination, from, {spawned: source, stdioStreamsGroups, options}) => {7 const {destinationStream, destinationError} = getDestinationStream(destination);
138 unmodified lines
added:lib/return/clone.js+70 added
1export const getFinalError = (initialError, message) => {2 const error = createFinalError(initialError, message);3 previousErrors.add(error);4 return error;5};67const createFinalError = (error, message) => {8 if (!isErrorInstance(error)) {9 return new Error(message);10 }1112 return previousErrors.has(error)13 ? cloneError(error, message)14 : setErrorMessage(error, message);15};1617export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';1819const cloneError = (oldError, newMessage) => {20 const {name, message, stack} = oldError;21 const error = new Error(newMessage);22 error.stack = fixStack(stack, message, newMessage);23 Object.defineProperty(error, 'name', {value: name, enumerable: false, configurable: true, writable: true});24 copyErrorProperties(error, oldError);25 return error;26};2728const copyErrorProperties = (newError, previousError) => {29 for (const propertyName of COPIED_ERROR_PROPERTIES) {30 const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName);31 if (descriptor !== undefined) {32 Object.defineProperty(newError, propertyName, descriptor);33 }34 }35};3637// Known error properties38const COPIED_ERROR_PROPERTIES = [39 'cause',40 'errors',41 'code',42 'errno',43 'syscall',44 'path',45 'dest',46 'address',47 'port',48 'info',49];5051// Sets `error.message`.52// Fixes `error.stack` not being updated when it has been already accessed, since it is memoized by V8.53// For example, this happens when calling `stream.destroy(error)`.54// See https://github.com/nodejs/node/issues/5171555const setErrorMessage = (error, newMessage) => {56 const {message, stack} = error;57 error.message = newMessage;58 error.stack = fixStack(stack, message, newMessage);59 return error;60};6162const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63 ? stack64 : stack.replace(`: ${message}`, `: ${newMessage}`);6566// Two `execa()` calls might return the same error.67// So we must close those before directly mutating them.68export const isPreviousError = error => previousErrors.has(error);6970const previousErrors = new WeakSet();
added:lib/return/error.js+191 added
1import {signalsByName} from 'human-signals';2import stripFinalNewline from 'strip-final-newline';3import {isBinary, binaryToString} from '../utils.js';4import {fixCwdError} from '../arguments/cwd.js';5import {getFinalError, isPreviousError} from './clone.js';67export const makeSuccessResult = ({8 command,9 escapedCommand,10 stdio,11 all,12 options: {cwd},13}) => ({14 command,15 escapedCommand,16 cwd,17 failed: false,18 timedOut: false,19 isCanceled: false,20 isTerminated: false,21 exitCode: 0,22 stdout: stdio[1],23 stderr: stdio[2],24 all,25 stdio,26 pipedFrom: [],27});2829export const makeEarlyError = ({30 error,31 command,32 escapedCommand,33 stdioStreamsGroups,34 options,35}) => makeError({36 error,37 command,38 escapedCommand,39 timedOut: false,40 isCanceled: false,41 stdio: Array.from({length: stdioStreamsGroups.length}),42 options,43});4445export const makeError = ({46 error: rawError,47 command,48 escapedCommand,49 timedOut,50 isCanceled,51 exitCode: rawExitCode,52 signal: rawSignal,53 stdio,54 all,55 options: {timeoutDuration, timeout = timeoutDuration, cwd},56}) => {57 const initialError = rawError instanceof DiscardedError ? undefined : rawError;58 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);59 const {originalMessage, shortMessage, message} = createMessages({60 stdio,61 all,62 error: initialError,63 signal,64 signalDescription,65 exitCode,66 command,67 timedOut,68 isCanceled,69 timeout,70 cwd,71 });72 const error = getFinalError(initialError, message);7374 error.shortMessage = shortMessage;75 error.originalMessage = originalMessage;76 error.command = command;77 error.escapedCommand = escapedCommand;78 error.cwd = cwd;7980 error.failed = true;81 error.timedOut = timedOut;82 error.isCanceled = isCanceled;83 error.isTerminated = signal !== undefined;84 error.exitCode = exitCode;85 error.signal = signal;86 error.signalDescription = signalDescription;8788 error.stdout = stdio[1];89 error.stderr = stdio[2];9091 if (all !== undefined) {92 error.all = all;93 }9495 error.stdio = stdio;9697 if ('bufferedData' in error) {98 delete error.bufferedData;99 }100101 error.pipedFrom = [];102103 return error;104};105106// Indicates that the error is used only to interrupt control flow, but not in the return value107export class DiscardedError extends Error {}108109// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.110// We normalize them to `undefined`111const normalizeExitPayload = (rawExitCode, rawSignal) => {112 const exitCode = rawExitCode === null ? undefined : rawExitCode;113 const signal = rawSignal === null ? undefined : rawSignal;114 const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;115 return {exitCode, signal, signalDescription};116};117118const createMessages = ({119 stdio,120 all,121 error,122 signal,123 signalDescription,124 exitCode,125 command,126 timedOut,127 isCanceled,128 timeout,129 cwd,130}) => {131 const errorCode = error?.code;132 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});133 const originalMessage = getOriginalMessage(error, cwd);134 const newline = originalMessage === '' ? '' : '\n';135 const shortMessage = `${prefix}: ${command}${newline}${originalMessage}`;136 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];137 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]138 .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart)))139 .filter(Boolean)140 .join('\n\n');141 return {originalMessage, shortMessage, message};142};143144const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {145 if (timedOut) {146 return `Command timed out after ${timeout} milliseconds`;147 }148149 if (isCanceled) {150 return 'Command was canceled';151 }152153 if (errorCode !== undefined) {154 return `Command failed with ${errorCode}`;155 }156157 if (signal !== undefined) {158 return `Command was killed with ${signal} (${signalDescription})`;159 }160161 if (exitCode !== undefined) {162 return `Command failed with exit code ${exitCode}`;163 }164165 return 'Command failed';166};167168const getOriginalMessage = (error, cwd) => {169 if (error === undefined) {170 return '';171 }172173 const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);174 return fixCwdError(originalMessage, cwd);175};176177const serializeMessagePart = messagePart => Array.isArray(messagePart)178 ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')179 : serializeMessageItem(messagePart);180181const serializeMessageItem = messageItem => {182 if (typeof messageItem === 'string') {183 return messageItem;184 }185186 if (isBinary(messageItem)) {187 return binaryToString(messageItem);188 }189190 return '';191};
added:lib/return/output.js+19 added
1import {Buffer} from 'node:buffer';2import stripFinalNewline from 'strip-final-newline';3import {bufferToUint8Array} from '../utils.js';45export const handleOutput = (options, value) => {6 if (value === undefined || value === null) {7 return;8 }910 if (Array.isArray(value)) {11 return value;12 }1314 if (Buffer.isBuffer(value)) {15 value = bufferToUint8Array(value);16 }1718 return options.stripFinalNewline ? stripFinalNewline(value) : value;19};
modified:lib/stdio/async.js+1 added-1 removed
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable} from 'node:stream';4import {isStandardStream, incrementMaxListeners} from '../utils.js';5import {handleInput} from './handle.js';6import {pipeStreams} from './pipeline.js';7import {TYPE_TO_MESSAGE} from './type.js';8import {generatorToDuplexStream, pipeGenerator} from './generator.js';8import {isStandardStream, incrementMaxListeners} from './utils.js';910// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode11export const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);12
82 unmodified lines
added:lib/stdio/encoding-end.js+49 added
1import {Buffer} from 'node:buffer';2import {isUint8Array} from '../utils.js';34/*5When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.6This allows generator functions to operate with those types instead.7Chunks might be Buffer, Uint8Array or strings since:8- `childProcess.stdout|stderr` emits Buffers9- `childProcess.stdin.write()` accepts Buffer, Uint8Array or string10- Previous generators might return Uint8Array or string1112However, those are converted to Buffer:13- on writes: `Duplex.writable` `decodeStrings: true` default option14- on reads: `Duplex.readable` `readableEncoding: null` default option15*/16export const getEncodingStartGenerator = encoding => {17 if (encoding === 'buffer') {18 return {transform: encodingStartBufferGenerator.bind(undefined, new TextEncoder())};19 }2021 const textDecoder = new TextDecoder();22 return {23 transform: encodingStartStringGenerator.bind(undefined, textDecoder),24 final: encodingStartStringFinal.bind(undefined, textDecoder),25 };26};2728const encodingStartBufferGenerator = function * (textEncoder, chunk) {29 if (Buffer.isBuffer(chunk)) {30 yield new Uint8Array(chunk);31 } else if (typeof chunk === 'string') {32 yield textEncoder.encode(chunk);33 } else {34 yield chunk;35 }36};3738const encodingStartStringGenerator = function * (textDecoder, chunk) {39 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)40 ? textDecoder.decode(chunk, {stream: true})41 : chunk;42};4344const encodingStartStringFinal = function * (textDecoder) {45 const lastChunk = textDecoder.decode();46 if (lastChunk !== '') {47 yield lastChunk;48 }49};
added:lib/stdio/encoding-start.js+55 added
1import {StringDecoder} from 'node:string_decoder';2import {isUint8Array} from '../utils.js';3import {willPipeStreams} from './forward.js';45// Apply the `encoding` option using an implicit generator.6// This encodes the final output of `stdout`/`stderr`.7export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {8 const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));9 if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {10 return newStdioStreams;11 }1213 const objectMode = newStdioStreams.findLast(({type}) => type === 'generator')?.value.objectMode === true;14 const stringDecoder = new StringDecoder(encoding);15 const generator = objectMode16 ? {17 transform: encodingEndObjectGenerator.bind(undefined, stringDecoder),18 }19 : {20 transform: encodingEndStringGenerator.bind(undefined, stringDecoder),21 final: encodingEndStringFinal.bind(undefined, stringDecoder),22 };23 return [24 ...newStdioStreams,25 {26 ...newStdioStreams[0],27 type: 'generator',28 value: {...generator, binary: true, objectMode},29 encoding: 'buffer',30 },31 ];32};3334const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'35 && !IGNORED_ENCODINGS.has(encoding)36 && !isSync37 && willPipeStreams(stdioStreams);3839// eslint-disable-next-line unicorn/text-encoding-identifier-case40const IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);4142const encodingEndStringGenerator = function * (stringDecoder, chunk) {43 yield stringDecoder.write(chunk);44};4546const encodingEndStringFinal = function * (stringDecoder) {47 const lastChunk = stringDecoder.end();48 if (lastChunk !== '') {49 yield lastChunk;50 }51};5253const encodingEndObjectGenerator = function * (stringDecoder, chunk) {54 yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;55};
deleted:lib/stdio/encoding.js-103 removed
1import {StringDecoder} from 'node:string_decoder';2import {Buffer} from 'node:buffer';3import {isUint8Array} from './utils.js';4import {willPipeStreams} from './pipe.js';56// Apply the `encoding` option using an implicit generator.7// This encodes the final output of `stdout`/`stderr`.8export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {9 const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));10 if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {11 return newStdioStreams;12 }1314 const objectMode = newStdioStreams.findLast(({type}) => type === 'generator')?.value.objectMode === true;15 const stringDecoder = new StringDecoder(encoding);16 const generator = objectMode17 ? {18 transform: encodingEndObjectGenerator.bind(undefined, stringDecoder),19 }20 : {21 transform: encodingEndStringGenerator.bind(undefined, stringDecoder),22 final: encodingEndStringFinal.bind(undefined, stringDecoder),23 };24 return [25 ...newStdioStreams,26 {27 ...newStdioStreams[0],28 type: 'generator',29 value: {...generator, binary: true, objectMode},30 encoding: 'buffer',31 },32 ];33};3435const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'36 && !IGNORED_ENCODINGS.has(encoding)37 && !isSync38 && willPipeStreams(stdioStreams);3940// eslint-disable-next-line unicorn/text-encoding-identifier-case41const IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);4243const encodingEndStringGenerator = function * (stringDecoder, chunk) {44 yield stringDecoder.write(chunk);45};4647const encodingEndStringFinal = function * (stringDecoder) {48 const lastChunk = stringDecoder.end();49 if (lastChunk !== '') {50 yield lastChunk;51 }52};5354const encodingEndObjectGenerator = function * (stringDecoder, chunk) {55 yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;56};5758/*59When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.60This allows generator functions to operate with those types instead.61Chunks might be Buffer, Uint8Array or strings since:62- `childProcess.stdout|stderr` emits Buffers63- `childProcess.stdin.write()` accepts Buffer, Uint8Array or string64- Previous generators might return Uint8Array or string6566However, those are converted to Buffer:67- on writes: `Duplex.writable` `decodeStrings: true` default option68- on reads: `Duplex.readable` `readableEncoding: null` default option69*/70export const getEncodingStartGenerator = encoding => {71 if (encoding === 'buffer') {72 return {transform: encodingStartBufferGenerator.bind(undefined, new TextEncoder())};73 }7475 const textDecoder = new TextDecoder();76 return {77 transform: encodingStartStringGenerator.bind(undefined, textDecoder),78 final: encodingStartStringFinal.bind(undefined, textDecoder),79 };80};8182const encodingStartBufferGenerator = function * (textEncoder, chunk) {83 if (Buffer.isBuffer(chunk)) {84 yield new Uint8Array(chunk);85 } else if (typeof chunk === 'string') {86 yield textEncoder.encode(chunk);87 } else {88 yield chunk;89 }90};9192const encodingStartStringGenerator = function * (textDecoder, chunk) {93 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)94 ? textDecoder.decode(chunk, {stream: true})95 : chunk;96};9798const encodingStartStringFinal = function * (textDecoder) {99 const lastChunk = textDecoder.decode();100 if (lastChunk !== '') {101 yield lastChunk;102 }103};
added:lib/stdio/forward.js+18 added
1// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `childProcess.std*`.2// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `childProcess.std*`.3// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `childProcess.std*`.4export const forwardStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => forwardStdioItem(stdioStreams));56// Whether `childProcess.std*` will be set7export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(forwardStdioItem(stdioStreams));89const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);1011const forwardStdioItem = stdioStreams => {12 if (stdioStreams.length > 1) {13 return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';14 }1516 const [stdioStream] = stdioStreams;17 return stdioStream.type !== 'native' && stdioStream.value !== 'overlapped' ? 'pipe' : stdioStream.value;18};
modified:lib/stdio/generator.js+2 added-29 removed
1import {generatorsToTransform} from './transform.js';2import {getEncodingStartGenerator} from './encoding.js';2import {getEncodingStartGenerator} from './encoding-end.js';3import {getLinesGenerator} from './lines.js';4import {pipeStreams} from './pipeline.js';5import {isGeneratorOptions, isAsyncGenerator} from './type.js';6import {isBinary} from './utils.js';6import {getValidateTransformReturn} from './validate.js';78export const normalizeGenerators = stdioStreams => {9 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');10 const generators = stdioStreams.filter(({type}) => type === 'generator');
72 unmodified lines
83 const duplexStream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});84 return {value: duplexStream};85};8687const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode88 ? validateObjectTransformReturn.bind(undefined, optionName)89 : validateStringTransformReturn.bind(undefined, optionName);9091const validateObjectTransformReturn = function * (optionName, chunk) {92 validateEmptyReturn(optionName, chunk);93 yield chunk;94};9596const validateStringTransformReturn = function * (optionName, chunk) {97 validateEmptyReturn(optionName, chunk);9899 if (typeof chunk !== 'string' && !isBinary(chunk)) {100 throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);101 }102103 yield chunk;104};105106const validateEmptyReturn = (optionName, chunk) => {107 if (chunk === null || chunk === undefined) {108 throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.109Instead, \`yield\` should either be called with a value, or not be called at all. For example:110 if (condition) { yield value; }`);111 }112};11387// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.88export const pipeGenerator = (spawned, {value, direction, index}) => {89 if (direction === 'output') {90 pipeStreams([spawned.stdio[index]], value);
13 unmodified lines
modified:lib/stdio/handle.js+4 added-4 removed
1import {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';2import {addStreamDirection} from './direction.js';3import {normalizeStdio} from './normalize.js';3import {normalizeStdio} from './option.js';4import {handleNativeStream} from './native.js';5import {handleInputOptions} from './input.js';6import {handleStreamsLines} from './lines.js';7import {handleStreamsEncoding} from './encoding.js';7import {handleStreamsEncoding} from './encoding-start.js';8import {normalizeGenerators} from './generator.js';9import {updateStdio} from './pipe.js';9import {forwardStdio} from './forward.js';1011// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode12export const handleInput = (addProperties, options, isSync) => {13 const stdio = normalizeStdio(options);
4 unmodified lines
18 .map(stdioStreams => handleStreamsLines(stdioStreams, options, isSync))19 .map(stdioStreams => handleStreamsEncoding(stdioStreams, options, isSync))20 .map(stdioStreams => normalizeGenerators(stdioStreams))21 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));22 options.stdio = updateStdio(stdioStreamsGroups);22 options.stdio = forwardStdio(stdioStreamsGroups);23 return stdioStreamsGroups;24};2526// We make sure passing an array with a single item behaves the same as passing that item without an array.
70 unmodified lines
modified:lib/stdio/input.js+1 added-1 removed
1import {isReadableStream} from 'is-stream';2import {isUint8Array} from '../utils.js';3import {isUrl, isFilePathString} from './type.js';3import {isUint8Array} from './utils.js';45// Append the `stdin` option with the `input` and `inputFile` options6export const handleInputOptions = ({input, inputFile}) => [7 handleInputOption(input),
43 unmodified lines
modified:lib/stdio/lines.js+2 added-2 removed
1import {isUint8Array} from './utils.js';2import {willPipeStreams} from './pipe.js';1import {isUint8Array} from '../utils.js';2import {willPipeStreams} from './forward.js';34// Split chunks line-wise for streams exposed to users like `childProcess.stdout`.5// Appending a noop transform in object mode is enough to do this, since every non-binary transform iterates line-wise.6export const handleStreamsLines = (stdioStreams, {lines}, isSync) => shouldSplitLines(stdioStreams, lines, isSync)
94 unmodified lines
modified:lib/stdio/native.js+1 added-1 removed
1import {isStream as isNodeStream} from 'is-stream';2import {STANDARD_STREAMS} from './utils.js';2import {STANDARD_STREAMS} from '../utils.js';34// When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.5// We then emulate the piping done by core Node.js.6// To do so, we transform the following values:
40 unmodified lines
deleted:lib/stdio/normalize.js-32 removed
1import {STANDARD_STREAMS_ALIASES} from './utils.js';23// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4export const normalizeStdio = ({stdio, ipc, ...options}) => {5 const stdioArray = getStdioArray(stdio, options);6 return ipc && !stdioArray.includes('ipc')7 ? [...stdioArray, 'ipc']8 : stdioArray;9};1011const getStdioArray = (stdio, options) => {12 if (stdio === undefined) {13 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);14 }1516 if (hasAlias(options)) {17 throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map(alias => `\`${alias}\``).join(', ')}`);18 }1920 if (typeof stdio === 'string') {21 return [stdio, stdio, stdio];22 }2324 if (!Array.isArray(stdio)) {25 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);26 }2728 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);29 return Array.from({length}, (value, index) => stdio[index]);30};3132const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);
added:lib/stdio/option.js+32 added
1import {STANDARD_STREAMS_ALIASES} from '../utils.js';23// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4export const normalizeStdio = ({stdio, ipc, ...options}) => {5 const stdioArray = getStdioArray(stdio, options);6 return ipc && !stdioArray.includes('ipc')7 ? [...stdioArray, 'ipc']8 : stdioArray;9};1011const getStdioArray = (stdio, options) => {12 if (stdio === undefined) {13 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);14 }1516 if (hasAlias(options)) {17 throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map(alias => `\`${alias}\``).join(', ')}`);18 }1920 if (typeof stdio === 'string') {21 return [stdio, stdio, stdio];22 }2324 if (!Array.isArray(stdio)) {25 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);26 }2728 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);29 return Array.from({length}, (value, index) => stdio[index]);30};3132const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);
deleted:lib/stdio/pipe.js-18 removed
1// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `childProcess.std*`.2// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `childProcess.std*`.3// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `childProcess.std*`.4export const updateStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => updateStdioItem(stdioStreams));56// Whether `childProcess.std*` will be set7export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(updateStdioItem(stdioStreams));89const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);1011const updateStdioItem = stdioStreams => {12 if (stdioStreams.length > 1) {13 return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';14 }1516 const [stdioStream] = stdioStreams;17 return stdioStream.type !== 'native' && stdioStream.value !== 'overlapped' ? 'pipe' : stdioStream.value;18};
modified:lib/stdio/pipeline.js+2 added-2 removed
1import {finished} from 'node:stream/promises';2import mergeStreams from '@sindresorhus/merge-streams';3import {isStreamAbort} from '../wait.js';4import {isStandardStream} from './utils.js';3import {isStreamAbort} from '../stream/wait.js';4import {isStandardStream} from '../utils.js';56// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.7// `sources` might be a single stream, or multiple ones combined with `merge-stream`.8export const pipeStreams = (sources, destination) => {
52 unmodified lines
modified:lib/stdio/sync.js+1 added-1 removed
1import {readFileSync, writeFileSync} from 'node:fs';2import {bufferToUint8Array, binaryToString} from '../utils.js';3import {handleInput} from './handle.js';4import {TYPE_TO_MESSAGE} from './type.js';4import {bufferToUint8Array, binaryToString} from './utils.js';56// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7export const handleInputSync = options => {8 const stdioStreamsGroups = handleInput(addPropertiesSync, options, true);
62 unmodified lines
modified:lib/stdio/type.js+1 added-1 removed
1import {isStream as isNodeStream} from 'is-stream';2import {isUint8Array} from './utils.js';2import {isUint8Array} from '../utils.js';34// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5export const getStdioOptionType = (stdioOption, optionName) => {6 if (isGenerator(stdioOption)) {
94 unmodified lines
deleted:lib/stdio/utils.js-27 removed
1import {Buffer} from 'node:buffer';2import {addAbortListener} from 'node:events';3import process from 'node:process';45export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);67export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);8export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);910const textDecoder = new TextDecoder();11export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);1213export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);14export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];15export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];1617export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {18 const maxListeners = eventEmitter.getMaxListeners();19 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {20 return;21 }2223 eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);24 addAbortListener(signal, () => {25 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);26 });27};
added:lib/stdio/validate.js+28 added
1import {isBinary} from '../utils.js';23export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode4 ? validateObjectTransformReturn.bind(undefined, optionName)5 : validateStringTransformReturn.bind(undefined, optionName);67const validateObjectTransformReturn = function * (optionName, chunk) {8 validateEmptyReturn(optionName, chunk);9 yield chunk;10};1112const validateStringTransformReturn = function * (optionName, chunk) {13 validateEmptyReturn(optionName, chunk);1415 if (typeof chunk !== 'string' && !isBinary(chunk)) {16 throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);17 }1819 yield chunk;20};2122const validateEmptyReturn = (optionName, chunk) => {23 if (chunk === null || chunk === undefined) {24 throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.25Instead, \`yield\` should either be called with a value, or not be called at all. For example:26 if (condition) { yield value; }`);27 }28};
added:lib/stream/all.js+36 added
1import mergeStreams from '@sindresorhus/merge-streams';2import {generatorToDuplexStream} from '../stdio/generator.js';3import {waitForChildStream} from './child.js';45// `all` interleaves `stdout` and `stderr`6export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)7 ? mergeStreams([stdout, stderr].filter(Boolean))8 : undefined;910// Read the contents of `childProcess.all` and|or wait for its completion11export const waitForAllStream = ({spawned, encoding, buffer, maxBuffer, streamInfo}) => waitForChildStream({12 stream: getAllStream(spawned, encoding),13 spawned,14 index: 1,15 encoding,16 buffer,17 maxBuffer: maxBuffer * 2,18 streamInfo,19});2021// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:22// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk23// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array24// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.25const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode26 ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)27 : all;2829const allStreamGenerator = {30 * transform(chunk) {31 yield chunk;32 },33 binary: true,34 writableObjectMode: true,35 readableObjectMode: true,36};
added:lib/stream/child.js+70 added
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';45export const waitForChildStream = async ({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}) => {6 if (!stream) {7 return;8 }910 if (isInputFileDescriptor(index, streamInfo.stdioStreamsGroups)) {11 await waitForStream(stream, index, streamInfo);12 return;13 }1415 if (!buffer) {16 await Promise.all([17 waitForStream(stream, index, streamInfo),18 resumeStream(stream),19 ]);20 return;21 }2223 try {24 return await getAnyStream(stream, encoding, maxBuffer);25 } catch (error) {26 if (error instanceof MaxBufferError) {27 spawned.kill();28 }2930 handleStreamError(error, index, streamInfo);31 return handleBufferedData(error, encoding);32 }33};3435// When using `buffer: false`, users need to read `childProcess.stdout|stderr|all` right away36// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631037const resumeStream = async stream => {38 await setImmediate();39 if (stream.readableFlowing === null) {40 stream.resume();41 }42};4344const getAnyStream = async (stream, encoding, maxBuffer) => {45 if (stream.readableObjectMode) {46 return getStreamAsArray(stream, {maxBuffer});47 }4849 const contents = encoding === 'buffer'50 ? await getStreamAsArrayBuffer(stream, {maxBuffer})51 : await getStream(stream, {maxBuffer});52 return applyEncoding(contents, encoding);53};5455// On failure, `result.stdout|stderr|all` should contain the currently buffered stream56// They are automatically closed and flushed by Node.js when the child process exits57// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve58export const getBufferedData = async (streamPromise, encoding) => {59 try {60 return await streamPromise;61 } catch (error) {62 return handleBufferedData(error, encoding);63 }64};6566const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)67 ? error.bufferedData68 : applyEncoding(error.bufferedData, encoding);6970const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;
added:lib/stream/exit.js+31 added
1import {once} from 'node:events';23// If `error` is emitted before `spawn`, `exit` will never be emitted.4// However, `error` might be emitted after `spawn`, e.g. with the `signal` option.5// In that case, `exit` will still be emitted.6// Since the `exit` event contains the signal name, we want to make sure we are listening for it.7// This function also takes into account the following unlikely cases:8// - `exit` being emitted in the same microtask as `spawn`9// - `error` being emitted multiple times10export const waitForExit = async spawned => {11 const [spawnPayload, exitPayload] = await Promise.allSettled([12 once(spawned, 'spawn'),13 once(spawned, 'exit'),14 ]);1516 if (spawnPayload.status === 'rejected') {17 return [];18 }1920 return exitPayload.status === 'rejected'21 ? waitForProcessExit(spawned)22 : exitPayload.value;23};2425const waitForProcessExit = async spawned => {26 try {27 return await once(spawned, 'exit');28 } catch {29 return waitForProcessExit(spawned);30 }31};
added:lib/stream/resolve.js+84 added
1import {once} from 'node:events';2import {isStream} from 'is-stream';3import {waitForSuccessfulExit} from '../exit/code.js';4import {errorSignal} from '../exit/kill.js';5import {throwOnTimeout} from '../exit/timeout.js';6import {isStandardStream} from '../utils.js';7import {waitForAllStream} from './all.js';8import {waitForChildStream, getBufferedData} from './child.js';9import {waitForExit} from './exit.js';10import {waitForStream} from './wait.js';1112// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)13export const getSpawnedResult = async ({14 spawned,15 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},16 context,17 stdioStreamsGroups,18 originalStreams,19 controller,20}) => {21 const exitPromise = waitForExit(spawned);22 const streamInfo = {originalStreams, stdioStreamsGroups, exitPromise, propagating: new Set([])};2324 const stdioPromises = waitForChildStreams({spawned, encoding, buffer, maxBuffer, streamInfo});25 const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, streamInfo});26 const originalPromises = waitForOriginalStreams(originalStreams, spawned, streamInfo);27 const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups, streamInfo);2829 try {30 return await Promise.race([31 Promise.all([32 {},33 waitForSuccessfulExit(exitPromise),34 Promise.all(stdioPromises),35 allPromise,36 ...originalPromises,37 ...customStreamsEndPromises,38 ]),39 throwOnProcessError(spawned, controller),40 throwOnInternalError(spawned, controller),41 ...throwOnTimeout(spawned, timeout, context, controller),42 ]);43 } catch (error) {44 return Promise.all([45 {error},46 exitPromise,47 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),48 getBufferedData(allPromise, encoding),49 Promise.allSettled(originalPromises),50 Promise.allSettled(customStreamsEndPromises),51 ]);52 }53};5455// Read the contents of `childProcess.std*` and|or wait for its completion56const waitForChildStreams = ({spawned, encoding, buffer, maxBuffer, streamInfo}) =>57 spawned.stdio.map((stream, index) => waitForChildStream({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}));5859// Transforms replace `childProcess.std*`, which means they are not exposed to users.60// However, we still want to wait for their completion.61const waitForOriginalStreams = (originalStreams, spawned, streamInfo) =>62 originalStreams.map((stream, index) => stream === spawned.stdio[index]63 ? undefined64 : waitForStream(stream, index, streamInfo));6566// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.67// The `.pipe()` method automatically ends that stream when `childProcess` ends.68// This makes sure we wait for the completion of those streams, in order to catch any error.69const waitForCustomStreamsEnd = (stdioStreamsGroups, streamInfo) => stdioStreamsGroups.flatMap((stdioStreams, index) => stdioStreams70 .filter(({value}) => isStream(value, {checkOpen: false}) && !isStandardStream(value))71 .map(({type, value}) => waitForStream(value, index, streamInfo, {72 isSameDirection: type === 'generator',73 stopOnExit: type === 'native',74 })));7576const throwOnProcessError = async (spawned, {signal}) => {77 const [error] = await once(spawned, 'error', {signal});78 throw error;79};8081const throwOnInternalError = async (spawned, {signal}) => {82 const [error] = await once(spawned, errorSignal, {signal});83 throw error;84};
added:lib/stream/wait.js+61 added
1import {finished} from 'node:stream/promises';23// Wraps `finished(stream)` to handle the following case:4// - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.5// - However, we still need to throw if `childProcess.stdin.destroy()` is called before child process exit.6export const waitForStream = async (stream, index, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7 const {originalStreams: [originalStdin], exitPromise} = streamInfo;89 const abortController = new AbortController();10 try {11 await Promise.race([12 ...(stopOnExit || stream === originalStdin ? [exitPromise] : []),13 finished(stream, {cleanup: true, signal: abortController.signal}),14 ]);15 } catch (error) {16 handleStreamError(error, index, streamInfo, isSameDirection);17 } finally {18 abortController.abort();19 }20};2122// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.23// When one stream errors, the error is propagated to the other streams on the same file descriptor.24// Those other streams might have a different direction due to the above.25// When this happens, the direction of both the initial stream and the others should then be taken into account.26// Therefore, we keep track of which file descriptor is currently propagating stream errors.27export const handleStreamError = (error, index, streamInfo, isSameDirection) => {28 if (!shouldIgnoreStreamError(error, index, streamInfo, isSameDirection)) {29 throw error;30 }31};3233const shouldIgnoreStreamError = (error, index, {stdioStreamsGroups, propagating}, isSameDirection = true) => {34 if (propagating.has(index)) {35 return isStreamEpipe(error) || isStreamAbort(error);36 }3738 propagating.add(index);39 return isInputFileDescriptor(index, stdioStreamsGroups) === isSameDirection40 ? isStreamEpipe(error)41 : isStreamAbort(error);42};4344// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.45// For example, `childProcess.stdin` is technically a Duplex, but can only be used as a writable.46// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).47// However, while `childProcess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.48// For example, `childProcess.stdin` is a writable, but the `stdin` option is a readable.49export const isInputFileDescriptor = (index, stdioStreamsGroups) => stdioStreamsGroups[index][0].direction === 'input';5051// When `stream.destroy()` is called without an `error` argument, stream is aborted.52// This is the only way to abort a readable stream, which can be useful in some instances.53// Therefore, we ignore this error on readable streams.54export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';5556// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.57// When piping processes, the source process usually decides when to stop piping.58// However, there are some instances when the destination does instead, such as `... | head -n1`.59// It notifies the source by using `EPIPE`.60// Therefore, we ignore this error on writable streams.61const isStreamEpipe = error => error?.code === 'EPIPE';
added:lib/async.js+94 added
1import {setMaxListeners} from 'node:events';2import childProcess from 'node:child_process';3import {handleOptionalArguments, handleArguments} from './arguments/options.js';4import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';5import {handleOutput} from './return/output.js';6import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './stdio/async.js';7import {spawnedKill} from './exit/kill.js';8import {cleanupOnExit} from './exit/cleanup.js';9import {pipeToProcess} from './pipe/setup.js';10import {makeAllStream} from './stream/all.js';11import {getSpawnedResult} from './stream/resolve.js';12import {mergePromise} from './promise.js';1314export const execa = (rawFile, rawArgs, rawOptions) => {15 const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);16 const stdioStreamsGroups = handleInputAsync(options);1718 let spawned;19 try {20 spawned = childProcess.spawn(file, args, options);21 } catch (error) {22 cleanupStdioStreams(stdioStreamsGroups);23 // Ensure the returned error is always both a promise and a child process24 const dummySpawned = new childProcess.ChildProcess();25 const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});26 const errorPromise = options.reject ? Promise.reject(errorInstance) : Promise.resolve(errorInstance);27 mergePromise(dummySpawned, errorPromise);28 return dummySpawned;29 }3031 const controller = new AbortController();32 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);3334 const originalStreams = [...spawned.stdio];35 pipeOutputAsync(spawned, stdioStreamsGroups, controller);36 cleanupOnExit(spawned, options, controller);3738 spawned.kill = spawnedKill.bind(undefined, {kill: spawned.kill.bind(spawned), spawned, options, controller});39 spawned.all = makeAllStream(spawned, options);40 spawned.pipe = pipeToProcess.bind(undefined, {spawned, stdioStreamsGroups, options});4142 const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});43 mergePromise(spawned, promise);44 return spawned;45};4647const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {48 [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);49 const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);50 const options = handleAsyncOptions(normalizedOptions);51 return {file, args, command, escapedCommand, options};52};5354// Prevent passing the `timeout` option directly to `child_process.spawn()`55const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});5657const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {58 const context = {timedOut: false};5960 const [61 errorInfo,62 [exitCode, signal],63 stdioResults,64 allResult,65 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});66 controller.abort();6768 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));69 const all = handleOutput(options, allResult);7071 if ('error' in errorInfo) {72 const isCanceled = options.signal?.aborted === true;73 const returnedError = makeError({74 error: errorInfo.error,75 command,76 escapedCommand,77 timedOut: context.timedOut,78 isCanceled,79 exitCode,80 signal,81 stdio,82 all,83 options,84 });8586 if (!options.reject) {87 return returnedError;88 }8990 throw returnedError;91 }9293 return makeSuccessResult({command, escapedCommand, stdio, all, options});94};
deleted:lib/clone.js-70 removed
1export const getFinalError = (initialError, message) => {2 const error = createFinalError(initialError, message);3 previousErrors.add(error);4 return error;5};67const createFinalError = (error, message) => {8 if (!isErrorInstance(error)) {9 return new Error(message);10 }1112 return previousErrors.has(error)13 ? cloneError(error, message)14 : setErrorMessage(error, message);15};1617export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';1819const cloneError = (oldError, newMessage) => {20 const {name, message, stack} = oldError;21 const error = new Error(newMessage);22 error.stack = fixStack(stack, message, newMessage);23 Object.defineProperty(error, 'name', {value: name, enumerable: false, configurable: true, writable: true});24 copyErrorProperties(error, oldError);25 return error;26};2728const copyErrorProperties = (newError, previousError) => {29 for (const propertyName of COPIED_ERROR_PROPERTIES) {30 const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName);31 if (descriptor !== undefined) {32 Object.defineProperty(newError, propertyName, descriptor);33 }34 }35};3637// Known error properties38const COPIED_ERROR_PROPERTIES = [39 'cause',40 'errors',41 'code',42 'errno',43 'syscall',44 'path',45 'dest',46 'address',47 'port',48 'info',49];5051// Sets `error.message`.52// Fixes `error.stack` not being updated when it has been already accessed, since it is memoized by V8.53// For example, this happens when calling `stream.destroy(error)`.54// See https://github.com/nodejs/node/issues/5171555const setErrorMessage = (error, newMessage) => {56 const {message, stack} = error;57 error.message = newMessage;58 error.stack = fixStack(stack, message, newMessage);59 return error;60};6162const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63 ? stack64 : stack.replace(`: ${message}`, `: ${newMessage}`);6566// Two `execa()` calls might return the same error.67// So we must close those before directly mutating them.68export const isPreviousError = error => previousErrors.has(error);6970const previousErrors = new WeakSet();
modified:lib/command.js+15 added-3 removed
1const SPACES_REGEXP = / +/g;1import {execa} from './async.js';2import {execaSync} from './sync.js';33// Handle `execaCommand()`4export const parseCommand = command => {4export function execaCommand(command, options) {5 const [file, ...args] = parseCommand(command);6 return execa(file, args, options);7}89export function execaCommandSync(command, options) {10 const [file, ...args] = parseCommand(command);11 return execaSync(file, args, options);12}1314const parseCommand = command => {15 const tokens = [];16 for (const token of command.trim().split(SPACES_REGEXP)) {17 // Allow spaces to be escaped by a backslash if not meant as a delimiter18 const previousToken = tokens.at(-1);
6 unmodified lines
25 }2627 return tokens;28};2930const SPACES_REGEXP = / +/g;
deleted:lib/cwd.js-49 removed
1import {statSync} from 'node:fs';2import {resolve} from 'node:path';3import {fileURLToPath} from 'node:url';4import process from 'node:process';56export const normalizeCwd = (cwd = getDefaultCwd()) => {7 const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option');8 return resolve(cwdString);9};1011const getDefaultCwd = () => {12 try {13 return process.cwd();14 } catch (error) {15 error.message = `The current directory does not exist.\n${error.message}`;16 throw error;17 }18};1920export const safeNormalizeFileUrl = (file, name) => {21 const fileString = normalizeFileUrl(file);2223 if (typeof fileString !== 'string') {24 throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`);25 }2627 return fileString;28};2930export const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;3132export const fixCwdError = (originalMessage, cwd) => {33 if (cwd === getDefaultCwd()) {34 return originalMessage;35 }3637 let cwdStat;38 try {39 cwdStat = statSync(cwd);40 } catch (error) {41 return `The "cwd" option is invalid: ${cwd}.\n${error.message}\n${originalMessage}`;42 }4344 if (!cwdStat.isDirectory()) {45 return `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`;46 }4748 return originalMessage;49};
deleted:lib/error.js-191 removed
1import {signalsByName} from 'human-signals';2import stripFinalNewline from 'strip-final-newline';3import {isBinary, binaryToString} from './stdio/utils.js';4import {fixCwdError} from './cwd.js';5import {getFinalError, isPreviousError} from './clone.js';67const createMessages = ({8 stdio,9 all,10 error,11 signal,12 signalDescription,13 exitCode,14 command,15 timedOut,16 isCanceled,17 timeout,18 cwd,19}) => {20 const errorCode = error?.code;21 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});22 const originalMessage = getOriginalMessage(error, cwd);23 const newline = originalMessage === '' ? '' : '\n';24 const shortMessage = `${prefix}: ${command}${newline}${originalMessage}`;25 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];26 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]27 .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart)))28 .filter(Boolean)29 .join('\n\n');30 return {originalMessage, shortMessage, message};31};3233const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {34 if (timedOut) {35 return `Command timed out after ${timeout} milliseconds`;36 }3738 if (isCanceled) {39 return 'Command was canceled';40 }4142 if (errorCode !== undefined) {43 return `Command failed with ${errorCode}`;44 }4546 if (signal !== undefined) {47 return `Command was killed with ${signal} (${signalDescription})`;48 }4950 if (exitCode !== undefined) {51 return `Command failed with exit code ${exitCode}`;52 }5354 return 'Command failed';55};5657const getOriginalMessage = (error, cwd) => {58 if (error === undefined) {59 return '';60 }6162 const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);63 return fixCwdError(originalMessage, cwd);64};6566const serializeMessagePart = messagePart => Array.isArray(messagePart)67 ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')68 : serializeMessageItem(messagePart);6970const serializeMessageItem = messageItem => {71 if (typeof messageItem === 'string') {72 return messageItem;73 }7475 if (isBinary(messageItem)) {76 return binaryToString(messageItem);77 }7879 return '';80};8182// Indicates that the error is used only to interrupt control flow, but not in the return value83export class DiscardedError extends Error {}8485// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.86// We normalize them to `undefined`87const normalizeExitPayload = (rawExitCode, rawSignal) => {88 const exitCode = rawExitCode === null ? undefined : rawExitCode;89 const signal = rawSignal === null ? undefined : rawSignal;90 const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;91 return {exitCode, signal, signalDescription};92};9394export const makeError = ({95 error: rawError,96 command,97 escapedCommand,98 timedOut,99 isCanceled,100 exitCode: rawExitCode,101 signal: rawSignal,102 stdio,103 all,104 options: {timeoutDuration, timeout = timeoutDuration, cwd},105}) => {106 const initialError = rawError instanceof DiscardedError ? undefined : rawError;107 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);108 const {originalMessage, shortMessage, message} = createMessages({109 stdio,110 all,111 error: initialError,112 signal,113 signalDescription,114 exitCode,115 command,116 timedOut,117 isCanceled,118 timeout,119 cwd,120 });121 const error = getFinalError(initialError, message);122123 error.shortMessage = shortMessage;124 error.originalMessage = originalMessage;125 error.command = command;126 error.escapedCommand = escapedCommand;127 error.cwd = cwd;128129 error.failed = true;130 error.timedOut = timedOut;131 error.isCanceled = isCanceled;132 error.isTerminated = signal !== undefined;133 error.exitCode = exitCode;134 error.signal = signal;135 error.signalDescription = signalDescription;136137 error.stdout = stdio[1];138 error.stderr = stdio[2];139140 if (all !== undefined) {141 error.all = all;142 }143144 error.stdio = stdio;145146 if ('bufferedData' in error) {147 delete error.bufferedData;148 }149150 error.pipedFrom = [];151152 return error;153};154155export const makeEarlyError = ({156 error,157 command,158 escapedCommand,159 stdioStreamsGroups,160 options,161}) => makeError({162 error,163 command,164 escapedCommand,165 timedOut: false,166 isCanceled: false,167 stdio: Array.from({length: stdioStreamsGroups.length}),168 options,169});170171export const makeSuccessResult = ({172 command,173 escapedCommand,174 stdio,175 all,176 options: {cwd},177}) => ({178 command,179 escapedCommand,180 cwd,181 failed: false,182 timedOut: false,183 isCanceled: false,184 isTerminated: false,185 exitCode: 0,186 stdout: stdio[1],187 stderr: stdio[2],188 all,189 stdio,190 pipedFrom: [],191});
deleted:lib/escape.js-12 removed
1export const joinCommand = (filePath, rawArgs) => {2 const fileAndArgs = [filePath, ...rawArgs];3 const command = fileAndArgs.join(' ');4 const escapedCommand = fileAndArgs.map(arg => escapeArg(arg)).join(' ');5 return {command, escapedCommand};6};78const escapeArg = arg => typeof arg === 'string' && !NO_ESCAPE_REGEXP.test(arg)9 ? `"${arg.replaceAll('"', '\\"')}"`10 : arg;1112const NO_ESCAPE_REGEXP = /^[\w.-]+$/;
deleted:lib/kill.js-124 removed
1import {addAbortListener} from 'node:events';2import os from 'node:os';3import {setTimeout} from 'node:timers/promises';4import {onExit} from 'signal-exit';5import {isErrorInstance} from './clone.js';6import {DiscardedError} from './error.js';78const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;910// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`11export const spawnedKill = ({kill, spawned, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => {12 const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);13 emitKillError(spawned, error);14 const killResult = kill(signal);15 setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller});16 return killResult;17};1819const parseKillArguments = (signalOrError, errorArgument, killSignal) => {20 const [signal = killSignal, error] = isErrorInstance(signalOrError)21 ? [undefined, signalOrError]22 : [signalOrError, errorArgument];2324 if (typeof signal !== 'string' && typeof signal !== 'number') {25 throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signal}`);26 }2728 if (error !== undefined && !isErrorInstance(error)) {29 throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);30 }3132 return {signal, error};33};3435const emitKillError = (spawned, error) => {36 if (error !== undefined) {37 spawned.emit(errorSignal, error);38 }39};4041// Like `error` signal but internal to Execa.42// E.g. does not make process crash when no `error` listener is set.43export const errorSignal = Symbol('error');4445const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {46 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {47 return;48 }4950 try {51 await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});52 kill('SIGKILL');53 } catch {}54};5556const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>57 normalizeSignal(signal) === normalizeSignal(killSignal)58 && forceKillAfterDelay !== false59 && killResult;6061const normalizeSignal = signal => typeof signal === 'string'62 ? os.constants.signals[signal.toUpperCase()]63 : signal;6465export const normalizeForceKillAfterDelay = forceKillAfterDelay => {66 if (forceKillAfterDelay === false) {67 return forceKillAfterDelay;68 }6970 if (forceKillAfterDelay === true) {71 return DEFAULT_FORCE_KILL_TIMEOUT;72 }7374 if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) {75 throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);76 }7778 return forceKillAfterDelay;79};8081export const waitForSuccessfulExit = async exitPromise => {82 const [exitCode, signal] = await exitPromise;8384 if (!isProcessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {85 throw new DiscardedError();86 }8788 return [exitCode, signal];89};9091const isProcessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;92export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;9394const killAfterTimeout = async (spawned, timeout, context, {signal}) => {95 await setTimeout(timeout, undefined, {signal});96 context.timedOut = true;97 spawned.kill();98 throw new DiscardedError();99};100101// `timeout` option handling102export const throwOnTimeout = (spawned, timeout, context, controller) => timeout === 0 || timeout === undefined103 ? []104 : [killAfterTimeout(spawned, timeout, context, controller)];105106export const validateTimeout = ({timeout}) => {107 if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {108 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);109 }110};111112// `cleanup` option handling113export const cleanupOnExit = (spawned, {cleanup, detached}, {signal}) => {114 if (!cleanup || detached) {115 return;116 }117118 const removeExitHandler = onExit(() => {119 spawned.kill();120 });121 addAbortListener(signal, () => {122 removeExitHandler();123 });124};
deleted:lib/node.js-34 removed
1import {execPath, execArgv} from 'node:process';2import {basename, resolve} from 'node:path';3import {safeNormalizeFileUrl} from './cwd.js';45export const handleNodeOption = (file, args, {6 node: shouldHandleNode = false,7 nodePath = execPath,8 nodeOptions = execArgv.filter(arg => !arg.startsWith('--inspect')),9 cwd,10 execPath: formerNodePath,11 ...options12}) => {13 if (formerNodePath !== undefined) {14 throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');15 }1617 const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');18 const resolvedNodePath = resolve(cwd, normalizedNodePath);19 const newOptions = {...options, nodePath: resolvedNodePath, cwd};2021 if (!shouldHandleNode) {22 return [file, args, newOptions];23 }2425 if (basename(file, '.exe') === 'node') {26 throw new TypeError('When the "node" option is true, the first argument does not need to be "node".');27 }2829 return [30 resolvedNodePath,31 [...nodeOptions, file, ...args],32 {ipc: true, ...newOptions, shell: false},33 ];34};
modified:lib/promise.js+8 added-8 removed
1// eslint-disable-next-line unicorn/prefer-top-level-await2const nativePromisePrototype = (async () => {})().constructor.prototype;34const descriptors = ['then', 'catch', 'finally'].map(property => [5 property,6 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),7]);81// The return value is a mixin of `childProcess` and `Promise`2export const mergePromise = (spawned, promise) => {3 for (const [property, descriptor] of descriptors) {4 const value = descriptor.value.bind(promise);5 Reflect.defineProperty(spawned, property, {...descriptor, value});6 }7};89// eslint-disable-next-line unicorn/prefer-top-level-await10const nativePromisePrototype = (async () => {})().constructor.prototype;1112const descriptors = ['then', 'catch', 'finally'].map(property => [13 property,14 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15]);
modified:lib/script.js+75 added-38 removed
1import {ChildProcess} from 'node:child_process';2import {isBinary, binaryToString} from './stdio/utils.js';2import {isBinary, binaryToString} from './utils.js';3import {execa} from './async.js';4import {execaSync} from './sync.js';54const parseExpression = expression => {5 const typeOfExpression = typeof expression;6const create$ = options => {7 function $(templatesOrOptions, ...expressions) {8 if (!Array.isArray(templatesOrOptions)) {9 return create$({...options, ...templatesOrOptions});10 }117 if (typeOfExpression === 'string') {8 return expression;12 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);13 return execa(file, args, normalizeScriptOptions(options));14 }1511 if (typeOfExpression === 'number') {12 return String(expression);13 }1415 if (16 typeOfExpression === 'object'17 && expression !== null18 && !(expression instanceof ChildProcess)19 && 'stdout' in expression20 ) {21 const typeOfStdout = typeof expression.stdout;2223 if (typeOfStdout === 'string') {24 return expression.stdout;16 $.sync = (templates, ...expressions) => {17 if (!Array.isArray(templates)) {18 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');19 }2027 if (isBinary(expression.stdout)) {28 return binaryToString(expression.stdout);29 }21 const [file, ...args] = parseTemplates(templates, expressions);22 return execaSync(file, args, normalizeScriptOptions(options));23 };2431 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);32 }25 $.s = $.sync;2634 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);27 return $;28};2937const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 038 ? [...tokens, ...nextTokens]39 : [40 ...tokens.slice(0, -1),41 `${tokens.at(-1)}${nextTokens[0]}`,42 ...nextTokens.slice(1),43 ];30export const $ = create$();3145const SPACES_REGEXP = / +/g;32const parseTemplates = (templates, expressions) => {33 let tokens = [];3435 for (const [index, template] of templates.entries()) {36 tokens = parseTemplate({templates, expressions, tokens, index, template});37 }3839 return tokens;40};4142const parseTemplate = ({templates, expressions, tokens, index, template}) => {43 const templateString = template ?? templates.raw[index];44 const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);45 const newTokens = concatTokens(
16 unmodified lines
62 templateString.endsWith(' '),63 );64};6571export const parseTemplates = (templates, expressions) => {72 let tokens = [];66const SPACES_REGEXP = / +/g;6774 for (const [index, template] of templates.entries()) {75 tokens = parseTemplate({templates, expressions, tokens, index, template});68const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 069 ? [...tokens, ...nextTokens]70 : [71 ...tokens.slice(0, -1),72 `${tokens.at(-1)}${nextTokens[0]}`,73 ...nextTokens.slice(1),74 ];7576const parseExpression = expression => {77 const typeOfExpression = typeof expression;7879 if (typeOfExpression === 'string') {80 return expression;81 }8278 return tokens;83 if (typeOfExpression === 'number') {84 return String(expression);85 }8687 if (88 typeOfExpression === 'object'89 && expression !== null90 && !(expression instanceof ChildProcess)91 && 'stdout' in expression92 ) {93 const typeOfStdout = typeof expression.stdout;9495 if (typeOfStdout === 'string') {96 return expression.stdout;97 }9899 if (isBinary(expression.stdout)) {100 return binaryToString(expression.stdout);101 }102103 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);104 }105106 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);107};108109const normalizeScriptOptions = (options = {}) => ({110 preferLocal: true,111 ...normalizeScriptStdin(options),112 ...options,113});114115const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined116 ? {stdin: 'inherit'}117 : {};
deleted:lib/stream.js-220 removed
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';4import {isStream} from 'is-stream';5import mergeStreams from '@sindresorhus/merge-streams';6import {waitForSuccessfulExit, throwOnTimeout, errorSignal} from './kill.js';7import {isStandardStream} from './stdio/utils.js';8import {generatorToDuplexStream} from './stdio/generator.js';9import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';1011// `all` interleaves `stdout` and `stderr`12export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)13 ? mergeStreams([stdout, stderr].filter(Boolean))14 : undefined;1516// On failure, `result.stdout|stderr|all` should contain the currently buffered stream17// They are automatically closed and flushed by Node.js when the child process exits18// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve19const getBufferedData = async (streamPromise, encoding) => {20 try {21 return await streamPromise;22 } catch (error) {23 return handleBufferedData(error, encoding);24 }25};2627const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)28 ? error.bufferedData29 : applyEncoding(error.bufferedData, encoding);3031// Read the contents of `childProcess.std*` and|or wait for its completion32const waitForChildStreams = ({spawned, encoding, buffer, maxBuffer, streamInfo}) => spawned.stdio.map((stream, index) => waitForChildStream({33 stream,34 spawned,35 index,36 encoding,37 buffer,38 maxBuffer,39 streamInfo,40}));4142// Read the contents of `childProcess.all` and|or wait for its completion43const waitForAllStream = ({spawned, encoding, buffer, maxBuffer, streamInfo}) => waitForChildStream({44 stream: getAllStream(spawned, encoding),45 spawned,46 index: 1,47 encoding,48 buffer,49 maxBuffer: maxBuffer * 2,50 streamInfo,51});5253// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:54// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk55// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array56// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.57const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode58 ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)59 : all;6061const allStreamGenerator = {62 * transform(chunk) {63 yield chunk;64 },65 binary: true,66 writableObjectMode: true,67 readableObjectMode: true,68};6970const waitForChildStream = async ({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}) => {71 if (!stream) {72 return;73 }7475 if (isInputFileDescriptor(index, streamInfo.stdioStreamsGroups)) {76 await waitForStream(stream, index, streamInfo);77 return;78 }7980 if (!buffer) {81 await Promise.all([82 waitForStream(stream, index, streamInfo),83 resumeStream(stream),84 ]);85 return;86 }8788 try {89 return await getAnyStream(stream, encoding, maxBuffer);90 } catch (error) {91 if (error instanceof MaxBufferError) {92 spawned.kill();93 }9495 handleStreamError(error, index, streamInfo);96 return handleBufferedData(error, encoding);97 }98};99100// When using `buffer: false`, users need to read `childProcess.stdout|stderr|all` right away101// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r1465496310102const resumeStream = async stream => {103 await setImmediate();104 if (stream.readableFlowing === null) {105 stream.resume();106 }107};108109const getAnyStream = async (stream, encoding, maxBuffer) => {110 if (stream.readableObjectMode) {111 return getStreamAsArray(stream, {maxBuffer});112 }113114 const contents = encoding === 'buffer'115 ? await getStreamAsArrayBuffer(stream, {maxBuffer})116 : await getStream(stream, {maxBuffer});117 return applyEncoding(contents, encoding);118};119120const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;121122// Transforms replace `childProcess.std*`, which means they are not exposed to users.123// However, we still want to wait for their completion.124const waitForOriginalStreams = (originalStreams, spawned, streamInfo) =>125 originalStreams.map((stream, index) => stream === spawned.stdio[index]126 ? undefined127 : waitForStream(stream, index, streamInfo));128129// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.130// The `.pipe()` method automatically ends that stream when `childProcess` ends.131// This makes sure we wait for the completion of those streams, in order to catch any error.132const waitForCustomStreamsEnd = (stdioStreamsGroups, streamInfo) => stdioStreamsGroups.flatMap((stdioStreams, index) => stdioStreams133 .filter(({value}) => isStream(value, {checkOpen: false}) && !isStandardStream(value))134 .map(({type, value}) => waitForStream(value, index, streamInfo, {135 isSameDirection: type === 'generator',136 stopOnExit: type === 'native',137 })));138139const throwOnProcessError = async (spawned, {signal}) => {140 const [error] = await once(spawned, 'error', {signal});141 throw error;142};143144const throwOnInternalError = async (spawned, {signal}) => {145 const [error] = await once(spawned, errorSignal, {signal});146 throw error;147};148149// If `error` is emitted before `spawn`, `exit` will never be emitted.150// However, `error` might be emitted after `spawn`, e.g. with the `signal` option.151// In that case, `exit` will still be emitted.152// Since the `exit` event contains the signal name, we want to make sure we are listening for it.153// This function also takes into account the following unlikely cases:154// - `exit` being emitted in the same microtask as `spawn`155// - `error` being emitted multiple times156const waitForExit = async spawned => {157 const [spawnPayload, exitPayload] = await Promise.allSettled([158 once(spawned, 'spawn'),159 once(spawned, 'exit'),160 ]);161162 if (spawnPayload.status === 'rejected') {163 return [];164 }165166 return exitPayload.status === 'rejected'167 ? waitForProcessExit(spawned)168 : exitPayload.value;169};170171const waitForProcessExit = async spawned => {172 try {173 return await once(spawned, 'exit');174 } catch {175 return waitForProcessExit(spawned);176 }177};178179// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)180export const getSpawnedResult = async ({181 spawned,182 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},183 context,184 stdioStreamsGroups,185 originalStreams,186 controller,187}) => {188 const exitPromise = waitForExit(spawned);189 const streamInfo = {originalStreams, stdioStreamsGroups, exitPromise, propagating: new Set([])};190191 const stdioPromises = waitForChildStreams({spawned, encoding, buffer, maxBuffer, streamInfo});192 const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, streamInfo});193 const originalPromises = waitForOriginalStreams(originalStreams, spawned, streamInfo);194 const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups, streamInfo);195196 try {197 return await Promise.race([198 Promise.all([199 {},200 waitForSuccessfulExit(exitPromise),201 Promise.all(stdioPromises),202 allPromise,203 ...originalPromises,204 ...customStreamsEndPromises,205 ]),206 throwOnProcessError(spawned, controller),207 throwOnInternalError(spawned, controller),208 ...throwOnTimeout(spawned, timeout, context, controller),209 ]);210 } catch (error) {211 return Promise.all([212 {error},213 exitPromise,214 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),215 getBufferedData(allPromise, encoding),216 Promise.allSettled(originalPromises),217 Promise.allSettled(customStreamsEndPromises),218 ]);219 }220};
added:lib/sync.js+67 added
1import childProcess from 'node:child_process';2import {handleOptionalArguments, handleArguments} from './arguments/options.js';3import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4import {handleOutput} from './return/output.js';5import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6import {isFailedExit} from './exit/code.js';78export const execaSync = (rawFile, rawArgs, rawOptions) => {9 const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);10 const stdioStreamsGroups = handleInputSync(options);1112 let result;13 try {14 result = childProcess.spawnSync(file, args, options);15 } catch (error) {16 const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});1718 if (!options.reject) {19 return errorInstance;20 }2122 throw errorInstance;23 }2425 pipeOutputSync(stdioStreamsGroups, result);2627 const output = result.output || Array.from({length: 3});28 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));2930 if (result.error !== undefined || isFailedExit(result.status, result.signal)) {31 const error = makeError({32 error: result.error,33 command,34 escapedCommand,35 timedOut: result.error && result.error.code === 'ETIMEDOUT',36 isCanceled: false,37 exitCode: result.status,38 signal: result.signal,39 stdio,40 options,41 });4243 if (!options.reject) {44 return error;45 }4647 throw error;48 }4950 return makeSuccessResult({command, escapedCommand, stdio, options});51};5253const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {54 [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);55 const syncOptions = normalizeSyncOptions(rawOptions);56 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);57 validateSyncOptions(options);58 return {file, args, command, escapedCommand, options};59};6061const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;6263const validateSyncOptions = ({ipc}) => {64 if (ipc) {65 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');66 }67};
added:lib/utils.js+27 added
1import {Buffer} from 'node:buffer';2import {addAbortListener} from 'node:events';3import process from 'node:process';45export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);67export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);8export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);910const textDecoder = new TextDecoder();11export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);1213export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);14export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];15export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];1617export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {18 const maxListeners = eventEmitter.getMaxListeners();19 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {20 return;21 }2223 eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);24 addAbortListener(signal, () => {25 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);26 });27};
deleted:lib/verbose.js-22 removed
1import {writeFileSync} from 'node:fs';2import {debuglog} from 'node:util';3import process from 'node:process';45export const verboseDefault = debuglog('execa').enabled;67const padField = (field, padding) => String(field).padStart(padding, '0');89const getTimestamp = () => {10 const date = new Date();11 return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;12};1314export const logCommand = (escapedCommand, {verbose}) => {15 if (!verbose) {16 return;17 }1819 // Write synchronously to ensure it is written before spawning the child process.20 // This guarantees this line is written to `stderr` before the child process prints anything.21 writeFileSync(process.stderr.fd, `[${getTimestamp()}] ${escapedCommand}\n`);22};
deleted:lib/wait.js-61 removed
1import {finished} from 'node:stream/promises';23// Wraps `finished(stream)` to handle the following case:4// - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.5// - However, we still need to throw if `childProcess.stdin.destroy()` is called before child process exit.6export const waitForStream = async (stream, index, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7 const {originalStreams: [originalStdin], exitPromise} = streamInfo;89 const abortController = new AbortController();10 try {11 await Promise.race([12 ...(stopOnExit || stream === originalStdin ? [exitPromise] : []),13 finished(stream, {cleanup: true, signal: abortController.signal}),14 ]);15 } catch (error) {16 handleStreamError(error, index, streamInfo, isSameDirection);17 } finally {18 abortController.abort();19 }20};2122// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.23// When one stream errors, the error is propagated to the other streams on the same file descriptor.24// Those other streams might have a different direction due to the above.25// When this happens, the direction of both the initial stream and the others should then be taken into account.26// Therefore, we keep track of which file descriptor is currently propagating stream errors.27export const handleStreamError = (error, index, streamInfo, isSameDirection) => {28 if (!shouldIgnoreStreamError(error, index, streamInfo, isSameDirection)) {29 throw error;30 }31};3233const shouldIgnoreStreamError = (error, index, {stdioStreamsGroups, propagating}, isSameDirection = true) => {34 if (propagating.has(index)) {35 return isStreamEpipe(error) || isStreamAbort(error);36 }3738 propagating.add(index);39 return isInputFileDescriptor(index, stdioStreamsGroups) === isSameDirection40 ? isStreamEpipe(error)41 : isStreamAbort(error);42};4344// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.45// For example, `childProcess.stdin` is technically a Duplex, but can only be used as a writable.46// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).47// However, while `childProcess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.48// For example, `childProcess.stdin` is a writable, but the `stdin` option is a readable.49export const isInputFileDescriptor = (index, stdioStreamsGroups) => stdioStreamsGroups[index][0].direction === 'input';5051// When `stream.destroy()` is called without an `error` argument, stream is aborted.52// This is the only way to abort a readable stream, which can be useful in some instances.53// Therefore, we ignore this error on readable streams.54export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';5556// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.57// When piping processes, the source process usually decides when to stop piping.58// However, there are some instances when the destination does instead, such as `... | head -n1`.59// It notifies the source by using `EPIPE`.60// Therefore, we ignore this error on writable streams.61const isStreamEpipe = error => error?.code === 'EPIPE';
added:test/arguments/cwd.js+103 added
1import {mkdir, rmdir} from 'node:fs/promises';2import {relative, toNamespacedPath} from 'node:path';3import process from 'node:process';4import {pathToFileURL, fileURLToPath} from 'node:url';5import tempfile from 'tempfile';6import test from 'ava';7import {execa, execaSync} from '../../index.js';8import {FIXTURES_DIR, setFixtureDir} from '../helpers/fixtures-dir.js';910setFixtureDir();1112const isWindows = process.platform === 'win32';1314const testOptionCwdString = async (t, execaMethod) => {15 const cwd = '/';16 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd});17 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));18};1920test('The "cwd" option can be a string', testOptionCwdString, execa);21test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);2223const testOptionCwdUrl = async (t, execaMethod) => {24 const cwd = '/';25 const cwdUrl = pathToFileURL(cwd);26 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd: cwdUrl});27 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));28};2930test('The "cwd" option can be a URL', testOptionCwdUrl, execa);31test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);3233const testOptionCwdInvalid = (t, execaMethod) => {34 t.throws(() => {35 execaMethod('empty.js', {cwd: true});36 }, {message: /The "cwd" option must be a string or a file URL: true/});37};3839test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);40test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);4142const testErrorCwdDefault = async (t, execaMethod) => {43 const {cwd} = await execaMethod('empty.js');44 t.is(cwd, process.cwd());45};4647test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);4950// Windows does not allow removing a directory used as `cwd` of a running process51if (!isWindows) {52 const testCwdPreSpawn = async (t, execaMethod) => {53 const currentCwd = process.cwd();54 const filePath = tempfile();55 await mkdir(filePath);56 process.chdir(filePath);57 await rmdir(filePath);5859 try {60 t.throws(() => {61 execaMethod('empty.js');62 }, {message: /The current directory does not exist/});63 } finally {64 process.chdir(currentCwd);65 }66 };6768 test.serial('The "cwd" option default fails if current cwd is missing', testCwdPreSpawn, execa);69 test.serial('The "cwd" option default fails if current cwd is missing - sync', testCwdPreSpawn, execaSync);70}7172const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74const cwdNotDir = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};7576const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {77 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});78 t.true(failed);79 t.is(code, expectedCode);80 t.true(message.includes(expectedMessage));81 t.true(message.includes(cwd));82};8384test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);85test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);86test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);87test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);88test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDir, execa);89test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDir, execaSync);9091const successProperties = {fixtureName: 'empty.js', expectedFailed: false};92const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};9394const testErrorCwd = async (t, execaMethod, {fixtureName, expectedFailed}) => {95 const {failed, cwd} = await execaMethod(fixtureName, {cwd: relative('.', FIXTURES_DIR), reject: false});96 t.is(failed, expectedFailed);97 t.is(cwd, FIXTURES_DIR);98};99100test('result.cwd is defined', testErrorCwd, execa, successProperties);101test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);102test('error.cwd is defined', testErrorCwd, execa, errorProperties);103test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);
added:test/arguments/escape.js+52 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testResultCommand = async (t, expected, ...args) => {8 const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));9 t.is(failCommand, `fail.js${expected}`);1011 const {command} = await execa('noop.js', args);12 t.is(command, `noop.js${expected}`);13};1415testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;1617test(testResultCommand, ' foo bar', 'foo', 'bar');18test(testResultCommand, ' baz quz', 'baz', 'quz');19test(testResultCommand, '');2021const testEscapedCommand = async (t, expected, args) => {22 const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));23 t.is(failEscapedCommand, `fail.js ${expected}`);2425 const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26 execaSync('fail.js', args);27 });28 t.is(failEscapedCommandSync, `fail.js ${expected}`);2930 const {escapedCommand} = await execa('noop.js', args);31 t.is(escapedCommand, `noop.js ${expected}`);3233 const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);34 t.is(escapedCommandSync, `noop.js ${expected}`);35};3637testEscapedCommand.title = (message, expected) => `result.escapedCommand is: ${JSON.stringify(expected)}`;3839test(testEscapedCommand, 'foo bar', ['foo', 'bar']);40test(testEscapedCommand, '"foo bar"', ['foo bar']);41test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);42test(testEscapedCommand, '"*"', ['*']);4344test('allow commands with spaces and no array arguments', async t => {45 const {stdout} = await execa('command with space.js');46 t.is(stdout, '');47});4849test('allow commands with spaces and array arguments', async t => {50 const {stdout} = await execa('command with space.js', ['foo', 'bar']);51 t.is(stdout, 'foo\nbar');52});
added:test/arguments/node.js+249 added
1import {dirname, relative} from 'node:path';2import process from 'node:process';3import {pathToFileURL} from 'node:url';4import test from 'ava';5import getNode from 'get-node';6import {pEvent} from 'p-event';7import {execa, execaSync, execaNode} from '../../index.js';8import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';9import {identity, fullStdio} from '../helpers/stdio.js';10import {foobarString} from '../helpers/input.js';1112process.chdir(FIXTURES_DIR);1314const runWithNodeOption = (file, args, options) => Array.isArray(args)15 ? execa(file, args, {...options, node: true})16 : execa(file, {...options, node: true});17const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18 ? execaSync(file, args, {...options, node: true})19 : execaSync(file, {...options, node: true});20const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2122const testNodeSuccess = async (t, execaMethod) => {23 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);24 t.is(exitCode, 0);25 t.is(stdout, foobarString);26};2728test('execaNode() succeeds', testNodeSuccess, execaNode);29test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);3132test('execaNode() cannot set the "node" option to false', t => {33 t.throws(() => {34 execaNode('empty.js', {node: false});35 }, {message: /The "node" option cannot be false/});36});3738const testDoubleNode = (t, nodePath, execaMethod) => {39 t.throws(() => {40 execaMethod(nodePath, ['noop.js']);41 }, {message: /does not need to be "node"/});42};4344test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);45test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);46test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);47test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);48test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);49test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);5051const getNodePath = async () => {52 const {path} = await getNode(TEST_NODE_VERSION);53 return path;54};5556const TEST_NODE_VERSION = '16.0.0';5758const testNodePath = async (t, execaMethod, mapPath) => {59 const nodePath = mapPath(await getNodePath());60 const {stdout} = await execaMethod('--version', [], {nodePath});61 t.is(stdout, `v${TEST_NODE_VERSION}`);62};6364test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);7071const testNodePathDefault = async (t, execaMethod) => {72 const {stdout} = await execaMethod('--version');73 t.is(stdout, process.version);74};7576test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);7980const testNodePathInvalid = (t, execaMethod) => {81 t.throws(() => {82 execaMethod('noop.js', [], {nodePath: true});83 }, {message: /The "nodePath" option must be a string or a file URL/});84};8586test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);8990const testFormerNodePath = (t, execaMethod) => {91 t.throws(() => {92 execaMethod('noop.js', [], {execPath: process.execPath});93 }, {message: /The "execPath" option has been removed/});94};9596test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99100const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];101102const testChildNodePath = async (t, mapPath) => {103 const nodePath = mapPath(await getNodePath());104 const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath});105 t.true(stdout.includes(TEST_NODE_VERSION));106};107108test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);110111test('The "nodePath" option defaults to the current Node.js binary in the child process', async t => {112 const {stdout} = await execa(...nodePathArguments, {preferLocal: true});113 t.true(stdout.includes(dirname(process.execPath)));114});115116test.serial('The "nodePath" option requires "preferLocal: true" to impact the child process', async t => {117 const nodePath = await getNodePath();118 const {stdout} = await execa(...nodePathArguments, {nodePath});119 t.false(stdout.includes(TEST_NODE_VERSION));120});121122test.serial('The "nodePath" option is relative to "cwd" when used in the child process', async t => {123 const nodePath = await getNodePath();124 const cwd = dirname(dirname(nodePath));125 const relativeExecPath = relative(cwd, nodePath);126 const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath: relativeExecPath, cwd});127 t.true(stdout.includes(TEST_NODE_VERSION));128});129130const testCwdNodePath = async (t, execaMethod) => {131 const nodePath = await getNodePath();132 const cwd = dirname(dirname(nodePath));133 const relativeExecPath = relative(cwd, nodePath);134 const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});135 t.is(stdout, `v${TEST_NODE_VERSION}`);136};137138test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141142const testNodeOptions = async (t, execaMethod) => {143 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144 t.is(stdout, process.version);145};146147test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150151const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(152 'node',153 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],154 {...fullStdio, cwd: FIXTURES_DIR},155);156157const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {158 const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');159 t.is(stdout, foobarString);160 t.is(stdio[3], '');161};162163test('The "nodeOptions" option removes --inspect without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');164test('The "nodeOptions" option removes --inspect without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');165test('The "nodeOptions" option removes --inspect with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');166test('The "nodeOptions" option removes --inspect with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');167test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');168test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');169test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');170test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');171172const testInspectDifferentPort = async (t, execaMethod) => {173 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');174 t.is(stdout, foobarString);175 t.true(stdio[3].includes('Debugger listening'));176};177178test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - execaNode()', testInspectDifferentPort, 'execaNode');179test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - "node" option', testInspectDifferentPort, 'nodeOption');180181const testInspectSamePort = async (t, execaMethod) => {182 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');183 t.is(stdout, foobarString);184 t.true(stdio[3].includes('address already in use'));185};186187test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - execaNode()', testInspectSamePort, 'execaNode');188test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - "node" option', testInspectSamePort, 'nodeOption');189190const testIpc = async (t, execaMethod, options) => {191 const subprocess = execaMethod('send.js', [], options);192 await pEvent(subprocess, 'message');193 subprocess.send(foobarString);194 const {stdout, stdio} = await subprocess;195 t.is(stdout, foobarString);196 t.is(stdio.length, 4);197 t.is(stdio[3], undefined);198};199200test('execaNode() adds an ipc channel', testIpc, execaNode, {});201test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});202test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});203test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});204test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});205test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});206test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});207208test('No ipc channel is added by default', async t => {209 const {stdio} = await t.throwsAsync(execa('node', ['send.js']), {message: /process.send is not a function/});210 t.is(stdio.length, 3);211});212213const testDisableIpc = async (t, execaMethod) => {214 const {failed, message, stdio} = await execaMethod('send.js', [], {ipc: false, reject: false});215 t.true(failed);216 t.true(message.includes('process.send is not a function'));217 t.is(stdio.length, 3);218};219220test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);221test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);222test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);223224const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;225226const testNoIpcSync = (t, node) => {227 t.throws(() => {228 execaSync('node', ['send.js'], {ipc: true, node});229 }, {message: NO_IPC_MESSAGE});230};231232test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);233test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);234235test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {236 t.throws(() => {237 execaSync('send.js', {ipc: true, node: true});238 }, {message: NO_IPC_MESSAGE});239});240241const testNoShell = async (t, execaMethod) => {242 const {failed, message} = await execaMethod('node --version', [], {shell: true, reject: false});243 t.true(failed);244 t.true(message.includes('MODULE_NOT_FOUND'));245};246247test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);248test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);249test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);
added:test/arguments/options.js+130 added
1import {delimiter, join, basename} from 'node:path';2import process from 'node:process';3import {pathToFileURL, fileURLToPath} from 'node:url';4import test from 'ava';5import which from 'which';6import {execa, $, execaSync, execaNode} from '../../index.js';7import {setFixtureDir, FIXTURES_DIR_URL, PATH_KEY} from '../helpers/fixtures-dir.js';8import {identity} from '../helpers/stdio.js';910setFixtureDir();11process.env.FOO = 'foo';1213const isWindows = process.platform === 'win32';14const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1516const getPathWithoutLocalDir = () => {17 const newPath = process.env[PATH_KEY].split(delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(delimiter);18 return {[PATH_KEY]: newPath};19};2021const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;2223test('preferLocal: true', async t => {24 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: getPathWithoutLocalDir()}));25});2627test('preferLocal: false', async t => {28 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});29});3031test('preferLocal: undefined', async t => {32 await t.throwsAsync(execa('ava', ['--version'], {env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});33});3435test('preferLocal: undefined with $', async t => {36 await t.notThrowsAsync($({env: getPathWithoutLocalDir()})`ava --version`);37});3839test('preferLocal: undefined with $.sync', t => {40 t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);41});4243test('localDir option', async t => {44 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';45 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});46 const envPaths = stdout.split(delimiter);47 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));48});4950test('localDir option can be a URL', async t => {51 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';52 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});53 const envPaths = stdout.split(delimiter);54 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));55});5657test('use environment variables by default', async t => {58 const {stdout} = await execa('environment.js');59 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);60});6162test('extend environment variables by default', async t => {63 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});64 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);65});6667test('do not extend environment with `extendEnv: false`', async t => {68 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});69 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);70});7172test('use extend environment with `extendEnv: true` and `shell: true`', async t => {73 process.env.TEST = 'test';74 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';75 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});76 t.is(stdout, 'test');77 delete process.env.TEST;78});7980test('can use `options.shell: true`', async t => {81 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});82 t.is(stdout, 'foo');83});8485const testShellPath = async (t, mapPath) => {86 const shellPath = isWindows ? 'cmd.exe' : 'bash';87 const shell = mapPath(await which(shellPath));88 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});89 t.is(stdout, 'foo');90};9192test('can use `options.shell: string`', testShellPath, identity);93test('can use `options.shell: file URL`', testShellPath, pathToFileURL);9495const testFileUrl = async (t, execaMethod) => {96 const command = new URL('noop.js', FIXTURES_DIR_URL);97 const {stdout} = await execaMethod(command, ['foobar']);98 t.is(stdout, 'foobar');99};100101test('execa()\'s command argument can be a file URL', testFileUrl, execa);102test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);103test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);104105const testInvalidFileUrl = async (t, execaMethod) => {106 const invalidUrl = new URL('https://invalid.com');107 t.throws(() => {108 execaMethod(invalidUrl);109 }, {code: 'ERR_INVALID_URL_SCHEME'});110};111112test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);113test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);114test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);115116const testInvalidCommand = async (t, execaMethod) => {117 t.throws(() => {118 execaMethod(['command', 'arg']);119 }, {message: /First argument must be a string or a file URL/});120};121122test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);123test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);124test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);125126test('use relative path with \'..\' chars', async t => {127 const pathViaParentDir = join('..', basename(fileURLToPath(new URL('../..', import.meta.url))), 'test', 'fixtures', 'noop.js');128 const {stdout} = await execa(pathViaParentDir, ['foo']);129 t.is(stdout, 'foo');130});
added:test/arguments/verbose.js+33 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const normalizeTimestamp = output => output.replaceAll(/\d/g, '0');8const testTimestamp = '[00:00:00.000]';910test('Prints command when "verbose" is true', async t => {11 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'test'], {all: true});12 t.is(stdout, 'test');13 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);14});1516test('Prints command with NODE_DEBUG=execa', async t => {17 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({stdio: 'inherit'}), 'noop.js', 'test'], {all: true, env: {NODE_DEBUG: 'execa'}});18 t.is(stdout, 'test');19 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);20});2122test('Escape verbose command', async t => {23 const {stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'one two', '"'], {all: true});24 t.true(stderr.endsWith('"one two" "\\""'));25});2627test('Verbose option works with inherit', async t => {28 const {all} = await execa('verbose-script.js', {all: true, env: {NODE_DEBUG: 'execa'}});29 t.is(normalizeTimestamp(all), `${testTimestamp} node -e "console.error(\\"one\\")"30one31${testTimestamp} node -e "console.error(\\"two\\")"32two`);33});
added:test/exit/cleanup.js+89 added
1import process from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {pEvent} from 'p-event';5import isRunning from 'is-running';6import {execa} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const isWindows = process.platform === 'win32';1213// When child process exits before parent process14const spawnAndExit = async (t, cleanup, detached) => {15 await t.notThrowsAsync(execa('nested.js', [JSON.stringify({cleanup, detached}), 'noop.js']));16};1718test('spawnAndExit', spawnAndExit, false, false);19test('spawnAndExit cleanup', spawnAndExit, true, false);20test('spawnAndExit detached', spawnAndExit, false, true);21test('spawnAndExit cleanup detached', spawnAndExit, true, true);2223// When parent process exits before child process24const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {25 const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: 'ignore', ipc: true});2627 const pid = await pEvent(subprocess, 'message');28 t.true(Number.isInteger(pid));29 t.true(isRunning(pid));3031 process.kill(subprocess.pid, signal);3233 await t.throwsAsync(subprocess);34 t.false(isRunning(subprocess.pid));3536 if (isKilled) {37 await Promise.race([38 setTimeout(1e4, undefined, {ref: false}),39 pollForProcessExit(pid),40 ]);41 t.is(isRunning(pid), false);42 } else {43 t.is(isRunning(pid), true);44 process.kill(pid, 'SIGKILL');45 }46};4748const pollForProcessExit = async pid => {49 while (isRunning(pid)) {50 // eslint-disable-next-line no-await-in-loop51 await setTimeout(100);52 }53};5455// Without `options.cleanup`:56// - on Windows subprocesses are killed if `options.detached: false`, but not57// if `options.detached: true`58// - on Linux subprocesses are never killed regardless of `options.detached`59// With `options.cleanup`, subprocesses are always killed60// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled61test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);62test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);63test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);64test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);65test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);66test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);67test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);68test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);6970// See #12871test('removes exit handler on exit', async t => {72 // @todo this relies on `signal-exit` internals73 const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;7475 const subprocess = execa('noop.js');76 const listener = exitListeners.at(-1);7778 await subprocess;79 t.false(exitListeners.includes(listener));80});8182test('detach child process', async t => {83 const {stdout} = await execa('detach.js');84 const pid = Number(stdout);85 t.true(Number.isInteger(pid));86 t.true(isRunning(pid));8788 process.kill(pid, 'SIGKILL');89});
added:test/exit/code.js+85 added
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56const isWindows = process.platform === 'win32';78setFixtureDir();910test('exitCode is 0 on success', async t => {11 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);13});1415const testExitCode = async (t, expectedExitCode) => {16 const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(17 execa('exit.js', [`${expectedExitCode}`]),18 );19 t.is(exitCode, expectedExitCode);20 t.is(originalMessage, '');21 t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22 t.is(message, shortMessage);23};2425test('exitCode is 2', testExitCode, 2);26test('exitCode is 3', testExitCode, 3);27test('exitCode is 4', testExitCode, 4);2829if (!isWindows) {30 test('error.signal is SIGINT', async t => {31 const subprocess = execa('forever.js');3233 process.kill(subprocess.pid, 'SIGINT');3435 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36 t.is(signal, 'SIGINT');37 });3839 test('error.signalDescription is defined', async t => {40 const subprocess = execa('forever.js');4142 process.kill(subprocess.pid, 'SIGINT');4344 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45 t.is(signalDescription, 'User interruption with CTRL-C');46 });4748 test('error.signal is SIGTERM', async t => {49 const subprocess = execa('forever.js');5051 process.kill(subprocess.pid, 'SIGTERM');5253 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54 t.is(signal, 'SIGTERM');55 });5657 test('error.signal uses killSignal', async t => {58 const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59 t.is(signal, 'SIGINT');60 });6162 test('exitCode is undefined on signal termination', async t => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6667 const {exitCode} = await t.throwsAsync(subprocess);68 t.is(exitCode, undefined);69 });70}7172test('result.signal is undefined for successful execution', async t => {73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('result.signal is undefined if process failed, but was not killed', async t => {78 const {signal} = await t.throwsAsync(execa('fail.js'));79 t.is(signal, undefined);80});8182test('result.signalDescription is undefined for successful execution', async t => {83 const {signalDescription} = await execa('noop.js');84 t.is(signalDescription, undefined);85});
added:test/exit/kill.js+306 added
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout, setImmediate} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {assertMaxListeners} from '../helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const spawnNoKillable = async (forceKillAfterDelay, options) => {17 const subprocess = execa('no-killable.js', {18 ipc: true,19 forceKillAfterDelay,20 ...options,21 });22 await pEvent(subprocess, 'message');23 return {subprocess};24};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2930test('kill("SIGKILL") should terminate cleanly', async t => {31 const {subprocess} = await spawnNoKillable();3233 subprocess.kill('SIGKILL');3435 const {isTerminated, signal} = await t.throwsAsync(subprocess);36 t.true(isTerminated);37 t.is(signal, 'SIGKILL');38});3940const testInvalidForceKill = async (t, forceKillAfterDelay) => {41 t.throws(() => {42 execa('empty.js', {forceKillAfterDelay});43 }, {instanceOf: TypeError, message: /non-negative integer/});44};4546test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);47test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4849// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).50// Therefore, this feature and those tests must be different on Windows.51if (isWindows) {52 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53 const {subprocess} = await spawnNoKillable(1);54 subprocess.kill();5556 const {isTerminated, signal} = await t.throwsAsync(subprocess);57 t.true(isTerminated);58 t.is(signal, 'SIGTERM');59 });60} else {61 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {62 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);6364 subprocess.kill(killArgument);6566 await setTimeout(6e3);67 t.true(isRunning(subprocess.pid));68 subprocess.kill('SIGKILL');6970 const {isTerminated, signal} = await t.throwsAsync(subprocess);71 t.true(isTerminated);72 t.is(signal, 'SIGKILL');73 };7475 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);76 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');77 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});78 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});7980 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {81 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8283 subprocess.kill(killArgument);8485 const {isTerminated, signal} = await t.throwsAsync(subprocess);86 t.true(isTerminated);87 t.is(signal, 'SIGKILL');88 };8990 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);91 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);92 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);93 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');94 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});95 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});96 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));97 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});9899 test('`forceKillAfterDelay` works with the "signal" option', async t => {100 const abortController = new AbortController();101 const subprocess = spawnNoKillableSimple({signal: abortController.signal});102 await once(subprocess, 'spawn');103 abortController.abort();104 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);105 t.true(isTerminated);106 t.is(signal, 'SIGKILL');107 t.true(isCanceled);108 });109110 test('`forceKillAfterDelay` works with the "timeout" option', async t => {111 const subprocess = spawnNoKillableSimple({timeout: 1});112 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);113 t.true(isTerminated);114 t.is(signal, 'SIGKILL');115 t.true(timedOut);116 });117118 test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {119 const subprocess = spawnNoKillableOutput({maxBuffer: 1});120 const {isTerminated, signal} = await t.throwsAsync(subprocess);121 t.true(isTerminated);122 t.is(signal, 'SIGKILL');123 });124125 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {126 const checkMaxListeners = assertMaxListeners(t);127128 const subprocess = spawnNoKillableSimple();129 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {130 subprocess.kill();131 }132133 const {isTerminated, signal} = await t.throwsAsync(subprocess);134 t.true(isTerminated);135 t.is(signal, 'SIGKILL');136137 checkMaxListeners();138 });139140 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {141 const subprocess = spawnNoKillableSimple();142 subprocess.kill();143 subprocess.kill();144145 const {isTerminated, signal} = await t.throwsAsync(subprocess);146 t.true(isTerminated);147 t.is(signal, 'SIGKILL');148 });149}150151test('Can call `.kill()` multiple times', async t => {152 const subprocess = execa('forever.js');153 subprocess.kill();154 subprocess.kill();155156 const {isTerminated, signal} = await t.throwsAsync(subprocess);157 t.true(isTerminated);158 t.is(signal, 'SIGTERM');159});160161test('execa() returns a promise with kill()', async t => {162 const subprocess = execa('noop.js', ['foo']);163 t.is(typeof subprocess.kill, 'function');164 await subprocess;165});166167const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {168 const subprocess = execa('empty.js');169 const message = secondKillArgument instanceof Error || secondKillArgument === undefined170 ? /error instance or a signal name/171 : /second argument is optional/;172 t.throws(() => {173 subprocess.kill(killArgument, secondKillArgument);174 }, {message});175 await subprocess;176};177178test('Cannot call .kill(null)', testInvalidKillArgument, null);179test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);180test('Cannot call .kill(true)', testInvalidKillArgument, true);181test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});182test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);183test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);184test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);185test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));186187test('.kill(error) propagates error', async t => {188 const subprocess = execa('forever.js');189 const originalMessage = 'test';190 const error = new Error(originalMessage);191 t.true(subprocess.kill(error));192 t.is(await t.throwsAsync(subprocess), error);193 t.is(error.exitCode, undefined);194 t.is(error.signal, 'SIGTERM');195 t.true(error.isTerminated);196 t.is(error.originalMessage, originalMessage);197 t.true(error.message.includes(originalMessage));198 t.true(error.message.includes('was killed with SIGTERM'));199 t.true(error.stack.includes(import.meta.url));200});201202test('.kill(error) uses killSignal', async t => {203 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});204 const error = new Error('test');205 subprocess.kill(error);206 t.is(await t.throwsAsync(subprocess), error);207 t.is(error.signal, 'SIGINT');208});209210test('.kill(signal, error) uses signal', async t => {211 const subprocess = execa('forever.js');212 const error = new Error('test');213 subprocess.kill('SIGINT', error);214 t.is(await t.throwsAsync(subprocess), error);215 t.is(error.signal, 'SIGINT');216});217218test('.kill(error) is a noop if process already exited', async t => {219 const subprocess = execa('empty.js');220 await subprocess;221 t.false(isRunning(subprocess.pid));222 t.false(subprocess.kill(new Error('test')));223});224225test('.kill(error) terminates but does not change the error if the process already errored but did not exit yet', async t => {226 const subprocess = execa('forever.js');227 const error = new Error('first');228 subprocess.stdout.destroy(error);229 await setImmediate();230 const secondError = new Error('second');231 t.true(subprocess.kill(secondError));232 t.is(await t.throwsAsync(subprocess), error);233 t.is(error.exitCode, undefined);234 t.is(error.signal, 'SIGTERM');235 t.true(error.isTerminated);236 t.false(error.message.includes(secondError.message));237});238239test('.kill(error) twice in a row', async t => {240 const subprocess = execa('forever.js');241 const error = new Error('first');242 subprocess.kill(error);243 const secondError = new Error('second');244 subprocess.kill(secondError);245 t.is(await t.throwsAsync(subprocess), error);246 t.false(error.message.includes(secondError.message));247});248249test('.kill(error) does not emit the "error" event', async t => {250 const subprocess = execa('forever.js');251 const error = new Error('test');252 subprocess.kill(error);253 t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);254});255256test('child process errors are handled before spawn', async t => {257 const subprocess = execa('forever.js');258 const error = new Error('test');259 subprocess.emit('error', error);260 subprocess.kill();261 const thrownError = await t.throwsAsync(subprocess);262 t.is(thrownError, error);263 t.is(thrownError.exitCode, undefined);264 t.is(thrownError.signal, undefined);265 t.false(thrownError.isTerminated);266});267268test('child process errors are handled after spawn', async t => {269 const subprocess = execa('forever.js');270 await once(subprocess, 'spawn');271 const error = new Error('test');272 subprocess.emit('error', error);273 subprocess.kill();274 const thrownError = await t.throwsAsync(subprocess);275 t.is(thrownError, error);276 t.is(thrownError.exitCode, undefined);277 t.is(thrownError.signal, 'SIGTERM');278 t.true(thrownError.isTerminated);279});280281test('child process double errors are handled after spawn', async t => {282 const abortController = new AbortController();283 const subprocess = execa('forever.js', {signal: abortController.signal});284 await once(subprocess, 'spawn');285 const error = new Error('test');286 subprocess.emit('error', error);287 await setImmediate();288 abortController.abort();289 const thrownError = await t.throwsAsync(subprocess);290 t.is(thrownError, error);291 t.is(thrownError.exitCode, undefined);292 t.is(thrownError.signal, 'SIGTERM');293 t.true(thrownError.isTerminated);294});295296test('child process errors use killSignal', async t => {297 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});298 await once(subprocess, 'spawn');299 const error = new Error('test');300 subprocess.emit('error', error);301 subprocess.kill();302 const thrownError = await t.throwsAsync(subprocess);303 t.is(thrownError, error);304 t.true(thrownError.isTerminated);305 t.is(thrownError.signal, 'SIGINT');306});
added:test/exit/signal.js+78 added
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78test('result.isCanceled is false when abort isn\'t called (success)', async t => {9 const {isCanceled} = await execa('noop.js');10 t.false(isCanceled);11});1213test('result.isCanceled is false when abort isn\'t called (failure)', async t => {14 const {isCanceled} = await t.throwsAsync(execa('fail.js'));15 t.false(isCanceled);16});1718test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {19 const {isCanceled} = execaSync('noop.js');20 t.false(isCanceled);21});2223test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {24 const {isCanceled} = t.throws(() => {25 execaSync('fail.js');26 });27 t.false(isCanceled);28});2930test('error.isCanceled is true when abort is used', async t => {31 const abortController = new AbortController();32 const subprocess = execa('noop.js', {signal: abortController.signal});33 abortController.abort();34 const {isCanceled} = await t.throwsAsync(subprocess);35 t.true(isCanceled);36});3738test('error.isCanceled is false when kill method is used', async t => {39 const abortController = new AbortController();40 const subprocess = execa('noop.js', {signal: abortController.signal});41 subprocess.kill();42 const {isCanceled} = await t.throwsAsync(subprocess);43 t.false(isCanceled);44});4546test('calling abort is considered a signal termination', async t => {47 const abortController = new AbortController();48 const subprocess = execa('forever.js', {signal: abortController.signal});49 await once(subprocess, 'spawn');50 abortController.abort();51 const {isTerminated, signal} = await t.throwsAsync(subprocess);52 t.true(isTerminated);53 t.is(signal, 'SIGTERM');54});5556test('calling abort throws an error with message "Command was canceled"', async t => {57 const abortController = new AbortController();58 const subprocess = execa('noop.js', {signal: abortController.signal});59 abortController.abort();60 await t.throwsAsync(subprocess, {message: /Command was canceled/});61});6263test('calling abort twice should show the same behaviour as calling it once', async t => {64 const abortController = new AbortController();65 const subprocess = execa('noop.js', {signal: abortController.signal});66 abortController.abort();67 abortController.abort();68 const {isCanceled} = await t.throwsAsync(subprocess);69 t.true(isCanceled);70});7172test('calling abort on a successfully completed process does not make result.isCanceled true', async t => {73 const abortController = new AbortController();74 const subprocess = execa('noop.js', {signal: abortController.signal});75 const result = await subprocess;76 abortController.abort();77 t.false(result.isCanceled);78});
added:test/exit/timeout.js+75 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('timeout kills the process if it times out', async t => {8 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));9 t.true(isTerminated);10 t.is(signal, 'SIGTERM');11 t.true(timedOut);12 t.is(originalMessage, '');13 t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');14 t.is(message, shortMessage);15});1617test('timeout kills the process if it times out, in sync mode', async t => {18 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19 execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});20 });21 t.true(isTerminated);22 t.is(signal, 'SIGTERM');23 t.true(timedOut);24 t.is(originalMessage, 'spawnSync node ETIMEDOUT');25 t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);26 t.is(message, shortMessage);27});2829test('timeout does not kill the process if it does not time out', async t => {30 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});31 t.false(timedOut);32});3334test('timeout uses killSignal', async t => {35 const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));36 t.true(isTerminated);37 t.is(signal, 'SIGINT');38 t.true(timedOut);39});4041const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;4243const testTimeoutValidation = (t, timeout, execaMethod) => {44 t.throws(() => {45 execaMethod('empty.js', {timeout});46 }, {message: INVALID_TIMEOUT_REGEXP});47};4849test('timeout must not be negative', testTimeoutValidation, -1, execa);50test('timeout must be an integer', testTimeoutValidation, false, execa);51test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);5354test('timedOut is false if timeout is undefined', async t => {55 const {timedOut} = await execa('noop.js');56 t.false(timedOut);57});5859test('timedOut is false if timeout is 0', async t => {60 const {timedOut} = await execa('noop.js', {timeout: 0});61 t.false(timedOut);62});6364test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {65 const {timedOut} = execaSync('noop.js');66 t.false(timedOut);67});6869test('timedOut is true if the timeout happened after a different error occurred', async t => {70 const childProcess = execa('forever.js', {timeout: 1e3});71 const error = new Error('test');72 childProcess.emit('error', error);73 t.is(await t.throwsAsync(childProcess), error);74 t.true(error.timedOut);75});
added:test/return/clone.js+150 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';56setFixtureDir();78const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {9 const childProcess = execa('empty.js');10 childProcess.emit('error', error);11 const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);12 t.is(originalMessage, expectedOriginalMessage);13 t.true(shortMessage.includes(expectedOriginalMessage));14 t.is(message, shortMessage);15};1617test('error instance can be null', testUnusualError, null);18test('error instance can be false', testUnusualError, false);19test('error instance can be a string', testUnusualError, 'test');20test('error instance can be a number', testUnusualError, 0);21test('error instance can be a BigInt', testUnusualError, 0n);22test('error instance can be a symbol', testUnusualError, Symbol('test'));23test('error instance can be a function', testUnusualError, () => {});24test('error instance can be an array', testUnusualError, ['test', 'test']);25// eslint-disable-next-line unicorn/error-message26test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27test('error instance can be undefined', testUnusualError, undefined, '');2829test('error instance can be a plain object', async t => {30 const childProcess = execa('empty.js');31 childProcess.emit('error', {message: foobarString});32 await t.throwsAsync(childProcess, {message: new RegExp(foobarString)});33});3435const runAndFail = (t, fixtureName, argument, error) => {36 const childProcess = execa(fixtureName, [argument]);37 childProcess.emit('error', error);38 return t.throwsAsync(childProcess);39};4041const runAndClone = async (t, initialError) => {42 const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43 t.is(previousError, initialError);4445 return runAndFail(t, 'empty.js', 'bar', previousError);46};4748const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49 const fixtureName = 'empty.js';50 const firstArgument = 'foo';5152 const previousArgument = await getPreviousArgument(t, fixtureName);53 const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);54 const error = await runAndFail(t, fixtureName, argument, previousError);55 const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;5657 t.not(error, previousError);58 t.is(error.command, `${fixtureName} ${argument}`);59 t.is(error.message, message);60 t.true(error.stack.includes(message));61 t.is(error.stack, previousError.stack.replace(firstArgument, argument));62 t.is(error.shortMessage, message);63 t.is(error.originalMessage, foobarString);64};6566test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68test('error string can be shared', testErrorCopy, () => foobarString);69test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');7172const testErrorCopyProperty = async (t, propertyName, isCopied) => {73 const propertyValue = 'test';74 const initialError = new Error(foobarString);75 initialError[propertyName] = propertyValue;7677 const error = await runAndClone(t, initialError);78 t.is(error[propertyName] === propertyValue, isCopied);79};8081test('error.code can be copied', testErrorCopyProperty, 'code', true);82test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84test('error.path can be copied', testErrorCopyProperty, 'path', true);85test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86test('error.address can be copied', testErrorCopyProperty, 'address', true);87test('error.port can be copied', testErrorCopyProperty, 'port', true);88test('error.info can be copied', testErrorCopyProperty, 'info', true);89test('error.other cannot be copied', testErrorCopyProperty, 'other', false);9091test('error.name can be copied', async t => {92 const initialError = new TypeError('test');93 const error = await runAndClone(t, initialError);94 t.deepEqual(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(initialError), 'name'), Object.getOwnPropertyDescriptor(error, 'name'));95});9697test('error.cause can be copied', async t => {98 const initialError = new Error('test', {cause: new Error('innerTest')});99 const error = await runAndClone(t, initialError);100 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'cause'), Object.getOwnPropertyDescriptor(error, 'cause'));101});102103test('error.errors can be copied', async t => {104 const initialError = new AggregateError([], 'test');105 const error = await runAndClone(t, initialError);106 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'errors'), Object.getOwnPropertyDescriptor(error, 'errors'));107});108109test('error.stack is set even if memoized', async t => {110 const message = 'test';111 const error = new Error(message);112 t.is(typeof error.stack, 'string');113114 const newMessage = 'newTest';115 error.message = newMessage;116 t.false(error.stack.includes(newMessage));117 error.message = message;118119 const childProcess = execa('empty.js');120 childProcess.emit('error', error);121 t.is(await t.throwsAsync(childProcess), error);122 t.is(error.message, `Command failed: empty.js\n${message}`);123 t.true(error.stack.startsWith(`Error: ${error.message}`));124});125126test('error.stack is set even if memoized with an unusual error.name', async t => {127 const childProcess = execa('empty.js');128 childProcess.stdin.destroy();129 const error = await t.throwsAsync(childProcess);130 t.is(error.message, 'Command failed with ERR_STREAM_PREMATURE_CLOSE: empty.js\nPremature close');131 t.true(error.stack.startsWith(`Error [ERR_STREAM_PREMATURE_CLOSE]: ${error.message}`));132});133134test('Cloned errors keep the stack trace', async t => {135 const message = 'test';136 const error = new Error(message);137 const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');138139 const childProcess = execa('empty.js');140 childProcess.emit('error', error);141 t.is(await t.throwsAsync(childProcess), error);142143 const secondChildProcess = execa('empty.js');144 secondChildProcess.emit('error', error);145 const secondError = await t.throwsAsync(secondChildProcess);146 t.not(secondError, error);147 t.is(secondError.message, `Command failed: empty.js\n${message}`);148 t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);149});150
added:test/return/early-error.js+70 added
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const isWindows = process.platform === 'win32';9const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1011test('execaSync() throws error if ENOENT', t => {12 t.throws(() => {13 execaSync('foo');14 }, {message: ENOENT_REGEXP});15});1617const testEarlyErrorShape = async (t, reject) => {18 const subprocess = execa('', {reject});19 t.notThrows(() => {20 subprocess.catch(() => {});21 subprocess.unref();22 subprocess.on('error', () => {});23 });24};2526test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);27test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);2829test('child_process.spawn() early errors are propagated', async t => {30 const {failed} = await t.throwsAsync(execa(''));31 t.true(failed);32});3334test('child_process.spawn() early errors are returned', async t => {35 const {failed} = await execa('', {reject: false});36 t.true(failed);37});3839test('child_process.spawnSync() early errors are propagated with a correct shape', t => {40 const {failed} = t.throws(() => {41 execaSync('');42 });43 t.true(failed);44});4546test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {47 const {failed} = execaSync('', {reject: false});48 t.true(failed);49});5051if (!isWindows) {52 test('execa() rejects if running non-executable', async t => {53 await t.throwsAsync(execa('non-executable.js'));54 });5556 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {57 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});58 });5960 test('write to fast-exit process', async t => {61 // Try-catch here is necessary, because this test is not 100% accurate62 // Sometimes process can manage to accept input before exiting63 try {64 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});65 t.pass();66 } catch (error) {67 t.is(error.code, 'EPIPE');68 }69 });70}
added:test/return/error.js+186 added
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio, getStdio} from '../helpers/stdio.js';6import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';78const isWindows = process.platform === 'win32';910setFixtureDir();1112test('Return value properties are not missing and are ordered', async t => {13 const result = await execa('empty.js', {...fullStdio, all: true});14 t.deepEqual(Reflect.ownKeys(result), [15 'command',16 'escapedCommand',17 'cwd',18 'failed',19 'timedOut',20 'isCanceled',21 'isTerminated',22 'exitCode',23 'stdout',24 'stderr',25 'all',26 'stdio',27 'pipedFrom',28 ]);29});3031test('Error properties are not missing and are ordered', async t => {32 const error = await t.throwsAsync(execa('fail.js', {...fullStdio, all: true}));33 t.deepEqual(Reflect.ownKeys(error), [34 'stack',35 'message',36 'shortMessage',37 'originalMessage',38 'command',39 'escapedCommand',40 'cwd',41 'failed',42 'timedOut',43 'isCanceled',44 'isTerminated',45 'exitCode',46 'signal',47 'signalDescription',48 'stdout',49 'stderr',50 'all',51 'stdio',52 'pipedFrom',53 ]);54});5556test('error.message contains the command', async t => {57 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});58});5960const testStdioMessage = async (t, encoding, all, objectMode) => {61 const {message} = await t.throwsAsync(execa('echo-fail.js', {...getStdio(1, noopGenerator(objectMode), 4), encoding, all}));62 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';63 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));64};6566test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);67test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);68test('error.message contains all if available', testStdioMessage, 'utf8', true, false);69test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);70test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);71test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);72test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);73test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);7475const testPartialIgnoreMessage = async (t, index, stdioOption, output) => {76 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(index, stdioOption, 4)));77 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));78};7980test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');81test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');82test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');83test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');8485const testFullIgnoreMessage = async (t, options, resultProperty) => {86 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));87 t.false(message.includes('stderr'));88 t.false(message.includes('stdout'));89 t.false(message.includes('fd3'));90};9192test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');93test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');9495const testErrorMessageConsistent = async (t, stdout) => {96 const {message} = await t.throwsAsync(execa('noop-both-fail.js', [stdout, 'stderr']));97 t.true(message.endsWith(`noop-both-fail.js ${stdout} stderr\n\nstderr\n\nstdout`));98};99100test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');101test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');102103test('Original error.message is kept', async t => {104 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));105 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');106});107108test('failed is false on success', async t => {109 const {failed} = await execa('noop.js', ['foo']);110 t.false(failed);111});112113test('failed is true on failure', async t => {114 const {failed} = await t.throwsAsync(execa('fail.js'));115 t.true(failed);116});117118test('error.isTerminated is true if process was killed directly', async t => {119 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});120121 subprocess.kill();122123 const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});124 t.true(isTerminated);125 t.is(signal, 'SIGINT');126 t.is(originalMessage, '');127 t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');128 t.is(message, shortMessage);129});130131test('error.isTerminated is true if process was killed indirectly', async t => {132 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});133134 process.kill(subprocess.pid, 'SIGINT');135136 // `process.kill()` is emulated by Node.js on Windows137 if (isWindows) {138 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});139 t.is(isTerminated, false);140 t.is(signal, undefined);141 } else {142 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});143 t.is(isTerminated, true);144 t.is(signal, 'SIGINT');145 }146});147148test('result.isTerminated is false if not killed', async t => {149 const {isTerminated} = await execa('noop.js');150 t.false(isTerminated);151});152153test('result.isTerminated is false if not killed and childProcess.kill() was called', async t => {154 const subprocess = execa('noop.js');155 subprocess.kill(0);156 t.true(subprocess.killed);157 const {isTerminated} = await subprocess;158 t.false(isTerminated);159});160161test('result.isTerminated is false if not killed, in sync mode', t => {162 const {isTerminated} = execaSync('noop.js');163 t.false(isTerminated);164});165166test('result.isTerminated is false on process error', async t => {167 const {isTerminated} = await t.throwsAsync(execa('wrong command'));168 t.false(isTerminated);169});170171test('result.isTerminated is false on process error, in sync mode', t => {172 const {isTerminated} = t.throws(() => {173 execaSync('wrong command');174 });175 t.false(isTerminated);176});177178test('error.code is undefined on success', async t => {179 const {code} = await execa('noop.js');180 t.is(code, undefined);181});182183test('error.code is defined on failure if applicable', async t => {184 const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));185 t.is(code, 'ERR_INVALID_ARG_TYPE');186});
added:test/return/output.js+142 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio, getStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';67setFixtureDir();89const testOutput = async (t, index, execaMethod) => {10 const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar'], fullStdio);11 t.is(stdio[index], 'foobar');1213 if (index === 1) {14 t.is(stdio[index], stdout);15 } else if (index === 2) {16 t.is(stdio[index], stderr);17 }18};1920test('can return stdout', testOutput, 1, execa);21test('can return stderr', testOutput, 2, execa);22test('can return output stdio[*]', testOutput, 3, execa);23test('can return stdout - sync', testOutput, 1, execaSync);24test('can return stderr - sync', testOutput, 2, execaSync);25test('can return output stdio[*] - sync', testOutput, 3, execaSync);2627const testNoStdin = async (t, execaMethod) => {28 const {stdio} = await execaMethod('noop.js', ['foobar']);29 t.is(stdio[0], undefined);30};3132test('cannot return stdin', testNoStdin, execa);33test('cannot return stdin - sync', testNoStdin, execaSync);3435test('cannot return input stdio[*]', async t => {36 const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [['foobar']]));37 t.is(stdio[3], undefined);38});3940test('do not try to consume streams twice', async t => {41 const subprocess = execa('noop.js', ['foo']);42 const {stdout} = await subprocess;43 const {stdout: stdout2} = await subprocess;44 t.is(stdout, 'foo');45 t.is(stdout2, 'foo');46});4748const testEmptyErrorStdio = async (t, execaMethod) => {49 const {failed, stdout, stderr, stdio} = await execaMethod('fail.js', {reject: false});50 t.true(failed);51 t.is(stdout, '');52 t.is(stderr, '');53 t.deepEqual(stdio, [undefined, '', '']);54};5556test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);57test('empty error.stdout/stderr/stdio - sync', testEmptyErrorStdio, execaSync);5859const testUndefinedErrorStdio = async (t, execaMethod) => {60 const {stdout, stderr, stdio} = await execaMethod('empty.js', {stdio: 'ignore'});61 t.is(stdout, undefined);62 t.is(stderr, undefined);63 t.deepEqual(stdio, [undefined, undefined, undefined]);64};6566test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);67test('undefined error.stdout/stderr/stdio - sync', testUndefinedErrorStdio, execaSync);6869const testEmptyAll = async (t, options, expectedValue) => {70 const {all} = await t.throwsAsync(execa('fail.js', options));71 t.is(all, expectedValue);72};7374test('empty error.all', testEmptyAll, {all: true}, '');75test('undefined error.all', testEmptyAll, {}, undefined);76test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined);7778test('empty error.stdio[0] even with input', async t => {79 const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));80 t.is(stdio[0], undefined);81});8283// `error.code` is OS-specific here84const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);8586test('stdout/stderr/stdio on process spawning errors', async t => {87 const {code, stdout, stderr, stdio} = await t.throwsAsync(execa('empty.js', {uid: -1}));88 t.true(SPAWN_ERROR_CODES.has(code));89 t.is(stdout, undefined);90 t.is(stderr, undefined);91 t.deepEqual(stdio, [undefined, undefined, undefined]);92});9394test('stdout/stderr/all/stdio on process spawning errors - sync', t => {95 const {code, stdout, stderr, stdio} = t.throws(() => {96 execaSync('empty.js', {uid: -1});97 });98 t.true(SPAWN_ERROR_CODES.has(code));99 t.is(stdout, undefined);100 t.is(stderr, undefined);101 t.deepEqual(stdio, [undefined, undefined, undefined]);102});103104const testErrorOutput = async (t, execaMethod) => {105 const {failed, stdout, stderr, stdio} = await execaMethod('echo-fail.js', {...fullStdio, reject: false});106 t.true(failed);107 t.is(stdout, 'stdout');108 t.is(stderr, 'stderr');109 t.deepEqual(stdio, [undefined, 'stdout', 'stderr', 'fd3']);110};111112test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);113test('error.stdout/stderr/stdio is defined - sync', testErrorOutput, execaSync);114115const testStripFinalNewline = async (t, index, stripFinalNewline, execaMethod) => {116 const {stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar\n'], {...fullStdio, stripFinalNewline});117 t.is(stdio[index], `foobar${stripFinalNewline === false ? '\n' : ''}`);118};119120test('stripFinalNewline: undefined with stdout', testStripFinalNewline, 1, undefined, execa);121test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, execa);122test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);123test('stripFinalNewline: undefined with stderr', testStripFinalNewline, 2, undefined, execa);124test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, execa);125test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);126test('stripFinalNewline: undefined with stdio[*]', testStripFinalNewline, 3, undefined, execa);127test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, execa);128test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);129test('stripFinalNewline: undefined with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);130test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, true, execaSync);131test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);132test('stripFinalNewline: undefined with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);133test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, true, execaSync);134test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);135test('stripFinalNewline: undefined with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);136test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, true, execaSync);137test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);138139test('stripFinalNewline is not used in objectMode', async t => {140 const {stdout} = await execa('noop-fd.js', ['1', 'foobar\n'], {stripFinalNewline: true, stdout: noopGenerator(true)});141 t.deepEqual(stdout, ['foobar\n']);142});
deleted:test/stdio/array.js-275 removed
1import {readFile, writeFile, rm} from 'node:fs/promises';2import process from 'node:process';3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const testEmptyArray = (t, index, optionName, execaMethod) => {12 t.throws(() => {13 execaMethod('empty.js', getStdio(index, []));14 }, {message: `The \`${optionName}\` option must not be an empty array.`});15};1617test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);18test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);19test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);20test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);21test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);22test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);23test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);24test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2526const testNoPipeOption = async (t, stdioOption, index) => {27 const childProcess = execa('empty.js', getStdio(index, stdioOption));28 t.is(childProcess.stdio[index], null);29 await childProcess;30};3132test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);33test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);34test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);35test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);36test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);37test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);38test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);39test('stdin can be 0', testNoPipeOption, 0, 0);40test('stdin can be [0]', testNoPipeOption, [0], 0);41test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);42test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);43test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);44test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);45test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);46test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);47test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);48test('stdout can be 1', testNoPipeOption, 1, 1);49test('stdout can be [1]', testNoPipeOption, [1], 1);50test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);51test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);52test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);53test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);54test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);55test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);56test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);57test('stderr can be 2', testNoPipeOption, 2, 2);58test('stderr can be [2]', testNoPipeOption, [2], 2);59test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);60test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);61test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);62test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);63test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);64test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);65test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);66test('stdio[*] can be 3', testNoPipeOption, 3, 3);67test('stdio[*] can be [3]', testNoPipeOption, [3], 3);6869const testInvalidArrayValue = (t, invalidStdio, index, execaMethod) => {70 t.throws(() => {71 execaMethod('empty.js', getStdio(index, ['pipe', invalidStdio]));72 }, {message: /must not include/});73};7475test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);76test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);77test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);78test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);79test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);80test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);81test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);82test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);83test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);84test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);85test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);86test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);87test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);88test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);89test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);90test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);9192const testInputOutput = (t, stdioOption, execaMethod) => {93 t.throws(() => {94 execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));95 }, {message: /readable and writable/});96};9798test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);99test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);100test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);101test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);102test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);103test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);104test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);105test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);106test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);107test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);108109const testAmbiguousDirection = async (t, execaMethod) => {110 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];111 await execaMethod('noop-fd.js', ['3', 'foobar'], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));112 t.deepEqual(113 await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]),114 ['foobar', 'foobar'],115 );116 await Promise.all([rm(filePathOne), rm(filePathTwo)]);117};118119test('stdio[*] default direction is output', testAmbiguousDirection, execa);120test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);121122const testAmbiguousMultiple = async (t, index) => {123 const filePath = tempfile();124 await writeFile(filePath, 'foobar');125 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, ['foo', 'bar']]));126 t.is(stdout, 'foobarfoobar');127 await rm(filePath);128};129130test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);131test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);132133const testRedirect = async (t, stdioOption, index, isInput) => {134 const {fixtureName, ...options} = isInput135 ? {fixtureName: 'stdin-fd.js', input: 'foobar'}136 : {fixtureName: 'noop-fd.js'};137 const {stdio} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), `${index}`, fixtureName, 'foobar'], options);138 const resultIndex = isStderrDescriptor(stdioOption) ? 2 : 1;139 t.is(stdio[resultIndex], 'foobar');140};141142const isStderrDescriptor = stdioOption => stdioOption === 2143 || stdioOption === 'stderr'144 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));145146test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);147test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);148test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);149test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);150test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);151test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);152test('stdout can be 2', testRedirect, 2, 1, false);153test('stdout can be [2]', testRedirect, [2], 1, false);154test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);155test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);156test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);157test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);158test('stderr can be 1', testRedirect, 1, 2, false);159test('stderr can be [1]', testRedirect, [1], 2, false);160test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);161test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);162test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);163test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);164test('stdio[*] can be 1', testRedirect, 1, 3, false);165test('stdio[*] can be [1]', testRedirect, [1], 3, false);166test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);167test('stdio[*] can be 2', testRedirect, 2, 3, false);168test('stdio[*] can be [2]', testRedirect, [2], 3, false);169test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);170test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);171test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);172test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);173test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);174test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);175test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);176177const testInheritStdin = async (t, stdin) => {178 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});179 t.is(stdout, 'foobarfoobar');180};181182test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe']);183test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe']);184185const testInheritStdout = async (t, stdout) => {186 const result = await execa('nested-multiple-stdout.js', [JSON.stringify(stdout)]);187 t.is(result.stdout, 'foobar');188 t.is(result.stderr, 'nested foobar');189};190191test('stdout can be ["inherit", "pipe"]', testInheritStdout, ['inherit', 'pipe']);192test('stdout can be [1, "pipe"]', testInheritStdout, [1, 'pipe']);193194const testInheritStderr = async (t, stderr) => {195 const result = await execa('nested-multiple-stderr.js', [JSON.stringify(stderr)]);196 t.is(result.stdout, 'nested foobar');197 t.is(result.stderr, 'foobar');198};199200test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);201test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);202203const testOverflowStream = async (t, index, stdioOption) => {204 const {stdout} = await execa('nested.js', [JSON.stringify(getStdio(index, stdioOption)), 'empty.js'], fullStdio);205 t.is(stdout, '');206};207208if (process.platform === 'linux') {209 test('stdin can use 4+', testOverflowStream, 0, 4);210 test('stdin can use [4+]', testOverflowStream, 0, [4]);211 test('stdout can use 4+', testOverflowStream, 1, 4);212 test('stdout can use [4+]', testOverflowStream, 1, [4]);213 test('stderr can use 4+', testOverflowStream, 2, 4);214 test('stderr can use [4+]', testOverflowStream, 2, [4]);215 test('stdio[*] can use 4+', testOverflowStream, 3, 4);216 test('stdio[*] can use [4+]', testOverflowStream, 3, [4]);217}218219test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');220test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);221222const testOverflowStreamArray = (t, index, stdioOption) => {223 t.throws(() => {224 execa('empty.js', getStdio(index, stdioOption));225 }, {message: /no such standard stream/});226};227228test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);229test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);230test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);231test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);232test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);233234const testOverlapped = async (t, index) => {235 const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));236 t.is(stdout, 'foobar');237};238239test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);240test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);241test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);242test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);243244const testDestroyStandard = async (t, index) => {245 const childProcess = execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), timeout: 1});246 await t.throwsAsync(childProcess, {message: /timed out/});247 t.false(STANDARD_STREAMS[index].destroyed);248};249250test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);251test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);252test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);253254const testDestroyStandardSpawn = async (t, index) => {255 await t.throwsAsync(execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), uid: -1}));256 t.false(STANDARD_STREAMS[index].destroyed);257};258259test('Does not destroy process.stdin on spawn process errors', testDestroyStandardSpawn, 0);260test('Does not destroy process.stdout on spawn process errors', testDestroyStandardSpawn, 1);261test('Does not destroy process.stderr on spawn process errors', testDestroyStandardSpawn, 2);262263const testDestroyStandardStream = async (t, index) => {264 const childProcess = execa('forever.js', getStdio(index, [STANDARD_STREAMS[index], 'pipe']));265 const error = new Error('test');266 childProcess.stdio[index].destroy(error);267 childProcess.kill();268 const thrownError = await t.throwsAsync(childProcess);269 t.is(thrownError, error);270 t.false(STANDARD_STREAMS[index].destroyed);271};272273test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);274test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);275test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);
added:test/stdio/direction.js+50 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import process from 'node:process';3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {getStdio} from '../helpers/stdio.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const testInputOutput = (t, stdioOption, execaMethod) => {12 t.throws(() => {13 execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));14 }, {message: /readable and writable/});15};1617test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);18test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);19test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);20test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);21test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);22test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);23test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);24test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);25test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);26test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);2728const testAmbiguousDirection = async (t, execaMethod) => {29 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];30 await execaMethod('noop-fd.js', ['3', 'foobar'], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));31 t.deepEqual(32 await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]),33 ['foobar', 'foobar'],34 );35 await Promise.all([rm(filePathOne), rm(filePathTwo)]);36};3738test('stdio[*] default direction is output', testAmbiguousDirection, execa);39test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);4041const testAmbiguousMultiple = async (t, index) => {42 const filePath = tempfile();43 await writeFile(filePath, 'foobar');44 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, ['foo', 'bar']]));45 t.is(stdout, 'foobarfoobar');46 await rm(filePath);47};4849test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);50test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);
added:test/stdio/encoding-end.js+196 added
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import process from 'node:process';4import {promisify} from 'node:util';5import test from 'ava';6import getStream, {getStreamAsBuffer} from 'get-stream';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9import {fullStdio} from '../helpers/stdio.js';10import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';11import {foobarObject} from '../helpers/input.js';1213const pExec = promisify(exec);1415setFixtureDir();1617const checkEncoding = async (t, encoding, index, execaMethod) => {18 const {stdio} = await execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding});19 compareValues(t, stdio[index], encoding);2021 if (execaMethod !== execaSync) {22 const childProcess = execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding, buffer: false});23 const getStreamMethod = encoding === 'buffer' ? getStreamAsBuffer : getStream;24 const result = await getStreamMethod(childProcess.stdio[index]);25 compareValues(t, result, encoding);26 await childProcess;27 }2829 if (index === 3) {30 return;31 }3233 const {stdout, stderr} = await pExec(`node noop-fd.js ${index} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});34 compareValues(t, index === 1 ? stdout : stderr, encoding);35};3637const compareValues = (t, value, encoding) => {38 if (encoding === 'buffer') {39 t.true(ArrayBuffer.isView(value));40 t.true(BUFFER_TO_ENCODE.equals(value));41 } else {42 t.is(value, BUFFER_TO_ENCODE.toString(encoding));43 }44};4546// This string gives different outputs with each encoding type47const STRING_TO_ENCODE = '\u1000.';48const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);4950/* eslint-disable unicorn/text-encoding-identifier-case */51test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);52test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);53test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);54test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);55test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);56test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);57test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);58test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);59test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);60test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);61test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);62test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);63test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);64test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);65test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);66test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);67test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);68test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);69test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);70test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);71test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);72test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);73test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);74test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);75test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);76test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);77test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);78test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);79test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);80test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);81test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);82test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);83test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);84test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);85test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);86test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);87test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);88test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);89test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);90test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);91test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);92test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);93test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);94test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);95test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);96test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);97test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);98test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);99test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);100test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);101test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);102test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);103test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);104test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);105test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);106test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);107test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);108test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);109test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);110test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);111test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);112test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);113test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);114test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);115test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);116test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);117test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);118test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);119test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);120test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);121test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);122test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);123test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);124test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);125test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);126test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);127test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);128test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);129/* eslint-enable unicorn/text-encoding-identifier-case */130131test('validate unknown encodings', t => {132 t.throws(() => {133 execa('noop.js', {encoding: 'unknownEncoding'});134 }, {code: 'ERR_UNKNOWN_ENCODING'});135});136137const foobarArray = ['fo', 'ob', 'ar', '..'];138139test('Handle multibyte characters', async t => {140 const {stdout} = await execa('noop.js', {stdout: getChunksGenerator(foobarArray, false), encoding: 'base64'});141 t.is(stdout, btoa(foobarArray.join('')));142});143144test('Handle multibyte characters, with objectMode', async t => {145 const {stdout} = await execa('noop.js', {stdout: getChunksGenerator(foobarArray, true), encoding: 'base64'});146 t.deepEqual(stdout, foobarArray.map(chunk => btoa(chunk)));147});148149test('Other encodings work with transforms that return objects', async t => {150 const {stdout} = await execa('noop.js', {stdout: outputObjectGenerator, encoding: 'base64'});151 t.deepEqual(stdout, [foobarObject]);152});153154const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options) => {155 const {stdout} = await execa('empty.js', {stdout: stdoutOption, ...options});156 t.is(stdout === undefined, isUndefined);157};158159const base64Options = {encoding: 'base64'};160const linesOptions = {lines: true};161test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options);162test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options);163test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options);164test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options);165test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options);166test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options);167test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options);168test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options);169test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options);170test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options);171test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options);172test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options);173test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options);174test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options);175test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options);176test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options);177test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options);178test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions);179test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions);180test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions);181test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions);182test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions);183test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions);184test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions);185test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions);186test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions);187test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions);188test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions);189test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions);190test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions);191test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions);192test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions);193test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions);194test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions);195test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions});196test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions});
added:test/stdio/encoding-start.js+188 added
1import {Buffer} from 'node:buffer';2import {scheduler} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio} from '../helpers/stdio.js';7import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';8import {noopGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';910setFixtureDir();1112const textEncoder = new TextEncoder();1314const getTypeofGenerator = objectMode => ({15 * transform(line) {16 yield Object.prototype.toString.call(line);17 },18 objectMode,19});2021// eslint-disable-next-line max-params22const testGeneratorFirstEncoding = async (t, input, encoding, output, objectMode) => {23 const childProcess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});24 childProcess.stdin.end(input);25 const {stdout} = await childProcess;26 const result = Buffer.from(stdout, encoding).toString();27 t.is(result, output);28};2930test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);31test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);32test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);33test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);34test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);35test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);36test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);37test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);38test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);39test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);40test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);4142const testEncodingIgnored = async (t, encoding) => {43 const input = Buffer.from(foobarString).toString(encoding);44 const childProcess = execa('stdin.js', {stdin: noopGenerator(true)});45 childProcess.stdin.end(input, encoding);46 const {stdout} = await childProcess;47 t.is(stdout, input);48};4950test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');51test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');52test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');53test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');5455// eslint-disable-next-line max-params56const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {57 const {stdout} = await execa('noop.js', ['other'], {58 stdout: [59 getOutputGenerator(input, firstObjectMode),60 getTypeofGenerator(secondObjectMode),61 ],62 encoding,63 });64 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;65 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();66 t.is(output, `[object ${expectedType}]`);67};6869test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');70test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');71test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');72test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');73test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');74test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');75test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');76test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');77test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');78test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');79test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');80test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');81test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');82test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');83test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');84test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');85test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');86test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');87test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');88test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');89test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');90test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');91test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');9293const testFirstOutputGeneratorArgument = async (t, index) => {94 const {stdio} = await execa('noop-fd.js', [`${index}`], getStdio(index, getTypeofGenerator(true)));95 t.deepEqual(stdio[index], ['[object String]']);96};9798test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);99test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);100test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);101102// eslint-disable-next-line max-params103const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final) => {104 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';105 const {stdout} = await execa(fixtureName, ['1', 'other'], {106 stdout: convertTransformToFinal(getOutputGenerator(input, objectMode), final),107 encoding,108 reject,109 });110 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;111 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();112 t.is(output, foobarString);113};114115test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false);116test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false);117test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false);118test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false);119test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false);120test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false);121test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false);122test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false);123test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false);124test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false);125test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false);126test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false);127test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false);128test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false);129test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false);130test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false);131test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false);132test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false);133test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false);134test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false);135test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false);136test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false);137test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false);138test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false);139test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true);140test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true);141test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true);142test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true);143test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true);144test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true);145test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true);146test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true);147test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true);148test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true);149test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true);150test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true);151test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true);152test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true);153test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true);154test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true);155test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true);156test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true);157test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true);158test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true);159test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true);160test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);161test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);162test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);163164const multibyteChar = '\u{1F984}';165const multibyteString = `${multibyteChar}${multibyteChar}`;166const multibyteUint8Array = textEncoder.encode(multibyteString);167const breakingLength = multibyteUint8Array.length * 0.75;168const brokenSymbol = '\uFFFD';169170const testMultibyte = async (t, objectMode) => {171 const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});172 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));173 await scheduler.yield();174 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));175 const {stdout} = await childProcess;176 t.is(stdout, multibyteString);177};178179test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);180test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);181182const testMultibytePartial = async (t, objectMode) => {183 const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator(objectMode)]});184 t.is(stdout, `${multibyteChar}${brokenSymbol}`);185};186187test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);188test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);
deleted:test/stdio/encoding.js-196 removed
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import process from 'node:process';4import {promisify} from 'node:util';5import test from 'ava';6import getStream, {getStreamAsBuffer} from 'get-stream';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9import {fullStdio} from '../helpers/stdio.js';10import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';11import {foobarObject} from '../helpers/input.js';1213const pExec = promisify(exec);1415setFixtureDir();1617const checkEncoding = async (t, encoding, index, execaMethod) => {18 const {stdio} = await execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding});19 compareValues(t, stdio[index], encoding);2021 if (execaMethod !== execaSync) {22 const childProcess = execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding, buffer: false});23 const getStreamMethod = encoding === 'buffer' ? getStreamAsBuffer : getStream;24 const result = await getStreamMethod(childProcess.stdio[index]);25 compareValues(t, result, encoding);26 await childProcess;27 }2829 if (index === 3) {30 return;31 }3233 const {stdout, stderr} = await pExec(`node noop-fd.js ${index} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});34 compareValues(t, index === 1 ? stdout : stderr, encoding);35};3637const compareValues = (t, value, encoding) => {38 if (encoding === 'buffer') {39 t.true(ArrayBuffer.isView(value));40 t.true(BUFFER_TO_ENCODE.equals(value));41 } else {42 t.is(value, BUFFER_TO_ENCODE.toString(encoding));43 }44};4546// This string gives different outputs with each encoding type47const STRING_TO_ENCODE = '\u1000.';48const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);4950/* eslint-disable unicorn/text-encoding-identifier-case */51test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);52test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);53test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);54test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);55test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);56test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);57test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);58test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);59test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);60test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);61test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);62test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);63test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);64test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);65test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);66test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);67test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);68test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);69test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);70test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);71test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);72test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);73test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);74test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);75test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);76test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);77test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);78test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);79test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);80test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);81test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);82test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);83test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);84test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);85test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);86test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);87test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);88test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);89test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);90test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);91test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);92test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);93test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);94test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);95test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);96test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);97test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);98test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);99test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);100test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);101test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);102test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);103test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);104test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);105test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);106test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);107test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);108test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);109test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);110test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);111test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);112test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);113test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);114test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);115test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);116test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);117test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);118test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);119test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);120test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);121test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);122test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);123test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);124test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);125test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);126test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);127test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);128test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);129/* eslint-enable unicorn/text-encoding-identifier-case */130131test('validate unknown encodings', t => {132 t.throws(() => {133 execa('noop.js', {encoding: 'unknownEncoding'});134 }, {code: 'ERR_UNKNOWN_ENCODING'});135});136137const foobarArray = ['fo', 'ob', 'ar', '..'];138139test('Handle multibyte characters', async t => {140 const {stdout} = await execa('noop.js', {stdout: getChunksGenerator(foobarArray, false), encoding: 'base64'});141 t.is(stdout, btoa(foobarArray.join('')));142});143144test('Handle multibyte characters, with objectMode', async t => {145 const {stdout} = await execa('noop.js', {stdout: getChunksGenerator(foobarArray, true), encoding: 'base64'});146 t.deepEqual(stdout, foobarArray.map(chunk => btoa(chunk)));147});148149test('Other encodings work with transforms that return objects', async t => {150 const {stdout} = await execa('noop.js', {stdout: outputObjectGenerator, encoding: 'base64'});151 t.deepEqual(stdout, [foobarObject]);152});153154const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options) => {155 const {stdout} = await execa('empty.js', {stdout: stdoutOption, ...options});156 t.is(stdout === undefined, isUndefined);157};158159const base64Options = {encoding: 'base64'};160const linesOptions = {lines: true};161test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options);162test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options);163test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options);164test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options);165test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options);166test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options);167test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options);168test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options);169test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options);170test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options);171test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options);172test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options);173test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options);174test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options);175test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options);176test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options);177test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options);178test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions);179test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions);180test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions);181test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions);182test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions);183test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions);184test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions);185test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions);186test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions);187test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions);188test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions);189test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions);190test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions);191test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions);192test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions);193test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions);194test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions);195test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions});196test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions});
added:test/stdio/forward.js+16 added
1import test from 'ava';2import {execa} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const testOverlapped = async (t, index) => {9 const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));10 t.is(stdout, 'foobar');11};1213test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);14test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);15test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);16test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);
modified:test/stdio/generator.js+3 added-447 removed
1import {Buffer} from 'node:buffer';2import {once} from 'node:events';1import {readFile, writeFile, rm} from 'node:fs/promises';4import {getDefaultHighWaterMark, PassThrough} from 'node:stream';5import {setTimeout, scheduler} from 'node:timers/promises';2import {PassThrough} from 'node:stream';3import test from 'ava';4import getStream, {getStreamAsArray} from 'get-stream';5import tempfile from 'tempfile';9import {execa, execaSync} from '../../index.js';6import {execa} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {getStdio} from '../helpers/stdio.js';9import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';13import {14 serializeGenerator,15 noopGenerator,16 getOutputsGenerator,17 getOutputGenerator,18 outputObjectGenerator,19 noYieldGenerator,20 convertTransformToFinal,21 infiniteGenerator,22} from '../helpers/generator.js';10import {serializeGenerator, outputObjectGenerator} from '../helpers/generator.js';1112setFixtureDir();1314const textEncoder = new TextEncoder();
58 unmodified lines
73test('Can use generators with childProcess.stdio[*] as input', testGeneratorStdioInputPipe, false);74test('Can use generators with childProcess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true);7576// eslint-disable-next-line max-params89const testGeneratorReturn = async (t, index, generators, fixtureName, isNull) => {90 const childProcess = execa(fixtureName, [`${index}`], getStdio(index, generators));91 const message = isNull ? /not be called at all/ : /a string or an Uint8Array/;92 await t.throwsAsync(childProcess, {message});93};9495const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];96const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator];9798test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator(foobarObject, false), 'stdin-fd.js', false);99test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator(foobarObject, false), 'stdin-fd.js', false);100test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);101test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);102test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);103test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);104test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);105test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator(null, false), 'stdin-fd.js', true);106test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator(null, true), 'stdin-fd.js', true);107test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, false), 'noop-fd.js', true);108test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, true), 'noop-fd.js', true);109test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, false), 'stdin-fd.js', true);110test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, true), 'stdin-fd.js', true);111test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, false), 'noop-fd.js', true);112test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, true), 'noop-fd.js', true);113114const testGeneratorFinal = async (t, fixtureName) => {115 const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});116 t.is(stdout, foobarString);117};118119test('Generators "final" can be used', testGeneratorFinal, 'noop.js');120test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');121122test('Generators "final" return value is validated', async t => {123 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});124 await t.throwsAsync(childProcess, {message: /not be called at all/});125});126127// eslint-disable-next-line max-params77const testGeneratorOutput = async (t, index, reject, useShortcutProperty, objectMode) => {78 const {generator, output} = getOutputObjectMode(objectMode);79 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';80 const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, generator), reject});
121 unmodified lines
202 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});203 t.is(stdout, foobarUppercase);204});205257const testInvalidGenerator = (t, index, stdioOption) => {258 t.throws(() => {259 execa('empty.js', getStdio(index, {...noopGenerator(), ...stdioOption}));260 }, {message: /must be a generator/});261};262263test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true});264test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});265test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});266test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});267test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true});268test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true});269test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true});270test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true});271272const testInvalidBinary = (t, index, optionName) => {273 t.throws(() => {274 execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));275 }, {message: /a boolean/});276};277278test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');279test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');280test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');281test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');282test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');283test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');284test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');285test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');286287const testSyncMethods = (t, index) => {288 t.throws(() => {289 execaSync('empty.js', getStdio(index, uppercaseGenerator));290 }, {message: /cannot be a generator/});291};292293test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);294test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);295test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);296test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);297298const repeatCount = getDefaultHighWaterMark() * 3;299300const writerGenerator = function * () {301 for (let index = 0; index < repeatCount; index += 1) {302 yield '\n';303 }304};305306const getLengthGenerator = function * (t, chunk) {307 t.is(chunk.length, 1);308 yield chunk;309};310311const testHighWaterMark = async (t, passThrough, binary, objectMode) => {312 const {stdout} = await execa('noop.js', {313 stdout: [314 ...(objectMode ? [outputObjectGenerator] : []),315 writerGenerator,316 ...(passThrough ? [noopGenerator(false, binary)] : []),317 {transform: getLengthGenerator.bind(undefined, t), binary: true, objectMode: true},318 ],319 });320 t.is(stdout.length, repeatCount);321 t.true(stdout.every(chunk => chunk.toString() === '\n'));322};323324test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false);325test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false);326test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false);327test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true);328329const getTypeofGenerator = objectMode => ({330 * transform(line) {331 yield Object.prototype.toString.call(line);332 },333 objectMode,334});335336// eslint-disable-next-line max-params337const testGeneratorFirstEncoding = async (t, input, encoding, output, objectMode) => {338 const childProcess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});339 childProcess.stdin.end(input);340 const {stdout} = await childProcess;341 const result = Buffer.from(stdout, encoding).toString();342 t.is(result, output);343};344345test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);346test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);347test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);348test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);349test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);350test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);351test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);352test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);353test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);354test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);355test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);356357const testEncodingIgnored = async (t, encoding) => {358 const input = Buffer.from(foobarString).toString(encoding);359 const childProcess = execa('stdin.js', {stdin: noopGenerator(true)});360 childProcess.stdin.end(input, encoding);361 const {stdout} = await childProcess;362 t.is(stdout, input);363};364365test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');366test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');367test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');368test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');369370// eslint-disable-next-line max-params371const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {372 const {stdout} = await execa('noop.js', ['other'], {373 stdout: [374 getOutputGenerator(input, firstObjectMode),375 getTypeofGenerator(secondObjectMode),376 ],377 encoding,378 });379 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;380 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();381 t.is(output, `[object ${expectedType}]`);382};383384test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');385test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');386test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');387test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');388test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');389test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');390test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');391test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');392test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');393test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');394test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');395test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');396test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');397test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');398test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');399test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');400test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');401test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');402test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');403test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');404test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');405test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');406test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');407408const testFirstOutputGeneratorArgument = async (t, index) => {409 const {stdio} = await execa('noop-fd.js', [`${index}`], getStdio(index, getTypeofGenerator(true)));410 t.deepEqual(stdio[index], ['[object String]']);411};412413test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);414test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);415test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);416417// eslint-disable-next-line max-params418const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final) => {419 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';420 const {stdout} = await execa(fixtureName, ['1', 'other'], {421 stdout: convertTransformToFinal(getOutputGenerator(input, objectMode), final),422 encoding,423 reject,424 });425 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;426 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();427 t.is(output, foobarString);428};429430test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false);431test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false);432test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false);433test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false);434test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false);435test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false);436test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false);437test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false);438test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false);439test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false);440test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false);441test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false);442test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false);443test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false);444test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false);445test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false);446test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false);447test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false);448test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false);449test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false);450test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false);451test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false);452test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false);453test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false);454test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true);455test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true);456test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true);457test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true);458test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true);459test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true);460test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true);461test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true);462test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true);463test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true);464test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true);465test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true);466test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true);467test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true);468test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true);469test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true);470test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true);471test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true);472test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true);473test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true);474test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true);475test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);476test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);477test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);478479const multibyteChar = '\u{1F984}';480const multibyteString = `${multibyteChar}${multibyteChar}`;481const multibyteUint8Array = textEncoder.encode(multibyteString);482const breakingLength = multibyteUint8Array.length * 0.75;483const brokenSymbol = '\uFFFD';484485const testMultibyte = async (t, objectMode) => {486 const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});487 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));488 await scheduler.yield();489 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));490 const {stdout} = await childProcess;491 t.is(stdout, multibyteString);492};493494test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);495test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);496497const testMultibytePartial = async (t, objectMode) => {498 const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator(objectMode)]});499 t.is(stdout, `${multibyteChar}${brokenSymbol}`);500};501502test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);503test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);504505const testNoYield = async (t, objectMode, final, output) => {506 const {stdout} = await execa('noop.js', {stdout: convertTransformToFinal(noYieldGenerator(objectMode), final)});507 t.deepEqual(stdout, output);508};509510test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');511test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);512test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');513test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);514515const prefix = '> ';516const suffix = ' <';517518const multipleYieldGenerator = async function * (line = foobarString) {519 yield prefix;520 await scheduler.yield();521 yield line;522 await scheduler.yield();523 yield suffix;524};525526const testMultipleYields = async (t, final) => {527 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator, final)});528 t.is(stdout, `${prefix}${foobarString}${suffix}`);529};530531test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);532test('Generator can yield "final" multiple times at different moments', testMultipleYields, true);533534const partsPerChunk = 4;535const chunksPerCall = 10;536const callCount = 5;537const fullString = '\n'.repeat(getDefaultHighWaterMark(false) / partsPerChunk);538539const yieldFullStrings = function * () {540 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);541};542543const manyYieldGenerator = async function * () {544 for (let index = 0; index < callCount; index += 1) {545 yield * yieldFullStrings();546 // eslint-disable-next-line no-await-in-loop547 await scheduler.yield();548 }549};550551const testManyYields = async (t, final) => {552 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), buffer: false});553 const [chunks] = await Promise.all([getStreamAsArray(childProcess.stdout), childProcess]);554 const expectedChunk = Buffer.alloc(getDefaultHighWaterMark(false) * chunksPerCall).fill('\n');555 t.deepEqual(chunks, Array.from({length: callCount}).fill(expectedChunk));556};557558test('Generator "transform" yields are sent right away', testManyYields, false);559test('Generator "final" yields are sent right away', testManyYields, true);560206const testInputFile = async (t, getOptions, reversed) => {207 const filePath = tempfile();208 await writeFile(filePath, foobarString);209 const {stdin, ...options} = getOptions(filePath);
74 unmodified lines
284test('Can use multiple identical generators', async t => {285 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: [appendGenerator, appendGenerator]});286 t.is(stdout, `${foobarString}${casedSuffix}${casedSuffix}`);287});643644const maxBuffer = 10;645646test('Generators take "maxBuffer" into account', async t => {647 const bigString = '.'.repeat(maxBuffer);648 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputGenerator(bigString, false)});649 t.is(stdout, bigString);650651 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));652});653654test('Generators take "maxBuffer" into account, objectMode', async t => {655 const bigArray = Array.from({length: maxBuffer}).fill('.');656 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputsGenerator(bigArray, true)});657 t.is(stdout.length, maxBuffer);658659 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));660});661662const timeoutGenerator = async function * (timeout) {663 await setTimeout(timeout);664 yield foobarString;665};666667const testAsyncGenerators = async (t, final) => {668 const {stdout} = await execa('noop.js', {669 maxBuffer,670 stdout: convertTransformToFinal(timeoutGenerator.bind(undefined, 1e2), final),671 });672 t.is(stdout, foobarString);673};674675test('Generators "transform" is awaited on success', testAsyncGenerators, false);676test('Generators "final" is awaited on success', testAsyncGenerators, true);677678// eslint-disable-next-line require-yield679const throwingGenerator = function * () {680 throw new Error('Generator error');681};682683const GENERATOR_ERROR_REGEXP = /Generator error/;684685const testThrowingGenerator = async (t, final) => {686 await t.throwsAsync(687 execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator, final)}),688 {message: GENERATOR_ERROR_REGEXP},689 );690};691692test('Generators "transform" errors make process fail', testThrowingGenerator, false);693test('Generators "final" errors make process fail', testThrowingGenerator, true);694695test('Generators errors make process fail even when other output generators do not throw', async t => {696 await t.throwsAsync(697 execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),698 {message: GENERATOR_ERROR_REGEXP},699 );700});701702test('Generators errors make process fail even when other input generators do not throw', async t => {703 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});704 childProcess.stdin.write('foobar\n');705 await t.throwsAsync(childProcess, {message: GENERATOR_ERROR_REGEXP});706});707708const testGeneratorCancel = async (t, error) => {709 const childProcess = execa('noop.js', {stdout: infiniteGenerator});710 await once(childProcess.stdout, 'data');711 childProcess.stdout.destroy(error);712 await (error === undefined ? t.notThrowsAsync(childProcess) : t.throwsAsync(childProcess));713};714715test('Running generators are canceled on process abort', testGeneratorCancel, undefined);716test('Running generators are canceled on process error', testGeneratorCancel, new Error('test'));717718const testGeneratorDestroy = async (t, transform) => {719 const childProcess = execa('forever.js', {stdout: transform});720 const error = new Error('test');721 childProcess.stdout.destroy(error);722 childProcess.kill();723 t.is(await t.throwsAsync(childProcess), error);724};725726test('Generators are destroyed on process error, sync', testGeneratorDestroy, noopGenerator(false));727test('Generators are destroyed on process error, async', testGeneratorDestroy, infiniteGenerator);728729test('Generators are destroyed on early process exit', async t => {730 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));731});
added:test/stdio/handle.js+87 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const testEmptyArray = (t, index, optionName, execaMethod) => {9 t.throws(() => {10 execaMethod('empty.js', getStdio(index, []));11 }, {message: `The \`${optionName}\` option must not be an empty array.`});12};1314test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2223const testNoPipeOption = async (t, stdioOption, index) => {24 const childProcess = execa('empty.js', getStdio(index, stdioOption));25 t.is(childProcess.stdio[index], null);26 await childProcess;27};2829test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);30test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);31test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);32test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);33test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);34test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);35test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);36test('stdin can be 0', testNoPipeOption, 0, 0);37test('stdin can be [0]', testNoPipeOption, [0], 0);38test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);39test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);40test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);41test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);42test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);43test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);44test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);45test('stdout can be 1', testNoPipeOption, 1, 1);46test('stdout can be [1]', testNoPipeOption, [1], 1);47test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);48test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);49test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);50test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);51test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);52test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);53test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);54test('stderr can be 2', testNoPipeOption, 2, 2);55test('stderr can be [2]', testNoPipeOption, [2], 2);56test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);57test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);58test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);59test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);60test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);61test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);62test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);63test('stdio[*] can be 3', testNoPipeOption, 3, 3);64test('stdio[*] can be [3]', testNoPipeOption, [3], 3);6566const testInvalidArrayValue = (t, invalidStdio, index, execaMethod) => {67 t.throws(() => {68 execaMethod('empty.js', getStdio(index, ['pipe', invalidStdio]));69 }, {message: /must not include/});70};7172test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);73test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);74test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);75test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);76test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);77test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);78test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);79test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);80test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);81test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);82test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);83test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);84test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);85test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);86test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);87test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);
added:test/stdio/native.js+108 added
1import {platform} from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {getStdio, fullStdio} from '../helpers/stdio.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89const testRedirect = async (t, stdioOption, index, isInput) => {10 const {fixtureName, ...options} = isInput11 ? {fixtureName: 'stdin-fd.js', input: 'foobar'}12 : {fixtureName: 'noop-fd.js'};13 const {stdio} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), `${index}`, fixtureName, 'foobar'], options);14 const resultIndex = isStderrDescriptor(stdioOption) ? 2 : 1;15 t.is(stdio[resultIndex], 'foobar');16};1718const isStderrDescriptor = stdioOption => stdioOption === 219 || stdioOption === 'stderr'20 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));2122test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);23test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);24test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);25test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);26test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);27test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);28test('stdout can be 2', testRedirect, 2, 1, false);29test('stdout can be [2]', testRedirect, [2], 1, false);30test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);31test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);32test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);33test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);34test('stderr can be 1', testRedirect, 1, 2, false);35test('stderr can be [1]', testRedirect, [1], 2, false);36test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);37test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);38test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);39test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);40test('stdio[*] can be 1', testRedirect, 1, 3, false);41test('stdio[*] can be [1]', testRedirect, [1], 3, false);42test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);43test('stdio[*] can be 2', testRedirect, 2, 3, false);44test('stdio[*] can be [2]', testRedirect, [2], 3, false);45test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);46test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);47test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);48test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);49test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);50test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);51test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);5253const testInheritStdin = async (t, stdin) => {54 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});55 t.is(stdout, 'foobarfoobar');56};5758test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe']);59test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe']);6061const testInheritStdout = async (t, stdout) => {62 const result = await execa('nested-multiple-stdout.js', [JSON.stringify(stdout)]);63 t.is(result.stdout, 'foobar');64 t.is(result.stderr, 'nested foobar');65};6667test('stdout can be ["inherit", "pipe"]', testInheritStdout, ['inherit', 'pipe']);68test('stdout can be [1, "pipe"]', testInheritStdout, [1, 'pipe']);6970const testInheritStderr = async (t, stderr) => {71 const result = await execa('nested-multiple-stderr.js', [JSON.stringify(stderr)]);72 t.is(result.stdout, 'nested foobar');73 t.is(result.stderr, 'foobar');74};7576test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);77test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);7879const testOverflowStream = async (t, index, stdioOption) => {80 const {stdout} = await execa('nested.js', [JSON.stringify(getStdio(index, stdioOption)), 'empty.js'], fullStdio);81 t.is(stdout, '');82};8384if (platform === 'linux') {85 test('stdin can use 4+', testOverflowStream, 0, 4);86 test('stdin can use [4+]', testOverflowStream, 0, [4]);87 test('stdout can use 4+', testOverflowStream, 1, 4);88 test('stdout can use [4+]', testOverflowStream, 1, [4]);89 test('stderr can use 4+', testOverflowStream, 2, 4);90 test('stderr can use [4+]', testOverflowStream, 2, [4]);91 test('stdio[*] can use 4+', testOverflowStream, 3, 4);92 test('stdio[*] can use [4+]', testOverflowStream, 3, [4]);93}9495test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');96test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);9798const testOverflowStreamArray = (t, index, stdioOption) => {99 t.throws(() => {100 execa('empty.js', getStdio(index, stdioOption));101 }, {message: /no such standard stream/});102};103104test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);105test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);106test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);107test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);108test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);
deleted:test/stdio/normalize.js-45 removed
1import {inspect} from 'node:util';2import test from 'ava';3import {normalizeStdio} from '../../lib/stdio/normalize.js';45const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdio(input);9 }, {message: expected.message});10 return;11 }1213 t.deepEqual(func(input), expected);14};1516const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;1718const stdioMacro = (...args) => macro(...args, normalizeStdio);19stdioMacro.title = macroTitle('execa()');2021test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);2526test(stdioMacro, {}, [undefined, undefined, undefined]);27test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);28test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);29test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);30test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);31test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);32test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);33test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);34test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);35test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);36test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);37test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);38test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);3940test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));4142test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));43test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));44test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));45test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));
added:test/stdio/option.js+45 added
1import {inspect} from 'node:util';2import test from 'ava';3import {normalizeStdio} from '../../lib/stdio/option.js';45const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdio(input);9 }, {message: expected.message});10 return;11 }1213 t.deepEqual(func(input), expected);14};1516const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;1718const stdioMacro = (...args) => macro(...args, normalizeStdio);19stdioMacro.title = macroTitle('execa()');2021test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);2526test(stdioMacro, {}, [undefined, undefined, undefined]);27test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);28test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);29test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);30test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);31test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);32test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);33test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);34test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);35test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);36test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);37test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);38test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);3940test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));4142test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));43test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));44test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));45test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));
added:test/stdio/pipeline.js+39 added
1import test from 'ava';2import {execa} from '../../index.js';3import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const testDestroyStandard = async (t, index) => {9 const childProcess = execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), timeout: 1});10 await t.throwsAsync(childProcess, {message: /timed out/});11 t.false(STANDARD_STREAMS[index].destroyed);12};1314test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);15test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);16test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);1718const testDestroyStandardSpawn = async (t, index) => {19 await t.throwsAsync(execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), uid: -1}));20 t.false(STANDARD_STREAMS[index].destroyed);21};2223test('Does not destroy process.stdin on spawn process errors', testDestroyStandardSpawn, 0);24test('Does not destroy process.stdout on spawn process errors', testDestroyStandardSpawn, 1);25test('Does not destroy process.stderr on spawn process errors', testDestroyStandardSpawn, 2);2627const testDestroyStandardStream = async (t, index) => {28 const childProcess = execa('forever.js', getStdio(index, [STANDARD_STREAMS[index], 'pipe']));29 const error = new Error('test');30 childProcess.stdio[index].destroy(error);31 childProcess.kill();32 const thrownError = await t.throwsAsync(childProcess);33 t.is(thrownError, error);34 t.false(STANDARD_STREAMS[index].destroyed);35};3637test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);38test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);39test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);
added:test/stdio/transform.js+204 added
1import {Buffer} from 'node:buffer';2import {once} from 'node:events';3import {setTimeout, scheduler} from 'node:timers/promises';4import {getDefaultHighWaterMark} from 'node:stream';5import test from 'ava';6import {getStreamAsArray} from 'get-stream';7import {execa} from '../../index.js';8import {foobarString} from '../helpers/input.js';9import {10 noopGenerator,11 getOutputsGenerator,12 getOutputGenerator,13 infiniteGenerator,14 outputObjectGenerator,15 convertTransformToFinal,16 noYieldGenerator,17} from '../helpers/generator.js';18import {setFixtureDir} from '../helpers/fixtures-dir.js';1920setFixtureDir();2122const testGeneratorFinal = async (t, fixtureName) => {23 const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});24 t.is(stdout, foobarString);25};2627test('Generators "final" can be used', testGeneratorFinal, 'noop.js');28test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');2930const repeatCount = getDefaultHighWaterMark() * 3;3132const writerGenerator = function * () {33 for (let index = 0; index < repeatCount; index += 1) {34 yield '\n';35 }36};3738const getLengthGenerator = function * (t, chunk) {39 t.is(chunk.length, 1);40 yield chunk;41};4243const testHighWaterMark = async (t, passThrough, binary, objectMode) => {44 const {stdout} = await execa('noop.js', {45 stdout: [46 ...(objectMode ? [outputObjectGenerator] : []),47 writerGenerator,48 ...(passThrough ? [noopGenerator(false, binary)] : []),49 {transform: getLengthGenerator.bind(undefined, t), binary: true, objectMode: true},50 ],51 });52 t.is(stdout.length, repeatCount);53 t.true(stdout.every(chunk => chunk.toString() === '\n'));54};5556test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false);57test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false);58test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false);59test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true);6061const testNoYield = async (t, objectMode, final, output) => {62 const {stdout} = await execa('noop.js', {stdout: convertTransformToFinal(noYieldGenerator(objectMode), final)});63 t.deepEqual(stdout, output);64};6566test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');67test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);68test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');69test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);7071const prefix = '> ';72const suffix = ' <';7374const multipleYieldGenerator = async function * (line = foobarString) {75 yield prefix;76 await scheduler.yield();77 yield line;78 await scheduler.yield();79 yield suffix;80};8182const testMultipleYields = async (t, final) => {83 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator, final)});84 t.is(stdout, `${prefix}${foobarString}${suffix}`);85};8687test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);88test('Generator can yield "final" multiple times at different moments', testMultipleYields, true);8990const partsPerChunk = 4;91const chunksPerCall = 10;92const callCount = 5;93const fullString = '\n'.repeat(getDefaultHighWaterMark(false) / partsPerChunk);9495const yieldFullStrings = function * () {96 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);97};9899const manyYieldGenerator = async function * () {100 for (let index = 0; index < callCount; index += 1) {101 yield * yieldFullStrings();102 // eslint-disable-next-line no-await-in-loop103 await scheduler.yield();104 }105};106107const testManyYields = async (t, final) => {108 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), buffer: false});109 const [chunks] = await Promise.all([getStreamAsArray(childProcess.stdout), childProcess]);110 const expectedChunk = Buffer.alloc(getDefaultHighWaterMark(false) * chunksPerCall).fill('\n');111 t.deepEqual(chunks, Array.from({length: callCount}).fill(expectedChunk));112};113114test('Generator "transform" yields are sent right away', testManyYields, false);115test('Generator "final" yields are sent right away', testManyYields, true);116117const maxBuffer = 10;118119test('Generators take "maxBuffer" into account', async t => {120 const bigString = '.'.repeat(maxBuffer);121 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputGenerator(bigString, false)});122 t.is(stdout, bigString);123124 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));125});126127test('Generators take "maxBuffer" into account, objectMode', async t => {128 const bigArray = Array.from({length: maxBuffer}).fill('.');129 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputsGenerator(bigArray, true)});130 t.is(stdout.length, maxBuffer);131132 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));133});134135const timeoutGenerator = async function * (timeout) {136 await setTimeout(timeout);137 yield foobarString;138};139140const testAsyncGenerators = async (t, final) => {141 const {stdout} = await execa('noop.js', {142 maxBuffer,143 stdout: convertTransformToFinal(timeoutGenerator.bind(undefined, 1e2), final),144 });145 t.is(stdout, foobarString);146};147148test('Generators "transform" is awaited on success', testAsyncGenerators, false);149test('Generators "final" is awaited on success', testAsyncGenerators, true);150151// eslint-disable-next-line require-yield152const throwingGenerator = function * () {153 throw new Error('Generator error');154};155156const GENERATOR_ERROR_REGEXP = /Generator error/;157158const testThrowingGenerator = async (t, final) => {159 await t.throwsAsync(160 execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator, final)}),161 {message: GENERATOR_ERROR_REGEXP},162 );163};164165test('Generators "transform" errors make process fail', testThrowingGenerator, false);166test('Generators "final" errors make process fail', testThrowingGenerator, true);167168test('Generators errors make process fail even when other output generators do not throw', async t => {169 await t.throwsAsync(170 execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),171 {message: GENERATOR_ERROR_REGEXP},172 );173});174175test('Generators errors make process fail even when other input generators do not throw', async t => {176 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});177 childProcess.stdin.write('foobar\n');178 await t.throwsAsync(childProcess, {message: GENERATOR_ERROR_REGEXP});179});180181const testGeneratorCancel = async (t, error) => {182 const childProcess = execa('noop.js', {stdout: infiniteGenerator});183 await once(childProcess.stdout, 'data');184 childProcess.stdout.destroy(error);185 await (error === undefined ? t.notThrowsAsync(childProcess) : t.throwsAsync(childProcess));186};187188test('Running generators are canceled on process abort', testGeneratorCancel, undefined);189test('Running generators are canceled on process error', testGeneratorCancel, new Error('test'));190191const testGeneratorDestroy = async (t, transform) => {192 const childProcess = execa('forever.js', {stdout: transform});193 const error = new Error('test');194 childProcess.stdout.destroy(error);195 childProcess.kill();196 t.is(await t.throwsAsync(childProcess), error);197};198199test('Generators are destroyed on process error, sync', testGeneratorDestroy, noopGenerator(false));200test('Generators are destroyed on process error, async', testGeneratorDestroy, infiniteGenerator);201202test('Generators are destroyed on early process exit', async t => {203 await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));204});
added:test/stdio/type.js+52 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {noopGenerator} from '../helpers/generator.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89const uppercaseGenerator = function * (line) {10 yield line.toUpperCase();11};1213const testInvalidGenerator = (t, index, stdioOption) => {14 t.throws(() => {15 execa('empty.js', getStdio(index, {...noopGenerator(), ...stdioOption}));16 }, {message: /must be a generator/});17};1819test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true});20test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});21test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});22test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});23test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true});24test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true});25test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true});26test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true});2728const testInvalidBinary = (t, index, optionName) => {29 t.throws(() => {30 execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));31 }, {message: /a boolean/});32};3334test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');35test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');36test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');37test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');38test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');39test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');40test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');41test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');4243const testSyncMethods = (t, index) => {44 t.throws(() => {45 execaSync('empty.js', getStdio(index, uppercaseGenerator));46 }, {message: /cannot be a generator/});47};4849test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);50test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);51test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);52test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);
added:test/stdio/validate.js+39 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {foobarUint8Array, foobarObject} from '../helpers/input.js';6import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';78setFixtureDir();910// eslint-disable-next-line max-params11const testGeneratorReturn = async (t, index, generators, fixtureName, isNull) => {12 const childProcess = execa(fixtureName, [`${index}`], getStdio(index, generators));13 const message = isNull ? /not be called at all/ : /a string or an Uint8Array/;14 await t.throwsAsync(childProcess, {message});15};1617const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];18const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator];1920test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator(foobarObject, false), 'stdin-fd.js', false);21test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator(foobarObject, false), 'stdin-fd.js', false);22test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);23test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);24test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);25test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);26test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);27test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator(null, false), 'stdin-fd.js', true);28test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator(null, true), 'stdin-fd.js', true);29test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, false), 'noop-fd.js', true);30test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, true), 'noop-fd.js', true);31test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, false), 'stdin-fd.js', true);32test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, true), 'stdin-fd.js', true);33test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, false), 'noop-fd.js', true);34test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, true), 'noop-fd.js', true);3536test('Generators "final" return value is validated', async t => {37 const childProcess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});38 await t.throwsAsync(childProcess, {message: /not be called at all/});39});
deleted:test/stdio/wait.js-228 removed
1import {platform} from 'node:process';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio, prematureClose} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {noopGenerator} from '../helpers/generator.js';9import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';1011setFixtureDir();1213const isWindows = platform === 'win32';1415const noop = () => {};1617const endOptionStream = ({stream}) => {18 stream.end();19};2021const destroyOptionStream = ({stream, error}) => {22 stream.destroy(error);23};2425const destroyChildStream = ({childProcess, index, error}) => {26 childProcess.stdio[index].destroy(error);27};2829const getStreamStdio = (index, stream, useTransform) => getStdio(index, [stream, useTransform ? noopGenerator(false) : 'pipe']);3031// eslint-disable-next-line max-params32const testStreamAbortWait = async (t, streamMethod, stream, index, useTransform) => {33 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));34 streamMethod({stream, childProcess, index});35 childProcess.stdin.end();36 await setImmediate();37 stream.destroy();3839 const {stdout} = await childProcess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Keeps running when stdin option is used and childProcess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45test('Keeps running when stdin option is used and childProcess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47test('Keeps running when stdin option is used and childProcess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48test('Keeps running when stdin option is used and childProcess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);5051// eslint-disable-next-line max-params52const testStreamAbortSuccess = async (t, streamMethod, stream, index, useTransform) => {53 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));54 streamMethod({stream, childProcess, index});55 childProcess.stdin.end();5657 const {stdout} = await childProcess;58 t.is(stdout, '');59 t.true(stream.destroyed);60};6162test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);63test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);64test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);65test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);66test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);67test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);68test('Passes when childProcess.stdout aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, false);69test('Passes when childProcess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, false);70test('Passes when childProcess.stderr aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, false);71test('Passes when childProcess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, false);72test('Passes when output childProcess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, false);73test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, false);74test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);75test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);76test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);77test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);78test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);79test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);80test('Passes when childProcess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, true);81test('Passes when childProcess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, true);82test('Passes when childProcess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, true);83test('Passes when childProcess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, true);84test('Passes when output childProcess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, true);85test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, true);8687// eslint-disable-next-line max-params88const testStreamAbortFail = async (t, streamMethod, stream, index, useTransform) => {89 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));90 streamMethod({stream, childProcess, index});91 if (index !== 0) {92 childProcess.stdin.end();93 }9495 const error = await t.throwsAsync(childProcess);96 t.like(error, {...prematureClose, exitCode: 0});97 t.true(stream.destroyed);98};99100test('Throws abort error when childProcess.stdin aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 0, false);101test('Throws abort error when childProcess.stdin Duplex aborts', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, false);102test('Throws abort error when input childProcess.stdio[*] aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 3, false);103test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);104test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);105test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);106test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);107test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);108test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);109test('Throws abort error when childProcess.stdin aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 0, true);110test('Throws abort error when childProcess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, true);111test('Throws abort error when input childProcess.stdio[*] aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 3, true);112test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);113test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);114test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);115test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);116test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);117test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118119// eslint-disable-next-line max-params120const testStreamEpipeSuccess = async (t, streamMethod, stream, index, useTransform) => {121 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));122 streamMethod({stream, childProcess, index});123 childProcess.stdin.end(foobarString);124125 const {stdio} = await childProcess;126 t.is(stdio[index], foobarString);127 t.true(stream.destroyed);128};129130test('Passes when stdout option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, false);131test('Passes when stderr option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, false);132test('Passes when output stdio[*] option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, false);133test('Passes when stdout option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, true);134test('Passes when stderr option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, true);135test('Passes when output stdio[*] option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, true);136137// eslint-disable-next-line max-params138const testStreamEpipeFail = async (t, streamMethod, stream, index, useTransform) => {139 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));140 streamMethod({stream, childProcess, index});141 await setImmediate();142 childProcess.stdin.end(foobarString);143144 const {exitCode, stdio, stderr} = await t.throwsAsync(childProcess);145 t.is(exitCode, 1);146 t.is(stdio[index], '');147 t.true(stream.destroyed);148 if (index !== 2 && !isWindows) {149 t.true(stderr.includes('EPIPE'));150 }151};152153test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);154test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);155test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);156test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);157test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);158test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);159test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);160test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);161test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);162test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);163test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);164test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);165test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);166test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);167test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);168test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);169test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);170test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);171test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);172test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);173test('Throws EPIPE when childProcess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, true);174test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, true);175test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, true);176test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, true);177178// eslint-disable-next-line max-params179const testStreamError = async (t, streamMethod, stream, index, useTransform) => {180 const childProcess = execa('empty.js', getStreamStdio(index, stream, useTransform));181 const error = new Error('test');182 streamMethod({stream, childProcess, index, error});183184 t.is(await t.throwsAsync(childProcess), error);185 const {exitCode, signal, isTerminated, failed} = error;186 t.is(exitCode, 0);187 t.is(signal, undefined);188 t.false(isTerminated);189 t.true(failed);190 t.true(stream.destroyed);191};192193test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);194test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);195test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);196test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);197test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);198test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);199test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);200test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);201test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);202test('Throws stream error when childProcess.stdin errors', testStreamError, destroyChildStream, noopReadable(), 0, false);203test('Throws stream error when childProcess.stdin Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 0, false);204test('Throws stream error when childProcess.stdout errors', testStreamError, destroyChildStream, noopWritable(), 1, false);205test('Throws stream error when childProcess.stdout Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 1, false);206test('Throws stream error when childProcess.stderr errors', testStreamError, destroyChildStream, noopWritable(), 2, false);207test('Throws stream error when childProcess.stderr Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 2, false);208test('Throws stream error when output childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopWritable(), 3, false);209test('Throws stream error when output childProcess.stdio[*] Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 3, false);210test('Throws stream error when input childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopReadable(), 3, false);211test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);212test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);213test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);214test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);215test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);216test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);217test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);218test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);219test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);220test('Throws stream error when childProcess.stdin errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 0, true);221test('Throws stream error when childProcess.stdin Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 0, true);222test('Throws stream error when childProcess.stdout errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 1, true);223test('Throws stream error when childProcess.stdout Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 1, true);224test('Throws stream error when childProcess.stderr errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 2, true);225test('Throws stream error when childProcess.stderr Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 2, true);226test('Throws stream error when output childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 3, true);227test('Throws stream error when output childProcess.stdio[*] Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 3, true);228test('Throws stream error when input childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 3, true);
added:test/stream/all.js+61 added
1import {getDefaultHighWaterMark} from 'node:stream';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {9 const {all} = await execa('noop-132.js', {all: true});10 t.is(all, '132');11});1213test('result.all is undefined unless opts.all is true', async t => {14 const {all} = await execa('noop.js');15 t.is(all, undefined);16});1718test('result.all is undefined if ignored', async t => {19 const {all} = await execa('noop.js', {stdio: 'ignore', all: true});20 t.is(all, undefined);21});2223const testAllProperties = async (t, options) => {24 const childProcess = execa('empty.js', {...options, all: true});25 t.is(childProcess.all.readableObjectMode, false);26 t.is(childProcess.all.readableHighWaterMark, getDefaultHighWaterMark(false));27 await childProcess;28};2930test('childProcess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});31test('childProcess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});32test('childProcess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});3334const testAllIgnore = async (t, streamName, otherStreamName) => {35 const childProcess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});36 t.is(childProcess[otherStreamName], null);37 t.not(childProcess[streamName], null);38 t.not(childProcess.all, null);39 t.is(childProcess.all.readableObjectMode, childProcess[streamName].readableObjectMode);40 t.is(childProcess.all.readableHighWaterMark, childProcess[streamName].readableHighWaterMark);4142 const result = await childProcess;43 t.is(result[otherStreamName], undefined);44 t.is(result[streamName], 'foobar');45 t.is(result.all, 'foobar');46};4748test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');49test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');5051test('can use all: true with stdout: ignore + stderr: ignore', async t => {52 const childProcess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});53 t.is(childProcess.stdout, null);54 t.is(childProcess.stderr, null);55 t.is(childProcess.all, undefined);5657 const {stdout, stderr, all} = await childProcess;58 t.is(stdout, undefined);59 t.is(stderr, undefined);60 t.is(all, undefined);61});
added:test/stream/child.js+118 added
1import {platform} from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';7import {infiniteGenerator} from '../helpers/generator.js';89setFixtureDir();1011const isWindows = platform === 'win32';1213const getStreamInputProcess = index => execa('stdin-fd.js', [`${index}`], index === 314 ? getStdio(3, [new Uint8Array(), infiniteGenerator])15 : {});16const getStreamOutputProcess = index => execa('noop-repeat.js', [`${index}`], index === 3 ? fullStdio : {});1718const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {19 t.is(exitCode, 0);20 t.is(signal, undefined);21 t.false(isTerminated);22 t.true(failed);23};2425const assertStreamOutputError = (t, index, {exitCode, signal, isTerminated, failed, stderr}) => {26 if (index !== 3) {27 t.is(exitCode, 1);28 }2930 t.is(signal, undefined);31 t.false(isTerminated);32 t.true(failed);3334 if (index === 1 && !isWindows) {35 t.true(stderr.includes('EPIPE'));36 }37};3839const testStreamInputAbort = async (t, index) => {40 const childProcess = getStreamInputProcess(index);41 childProcess.stdio[index].destroy();42 const error = await t.throwsAsync(childProcess, prematureClose);43 assertStreamInputError(t, error);44};4546test('Aborting stdin should not make the process exit', testStreamInputAbort, 0);47test('Aborting input stdio[*] should not make the process exit', testStreamInputAbort, 3);4849const testStreamOutputAbort = async (t, index) => {50 const childProcess = getStreamOutputProcess(index);51 childProcess.stdio[index].destroy();52 const error = await t.throwsAsync(childProcess);53 assertStreamOutputError(t, index, error);54};5556test('Aborting stdout should not make the process exit', testStreamOutputAbort, 1);57test('Aborting stderr should not make the process exit', testStreamOutputAbort, 2);58test('Aborting output stdio[*] should not make the process exit', testStreamOutputAbort, 3);5960const testStreamInputDestroy = async (t, index) => {61 const childProcess = getStreamInputProcess(index);62 const error = new Error('test');63 childProcess.stdio[index].destroy(error);64 t.is(await t.throwsAsync(childProcess), error);65 assertStreamInputError(t, error);66};6768test('Destroying stdin should not make the process exit', testStreamInputDestroy, 0);69test('Destroying input stdio[*] should not make the process exit', testStreamInputDestroy, 3);7071const testStreamOutputDestroy = async (t, index) => {72 const childProcess = getStreamOutputProcess(index);73 const error = new Error('test');74 childProcess.stdio[index].destroy(error);75 t.is(await t.throwsAsync(childProcess), error);76 assertStreamOutputError(t, index, error);77};7879test('Destroying stdout should not make the process exit', testStreamOutputDestroy, 1);80test('Destroying stderr should not make the process exit', testStreamOutputDestroy, 2);81test('Destroying output stdio[*] should not make the process exit', testStreamOutputDestroy, 3);8283const testStreamInputError = async (t, index) => {84 const childProcess = getStreamInputProcess(index);85 const error = new Error('test');86 const stream = childProcess.stdio[index];87 stream.emit('error', error);88 stream.end();89 t.is(await t.throwsAsync(childProcess), error);90 assertStreamInputError(t, error);91};9293test('Errors on stdin should not make the process exit', testStreamInputError, 0);94test('Errors on input stdio[*] should not make the process exit', testStreamInputError, 3);9596const testStreamOutputError = async (t, index) => {97 const childProcess = getStreamOutputProcess(index);98 const error = new Error('test');99 const stream = childProcess.stdio[index];100 stream.emit('error', error);101 t.is(await t.throwsAsync(childProcess), error);102 assertStreamOutputError(t, index, error);103};104105test('Errors on stdout should not make the process exit', testStreamOutputError, 1);106test('Errors on stderr should not make the process exit', testStreamOutputError, 2);107test('Errors on output stdio[*] should not make the process exit', testStreamOutputError, 3);108109const testWaitOnStreamEnd = async (t, index) => {110 const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);111 await setTimeout(100);112 childProcess.stdio[index].end('foobar');113 const {stdout} = await childProcess;114 t.is(stdout, 'foobar');115};116117test('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);118test('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);
added:test/stream/exit.js+78 added
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';78setFixtureDir();910const testBufferIgnore = async (t, index, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));12};1314test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);1718const testBufferNotRead = async (t, index, all) => {19 const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};2223test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);2728const testBufferRead = async (t, index, all) => {29 const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});30 const stream = all ? subprocess.all : subprocess.stdio[index];31 stream.resume();32 await t.notThrowsAsync(subprocess);33};3435test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);3940const testBufferExit = async (t, index, fixtureName, reject) => {41 const childProcess = execa(fixtureName, [`${index}`], {...fullStdio, reject});42 await setTimeout(100);43 const {stdio} = await childProcess;44 t.is(stdio[index], 'foobar');45};4647test('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);5657const testBufferDirect = async (t, index) => {58 const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);59 const data = await once(childProcess.stdio[index], 'data');60 t.is(data.toString().trim(), 'foobar');61 const result = await childProcess;62 t.is(result.stdio[index], 'foobar');63};6465test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);6869const testBufferDestroyOnEnd = async (t, index) => {70 const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);71 const result = await childProcess;72 t.is(result.stdio[index], 'foobar');73 t.true(childProcess.stdio[index].destroyed);74};7576test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
added:test/stream/max-buffer.js+108 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import getStream from 'get-stream';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio} from '../helpers/stdio.js';78setFixtureDir();910const maxBuffer = 10;1112const testMaxBufferSuccess = async (t, index, all) => {13 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));14};1516test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);17test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);18test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);19test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);2021test('maxBuffer uses killSignal', async t => {22 const {isTerminated, signal} = await t.throwsAsync(23 execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),24 {message: /maxBuffer exceeded/},25 );26 t.true(isTerminated);27 t.is(signal, 'SIGINT');28});2930const testMaxBufferLimit = async (t, index, all) => {31 const length = all ? maxBuffer * 2 : maxBuffer;32 const result = await t.throwsAsync(33 execa('max-buffer.js', [`${index}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),34 {message: /maxBuffer exceeded/},35 );36 t.is(all ? result.all : result.stdio[index], '.'.repeat(length));37};3839test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);40test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);41test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);42test('maxBuffer affects all', testMaxBufferLimit, 1, true);4344const testMaxBufferEncoding = async (t, index) => {45 const result = await t.throwsAsync(46 execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'buffer'}),47 );48 const stream = result.stdio[index];49 t.true(stream instanceof Uint8Array);50 t.is(Buffer.from(stream).toString(), '.'.repeat(maxBuffer));51};5253test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);54test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);55test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);5657const testMaxBufferHex = async (t, index) => {58 const halfMaxBuffer = maxBuffer / 2;59 const {stdio} = await t.throwsAsync(60 execa('max-buffer.js', [`${index}`, `${halfMaxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'hex'}),61 );62 t.is(stdio[index], Buffer.from('.'.repeat(halfMaxBuffer)).toString('hex'));63};6465test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);66test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);67test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);6869const testNoMaxBuffer = async (t, index) => {70 const subprocess = execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, buffer: false});71 const [result, output] = await Promise.all([72 subprocess,73 getStream(subprocess.stdio[index]),74 ]);75 t.is(result.stdio[index], undefined);76 t.is(output, '.'.repeat(maxBuffer));77};7879test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);80test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);81test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);8283const testNoMaxBufferOption = async (t, index) => {84 const length = maxBuffer + 1;85 const subprocess = execa('max-buffer.js', [`${index}`, `${length}`], {...fullStdio, maxBuffer, buffer: false});86 const [result, output] = await Promise.all([87 subprocess,88 getStream(subprocess.stdio[index]),89 ]);90 t.is(result.stdio[index], undefined);91 t.is(output, '.'.repeat(length));92};9394test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);95test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);96test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);9798const testMaxBufferAbort = async (t, index) => {99 const childProcess = execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});100 await Promise.all([101 t.throwsAsync(childProcess, {message: /maxBuffer exceeded/}),102 t.throwsAsync(getStream(childProcess.stdio[index]), {code: 'ABORT_ERR'}),103 ]);104};105106test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);107test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);108test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);
added:test/stream/no-buffer.js+111 added
1import {once} from 'node:events';2import test from 'ava';3import getStream from 'get-stream';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';89setFixtureDir();1011const testLateStream = async (t, index, all) => {12 const subprocess = execa('noop-fd-ipc.js', [`${index}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});13 await once(subprocess, 'message');14 const [output, allOutput] = await Promise.all([15 getStream(subprocess.stdio[index]),16 all ? getStream(subprocess.all) : undefined,17 subprocess,18 ]);1920 t.is(output, '');2122 if (all) {23 t.is(allOutput, '');24 }25};2627test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);28test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);29test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);30test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);3132const getFirstDataEvent = async stream => {33 const [output] = await once(stream, 'data');34 return output.toString();35};3637// eslint-disable-next-line max-params38const testIterationBuffer = async (t, index, buffer, useDataEvents, all) => {39 const subprocess = execa('noop-fd.js', [`${index}`, foobarString], {...fullStdio, buffer, all});40 const getOutput = useDataEvents ? getFirstDataEvent : getStream;41 const [result, output, allOutput] = await Promise.all([42 subprocess,43 getOutput(subprocess.stdio[index]),44 all ? getOutput(subprocess.all) : undefined,45 ]);4647 const expectedProcessResult = buffer ? foobarString : undefined;48 const expectedOutput = !buffer || useDataEvents ? foobarString : '';4950 t.is(result.stdio[index], expectedProcessResult);51 t.is(output, expectedOutput);5253 if (all) {54 t.is(result.all, expectedProcessResult);55 t.is(allOutput, expectedOutput);56 }57};5859test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63test('Cannot iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64test('Cannot iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65test('Cannot iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66test('Cannot iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);7576const testNoBufferStreamError = async (t, index, all) => {77 const subprocess = execa('noop-fd.js', [`${index}`], {...fullStdio, buffer: false, all});78 const stream = all ? subprocess.all : subprocess.stdio[index];79 const error = new Error('test');80 stream.destroy(error);81 t.is(await t.throwsAsync(subprocess), error);82};8384test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);8889test('buffer: false > promise resolves', async t => {90 await t.notThrowsAsync(execa('noop.js', {buffer: false}));91});9293test('buffer: false > promise rejects when process returns non-zero', async t => {94 const {exitCode} = await t.throwsAsync(execa('fail.js', {buffer: false}));95 t.is(exitCode, 2);96});9798const testStreamEnd = async (t, index, buffer) => {99 const subprocess = execa('wrong command', {...fullStdio, buffer});100 await Promise.all([101 t.throwsAsync(subprocess, {message: /wrong command/}),102 once(subprocess.stdio[index], 'end'),103 ]);104};105106test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);107test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);108test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);109test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);110test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);111test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);
added:test/stream/resolve.js+49 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const testIgnore = async (t, index, execaMethod) => {9 const result = await execaMethod('noop.js', getStdio(index, 'ignore'));10 t.is(result.stdio[index], undefined);11};1213test('stdout is undefined if ignored', testIgnore, 1, execa);14test('stderr is undefined if ignored', testIgnore, 2, execa);15test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);1920const testProcessEventsCleanup = async (t, fixtureName) => {21 const childProcess = execa(fixtureName, {reject: false});22 t.deepEqual(childProcess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);23 await childProcess;24 t.deepEqual(childProcess.eventNames(), []);25};2627test('childProcess listeners are cleaned up on success', testProcessEventsCleanup, 'empty.js');28test('childProcess listeners are cleaned up on failure', testProcessEventsCleanup, 'fail.js');2930test('Aborting stdout should not abort stderr nor all', async t => {31 const subprocess = execa('empty.js', {all: true});3233 subprocess.stdout.destroy();34 t.false(subprocess.stdout.readable);35 t.true(subprocess.stderr.readable);36 t.true(subprocess.all.readable);3738 await subprocess;3940 t.false(subprocess.stdout.readableEnded);41 t.is(subprocess.stdout.errored, null);42 t.true(subprocess.stdout.destroyed);43 t.true(subprocess.stderr.readableEnded);44 t.is(subprocess.stderr.errored, null);45 t.true(subprocess.stderr.destroyed);46 t.true(subprocess.all.readableEnded);47 t.is(subprocess.all.errored, null);48 t.true(subprocess.all.destroyed);49});
added:test/stream/wait.js+228 added
1import {platform} from 'node:process';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio, prematureClose} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {noopGenerator} from '../helpers/generator.js';9import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';1011setFixtureDir();1213const isWindows = platform === 'win32';1415const noop = () => {};1617const endOptionStream = ({stream}) => {18 stream.end();19};2021const destroyOptionStream = ({stream, error}) => {22 stream.destroy(error);23};2425const destroyChildStream = ({childProcess, index, error}) => {26 childProcess.stdio[index].destroy(error);27};2829const getStreamStdio = (index, stream, useTransform) => getStdio(index, [stream, useTransform ? noopGenerator(false) : 'pipe']);3031// eslint-disable-next-line max-params32const testStreamAbortWait = async (t, streamMethod, stream, index, useTransform) => {33 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));34 streamMethod({stream, childProcess, index});35 childProcess.stdin.end();36 await setImmediate();37 stream.destroy();3839 const {stdout} = await childProcess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Keeps running when stdin option is used and childProcess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45test('Keeps running when stdin option is used and childProcess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47test('Keeps running when stdin option is used and childProcess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48test('Keeps running when stdin option is used and childProcess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);5051// eslint-disable-next-line max-params52const testStreamAbortSuccess = async (t, streamMethod, stream, index, useTransform) => {53 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));54 streamMethod({stream, childProcess, index});55 childProcess.stdin.end();5657 const {stdout} = await childProcess;58 t.is(stdout, '');59 t.true(stream.destroyed);60};6162test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);63test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);64test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);65test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);66test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);67test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);68test('Passes when childProcess.stdout aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, false);69test('Passes when childProcess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, false);70test('Passes when childProcess.stderr aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, false);71test('Passes when childProcess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, false);72test('Passes when output childProcess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, false);73test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, false);74test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);75test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);76test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);77test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);78test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);79test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);80test('Passes when childProcess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, true);81test('Passes when childProcess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, true);82test('Passes when childProcess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, true);83test('Passes when childProcess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, true);84test('Passes when output childProcess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, true);85test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, true);8687// eslint-disable-next-line max-params88const testStreamAbortFail = async (t, streamMethod, stream, index, useTransform) => {89 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));90 streamMethod({stream, childProcess, index});91 if (index !== 0) {92 childProcess.stdin.end();93 }9495 const error = await t.throwsAsync(childProcess);96 t.like(error, {...prematureClose, exitCode: 0});97 t.true(stream.destroyed);98};99100test('Throws abort error when childProcess.stdin aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 0, false);101test('Throws abort error when childProcess.stdin Duplex aborts', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, false);102test('Throws abort error when input childProcess.stdio[*] aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 3, false);103test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);104test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);105test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);106test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);107test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);108test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);109test('Throws abort error when childProcess.stdin aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 0, true);110test('Throws abort error when childProcess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, true);111test('Throws abort error when input childProcess.stdio[*] aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 3, true);112test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);113test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);114test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);115test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);116test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);117test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118119// eslint-disable-next-line max-params120const testStreamEpipeSuccess = async (t, streamMethod, stream, index, useTransform) => {121 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));122 streamMethod({stream, childProcess, index});123 childProcess.stdin.end(foobarString);124125 const {stdio} = await childProcess;126 t.is(stdio[index], foobarString);127 t.true(stream.destroyed);128};129130test('Passes when stdout option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, false);131test('Passes when stderr option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, false);132test('Passes when output stdio[*] option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, false);133test('Passes when stdout option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, true);134test('Passes when stderr option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, true);135test('Passes when output stdio[*] option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, true);136137// eslint-disable-next-line max-params138const testStreamEpipeFail = async (t, streamMethod, stream, index, useTransform) => {139 const childProcess = execa('noop-stdin-fd.js', [`${index}`], getStreamStdio(index, stream, useTransform));140 streamMethod({stream, childProcess, index});141 await setImmediate();142 childProcess.stdin.end(foobarString);143144 const {exitCode, stdio, stderr} = await t.throwsAsync(childProcess);145 t.is(exitCode, 1);146 t.is(stdio[index], '');147 t.true(stream.destroyed);148 if (index !== 2 && !isWindows) {149 t.true(stderr.includes('EPIPE'));150 }151};152153test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);154test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);155test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);156test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);157test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);158test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);159test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);160test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);161test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);162test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);163test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);164test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);165test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);166test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);167test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);168test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);169test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);170test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);171test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);172test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);173test('Throws EPIPE when childProcess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, true);174test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, true);175test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, true);176test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, true);177178// eslint-disable-next-line max-params179const testStreamError = async (t, streamMethod, stream, index, useTransform) => {180 const childProcess = execa('empty.js', getStreamStdio(index, stream, useTransform));181 const error = new Error('test');182 streamMethod({stream, childProcess, index, error});183184 t.is(await t.throwsAsync(childProcess), error);185 const {exitCode, signal, isTerminated, failed} = error;186 t.is(exitCode, 0);187 t.is(signal, undefined);188 t.false(isTerminated);189 t.true(failed);190 t.true(stream.destroyed);191};192193test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);194test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);195test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);196test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);197test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);198test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);199test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);200test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);201test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);202test('Throws stream error when childProcess.stdin errors', testStreamError, destroyChildStream, noopReadable(), 0, false);203test('Throws stream error when childProcess.stdin Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 0, false);204test('Throws stream error when childProcess.stdout errors', testStreamError, destroyChildStream, noopWritable(), 1, false);205test('Throws stream error when childProcess.stdout Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 1, false);206test('Throws stream error when childProcess.stderr errors', testStreamError, destroyChildStream, noopWritable(), 2, false);207test('Throws stream error when childProcess.stderr Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 2, false);208test('Throws stream error when output childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopWritable(), 3, false);209test('Throws stream error when output childProcess.stdio[*] Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 3, false);210test('Throws stream error when input childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopReadable(), 3, false);211test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);212test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);213test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);214test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);215test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);216test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);217test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);218test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);219test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);220test('Throws stream error when childProcess.stdin errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 0, true);221test('Throws stream error when childProcess.stdin Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 0, true);222test('Throws stream error when childProcess.stdout errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 1, true);223test('Throws stream error when childProcess.stdout Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 1, true);224test('Throws stream error when childProcess.stderr errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 2, true);225test('Throws stream error when childProcess.stderr Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 2, true);226test('Throws stream error when output childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 3, true);227test('Throws stream error when output childProcess.stdio[*] Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 3, true);228test('Throws stream error when input childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 3, true);
added:test/async.js+36 added
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../index.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';56setFixtureDir();78const isWindows = process.platform === 'win32';910if (isWindows) {11 test('execa() - cmd file', async t => {12 const {stdout} = await execa('hello.cmd');13 t.is(stdout, 'Hello World');14 });1516 test('execa() - run cmd command', async t => {17 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18 t.is(stdout, 'Hello World');19 });20}2122test('skip throwing when using reject option', async t => {23 const {exitCode} = await execa('fail.js', {reject: false});24 t.is(exitCode, 2);25});2627test('skip throwing when using reject option in sync mode', t => {28 const {exitCode} = execaSync('fail.js', {reject: false});29 t.is(exitCode, 2);30});3132test('execa() returns a promise with pid', async t => {33 const subprocess = execa('noop.js', ['foo']);34 t.is(typeof subprocess.pid, 'number');35 await subprocess;36});
deleted:test/clone.js-150 removed
1import test from 'ava';2import {execa} from '../index.js';3import {setFixtureDir} from './helpers/fixtures-dir.js';4import {foobarString} from './helpers/input.js';56setFixtureDir();78const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {9 const childProcess = execa('empty.js');10 childProcess.emit('error', error);11 const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);12 t.is(originalMessage, expectedOriginalMessage);13 t.true(shortMessage.includes(expectedOriginalMessage));14 t.is(message, shortMessage);15};1617test('error instance can be null', testUnusualError, null);18test('error instance can be false', testUnusualError, false);19test('error instance can be a string', testUnusualError, 'test');20test('error instance can be a number', testUnusualError, 0);21test('error instance can be a BigInt', testUnusualError, 0n);22test('error instance can be a symbol', testUnusualError, Symbol('test'));23test('error instance can be a function', testUnusualError, () => {});24test('error instance can be an array', testUnusualError, ['test', 'test']);25// eslint-disable-next-line unicorn/error-message26test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27test('error instance can be undefined', testUnusualError, undefined, '');2829test('error instance can be a plain object', async t => {30 const childProcess = execa('empty.js');31 childProcess.emit('error', {message: foobarString});32 await t.throwsAsync(childProcess, {message: new RegExp(foobarString)});33});3435const runAndFail = (t, fixtureName, argument, error) => {36 const childProcess = execa(fixtureName, [argument]);37 childProcess.emit('error', error);38 return t.throwsAsync(childProcess);39};4041const runAndClone = async (t, initialError) => {42 const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43 t.is(previousError, initialError);4445 return runAndFail(t, 'empty.js', 'bar', previousError);46};4748const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49 const fixtureName = 'empty.js';50 const firstArgument = 'foo';5152 const previousArgument = await getPreviousArgument(t, fixtureName);53 const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);54 const error = await runAndFail(t, fixtureName, argument, previousError);55 const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;5657 t.not(error, previousError);58 t.is(error.command, `${fixtureName} ${argument}`);59 t.is(error.message, message);60 t.true(error.stack.includes(message));61 t.is(error.stack, previousError.stack.replace(firstArgument, argument));62 t.is(error.shortMessage, message);63 t.is(error.originalMessage, foobarString);64};6566test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68test('error string can be shared', testErrorCopy, () => foobarString);69test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');7172const testErrorCopyProperty = async (t, propertyName, isCopied) => {73 const propertyValue = 'test';74 const initialError = new Error(foobarString);75 initialError[propertyName] = propertyValue;7677 const error = await runAndClone(t, initialError);78 t.is(error[propertyName] === propertyValue, isCopied);79};8081test('error.code can be copied', testErrorCopyProperty, 'code', true);82test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84test('error.path can be copied', testErrorCopyProperty, 'path', true);85test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86test('error.address can be copied', testErrorCopyProperty, 'address', true);87test('error.port can be copied', testErrorCopyProperty, 'port', true);88test('error.info can be copied', testErrorCopyProperty, 'info', true);89test('error.other cannot be copied', testErrorCopyProperty, 'other', false);9091test('error.name can be copied', async t => {92 const initialError = new TypeError('test');93 const error = await runAndClone(t, initialError);94 t.deepEqual(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(initialError), 'name'), Object.getOwnPropertyDescriptor(error, 'name'));95});9697test('error.cause can be copied', async t => {98 const initialError = new Error('test', {cause: new Error('innerTest')});99 const error = await runAndClone(t, initialError);100 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'cause'), Object.getOwnPropertyDescriptor(error, 'cause'));101});102103test('error.errors can be copied', async t => {104 const initialError = new AggregateError([], 'test');105 const error = await runAndClone(t, initialError);106 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'errors'), Object.getOwnPropertyDescriptor(error, 'errors'));107});108109test('error.stack is set even if memoized', async t => {110 const message = 'test';111 const error = new Error(message);112 t.is(typeof error.stack, 'string');113114 const newMessage = 'newTest';115 error.message = newMessage;116 t.false(error.stack.includes(newMessage));117 error.message = message;118119 const childProcess = execa('empty.js');120 childProcess.emit('error', error);121 t.is(await t.throwsAsync(childProcess), error);122 t.is(error.message, `Command failed: empty.js\n${message}`);123 t.true(error.stack.startsWith(`Error: ${error.message}`));124});125126test('error.stack is set even if memoized with an unusual error.name', async t => {127 const childProcess = execa('empty.js');128 childProcess.stdin.destroy();129 const error = await t.throwsAsync(childProcess);130 t.is(error.message, 'Command failed with ERR_STREAM_PREMATURE_CLOSE: empty.js\nPremature close');131 t.true(error.stack.startsWith(`Error [ERR_STREAM_PREMATURE_CLOSE]: ${error.message}`));132});133134test('Cloned errors keep the stack trace', async t => {135 const message = 'test';136 const error = new Error(message);137 const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');138139 const childProcess = execa('empty.js');140 childProcess.emit('error', error);141 t.is(await t.throwsAsync(childProcess), error);142143 const secondChildProcess = execa('empty.js');144 secondChildProcess.emit('error', error);145 const secondError = await t.throwsAsync(secondChildProcess);146 t.not(secondError, error);147 t.is(secondError.message, `Command failed: empty.js\n${message}`);148 t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);149});150
deleted:test/cwd.js-103 removed
1import {mkdir, rmdir} from 'node:fs/promises';2import {relative, toNamespacedPath} from 'node:path';3import process from 'node:process';4import {pathToFileURL, fileURLToPath} from 'node:url';5import tempfile from 'tempfile';6import test from 'ava';7import {execa, execaSync} from '../index.js';8import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';910setFixtureDir();1112const isWindows = process.platform === 'win32';1314const testOptionCwdString = async (t, execaMethod) => {15 const cwd = '/';16 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd});17 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));18};1920test('The "cwd" option can be a string', testOptionCwdString, execa);21test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);2223const testOptionCwdUrl = async (t, execaMethod) => {24 const cwd = '/';25 const cwdUrl = pathToFileURL(cwd);26 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd: cwdUrl});27 t.is(toNamespacedPath(stdout), toNamespacedPath(cwd));28};2930test('The "cwd" option can be a URL', testOptionCwdUrl, execa);31test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);3233const testOptionCwdInvalid = (t, execaMethod) => {34 t.throws(() => {35 execaMethod('empty.js', {cwd: true});36 }, {message: /The "cwd" option must be a string or a file URL: true/});37};3839test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);40test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);4142const testErrorCwdDefault = async (t, execaMethod) => {43 const {cwd} = await execaMethod('empty.js');44 t.is(cwd, process.cwd());45};4647test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);4950// Windows does not allow removing a directory used as `cwd` of a running process51if (!isWindows) {52 const testCwdPreSpawn = async (t, execaMethod) => {53 const currentCwd = process.cwd();54 const filePath = tempfile();55 await mkdir(filePath);56 process.chdir(filePath);57 await rmdir(filePath);5859 try {60 t.throws(() => {61 execaMethod('empty.js');62 }, {message: /The current directory does not exist/});63 } finally {64 process.chdir(currentCwd);65 }66 };6768 test.serial('The "cwd" option default fails if current cwd is missing', testCwdPreSpawn, execa);69 test.serial('The "cwd" option default fails if current cwd is missing - sync', testCwdPreSpawn, execaSync);70}7172const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74const cwdNotDir = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};7576const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {77 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});78 t.true(failed);79 t.is(code, expectedCode);80 t.true(message.includes(expectedMessage));81 t.true(message.includes(cwd));82};8384test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);85test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);86test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);87test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);88test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDir, execa);89test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDir, execaSync);9091const successProperties = {fixtureName: 'empty.js', expectedFailed: false};92const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};9394const testErrorCwd = async (t, execaMethod, {fixtureName, expectedFailed}) => {95 const {failed, cwd} = await execaMethod(fixtureName, {cwd: relative('.', FIXTURES_DIR), reject: false});96 t.is(failed, expectedFailed);97 t.is(cwd, FIXTURES_DIR);98};99100test('result.cwd is defined', testErrorCwd, execa, successProperties);101test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);102test('error.cwd is defined', testErrorCwd, execa, errorProperties);103test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);
deleted:test/error.js-332 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../index.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';5import {fullStdio, getStdio} from './helpers/stdio.js';6import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';78const isWindows = process.platform === 'win32';910setFixtureDir();1112const TIMEOUT_REGEXP = /timed out after/;1314test('Return value properties are not missing and are ordered', async t => {15 const result = await execa('empty.js', {...fullStdio, all: true});16 t.deepEqual(Reflect.ownKeys(result), [17 'command',18 'escapedCommand',19 'cwd',20 'failed',21 'timedOut',22 'isCanceled',23 'isTerminated',24 'exitCode',25 'stdout',26 'stderr',27 'all',28 'stdio',29 'pipedFrom',30 ]);31});3233test('Error properties are not missing and are ordered', async t => {34 const error = await t.throwsAsync(execa('fail.js', {...fullStdio, all: true}));35 t.deepEqual(Reflect.ownKeys(error), [36 'stack',37 'message',38 'shortMessage',39 'originalMessage',40 'command',41 'escapedCommand',42 'cwd',43 'failed',44 'timedOut',45 'isCanceled',46 'isTerminated',47 'exitCode',48 'signal',49 'signalDescription',50 'stdout',51 'stderr',52 'all',53 'stdio',54 'pipedFrom',55 ]);56});5758const testEmptyErrorStdio = async (t, execaMethod) => {59 const {failed, stdout, stderr, stdio} = await execaMethod('fail.js', {reject: false});60 t.true(failed);61 t.is(stdout, '');62 t.is(stderr, '');63 t.deepEqual(stdio, [undefined, '', '']);64};6566test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);67test('empty error.stdout/stderr/stdio - sync', testEmptyErrorStdio, execaSync);6869const testUndefinedErrorStdio = async (t, execaMethod) => {70 const {stdout, stderr, stdio} = await execaMethod('empty.js', {stdio: 'ignore'});71 t.is(stdout, undefined);72 t.is(stderr, undefined);73 t.deepEqual(stdio, [undefined, undefined, undefined]);74};7576test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);77test('undefined error.stdout/stderr/stdio - sync', testUndefinedErrorStdio, execaSync);7879const testEmptyAll = async (t, options, expectedValue) => {80 const {all} = await t.throwsAsync(execa('fail.js', options));81 t.is(all, expectedValue);82};8384test('empty error.all', testEmptyAll, {all: true}, '');85test('undefined error.all', testEmptyAll, {}, undefined);86test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined);8788test('empty error.stdio[0] even with input', async t => {89 const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));90 t.is(stdio[0], undefined);91});9293// `error.code` is OS-specific here94const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);9596test('stdout/stderr/stdio on process spawning errors', async t => {97 const {code, stdout, stderr, stdio} = await t.throwsAsync(execa('empty.js', {uid: -1}));98 t.true(SPAWN_ERROR_CODES.has(code));99 t.is(stdout, undefined);100 t.is(stderr, undefined);101 t.deepEqual(stdio, [undefined, undefined, undefined]);102});103104test('stdout/stderr/all/stdio on process spawning errors - sync', t => {105 const {code, stdout, stderr, stdio} = t.throws(() => {106 execaSync('empty.js', {uid: -1});107 });108 t.true(SPAWN_ERROR_CODES.has(code));109 t.is(stdout, undefined);110 t.is(stderr, undefined);111 t.deepEqual(stdio, [undefined, undefined, undefined]);112});113114const testErrorOutput = async (t, execaMethod) => {115 const {failed, stdout, stderr, stdio} = await execaMethod('echo-fail.js', {...fullStdio, reject: false});116 t.true(failed);117 t.is(stdout, 'stdout');118 t.is(stderr, 'stderr');119 t.deepEqual(stdio, [undefined, 'stdout', 'stderr', 'fd3']);120};121122test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);123test('error.stdout/stderr/stdio is defined - sync', testErrorOutput, execaSync);124125test('exitCode is 0 on success', async t => {126 const {exitCode} = await execa('noop.js', ['foo']);127 t.is(exitCode, 0);128});129130const testExitCode = async (t, expectedExitCode) => {131 const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(132 execa('exit.js', [`${expectedExitCode}`]),133 );134 t.is(exitCode, expectedExitCode);135 t.is(originalMessage, '');136 t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);137 t.is(message, shortMessage);138};139140test('exitCode is 2', testExitCode, 2);141test('exitCode is 3', testExitCode, 3);142test('exitCode is 4', testExitCode, 4);143144test('error.message contains the command', async t => {145 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});146});147148const testStdioMessage = async (t, encoding, all, objectMode) => {149 const {message} = await t.throwsAsync(execa('echo-fail.js', {...getStdio(1, noopGenerator(objectMode), 4), encoding, all}));150 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';151 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));152};153154test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);155test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);156test('error.message contains all if available', testStdioMessage, 'utf8', true, false);157test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);158test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);159test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);160test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);161test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);162163const testPartialIgnoreMessage = async (t, index, stdioOption, output) => {164 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(index, stdioOption, 4)));165 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));166};167168test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');169test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');170test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');171test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');172173const testFullIgnoreMessage = async (t, options, resultProperty) => {174 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));175 t.false(message.includes('stderr'));176 t.false(message.includes('stdout'));177 t.false(message.includes('fd3'));178};179180test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');181test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');182183const testErrorMessageConsistent = async (t, stdout) => {184 const {message} = await t.throwsAsync(execa('noop-both-fail.js', [stdout, 'stderr']));185 t.true(message.endsWith(`noop-both-fail.js ${stdout} stderr\n\nstderr\n\nstdout`));186};187188test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');189test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');190191test('Original error.message is kept', async t => {192 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));193 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');194});195196test('failed is false on success', async t => {197 const {failed} = await execa('noop.js', ['foo']);198 t.false(failed);199});200201test('failed is true on failure', async t => {202 const {failed} = await t.throwsAsync(execa('fail.js'));203 t.true(failed);204});205206test('error.isTerminated is true if process was killed directly', async t => {207 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});208209 subprocess.kill();210211 const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});212 t.true(isTerminated);213 t.is(signal, 'SIGINT');214 t.is(originalMessage, '');215 t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');216 t.is(message, shortMessage);217});218219test('error.isTerminated is true if process was killed indirectly', async t => {220 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});221222 process.kill(subprocess.pid, 'SIGINT');223224 // `process.kill()` is emulated by Node.js on Windows225 if (isWindows) {226 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});227 t.is(isTerminated, false);228 t.is(signal, undefined);229 } else {230 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});231 t.is(isTerminated, true);232 t.is(signal, 'SIGINT');233 }234});235236test('result.isTerminated is false if not killed', async t => {237 const {isTerminated} = await execa('noop.js');238 t.false(isTerminated);239});240241test('result.isTerminated is false if not killed and childProcess.kill() was called', async t => {242 const subprocess = execa('noop.js');243 subprocess.kill(0);244 t.true(subprocess.killed);245 const {isTerminated} = await subprocess;246 t.false(isTerminated);247});248249test('result.isTerminated is false if not killed, in sync mode', t => {250 const {isTerminated} = execaSync('noop.js');251 t.false(isTerminated);252});253254test('result.isTerminated is false on process error', async t => {255 const {isTerminated} = await t.throwsAsync(execa('wrong command'));256 t.false(isTerminated);257});258259test('result.isTerminated is false on process error, in sync mode', t => {260 const {isTerminated} = t.throws(() => {261 execaSync('wrong command');262 });263 t.false(isTerminated);264});265266if (!isWindows) {267 test('error.signal is SIGINT', async t => {268 const subprocess = execa('forever.js');269270 process.kill(subprocess.pid, 'SIGINT');271272 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});273 t.is(signal, 'SIGINT');274 });275276 test('error.signalDescription is defined', async t => {277 const subprocess = execa('forever.js');278279 process.kill(subprocess.pid, 'SIGINT');280281 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});282 t.is(signalDescription, 'User interruption with CTRL-C');283 });284285 test('error.signal is SIGTERM', async t => {286 const subprocess = execa('forever.js');287288 process.kill(subprocess.pid, 'SIGTERM');289290 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});291 t.is(signal, 'SIGTERM');292 });293294 test('error.signal uses killSignal', async t => {295 const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: TIMEOUT_REGEXP}));296 t.is(signal, 'SIGINT');297 });298299 test('exitCode is undefined on signal termination', async t => {300 const subprocess = execa('forever.js');301302 process.kill(subprocess.pid);303304 const {exitCode} = await t.throwsAsync(subprocess);305 t.is(exitCode, undefined);306 });307}308309test('result.signal is undefined for successful execution', async t => {310 const {signal} = await execa('noop.js');311 t.is(signal, undefined);312});313314test('result.signal is undefined if process failed, but was not killed', async t => {315 const {signal} = await t.throwsAsync(execa('fail.js'));316 t.is(signal, undefined);317});318319test('result.signalDescription is undefined for successful execution', async t => {320 const {signalDescription} = await execa('noop.js');321 t.is(signalDescription, undefined);322});323324test('error.code is undefined on success', async t => {325 const {code} = await execa('noop.js');326 t.is(code, undefined);327});328329test('error.code is defined on failure if applicable', async t => {330 const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));331 t.is(code, 'ERR_INVALID_ARG_TYPE');332});
deleted:test/escape.js-52 removed
1import test from 'ava';2import {execa, execaSync} from '../index.js';3import {setFixtureDir} from './helpers/fixtures-dir.js';45setFixtureDir();67const testResultCommand = async (t, expected, ...args) => {8 const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));9 t.is(failCommand, `fail.js${expected}`);1011 const {command} = await execa('noop.js', args);12 t.is(command, `noop.js${expected}`);13};1415testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;1617test(testResultCommand, ' foo bar', 'foo', 'bar');18test(testResultCommand, ' baz quz', 'baz', 'quz');19test(testResultCommand, '');2021const testEscapedCommand = async (t, expected, args) => {22 const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));23 t.is(failEscapedCommand, `fail.js ${expected}`);2425 const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26 execaSync('fail.js', args);27 });28 t.is(failEscapedCommandSync, `fail.js ${expected}`);2930 const {escapedCommand} = await execa('noop.js', args);31 t.is(escapedCommand, `noop.js ${expected}`);3233 const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);34 t.is(escapedCommandSync, `noop.js ${expected}`);35};3637testEscapedCommand.title = (message, expected) => `result.escapedCommand is: ${JSON.stringify(expected)}`;3839test(testEscapedCommand, 'foo bar', ['foo', 'bar']);40test(testEscapedCommand, '"foo bar"', ['foo bar']);41test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);42test(testEscapedCommand, '"*"', ['*']);4344test('allow commands with spaces and no array arguments', async t => {45 const {stdout} = await execa('command with space.js');46 t.is(stdout, '');47});4849test('allow commands with spaces and array arguments', async t => {50 const {stdout} = await execa('command with space.js', ['foo', 'bar']);51 t.is(stdout, 'foo\nbar');52});
deleted:test/kill.js-517 removed
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout, setImmediate} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa, execaSync} from '../index.js';9import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';10import {assertMaxListeners} from './helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const spawnNoKillable = async (forceKillAfterDelay, options) => {17 const subprocess = execa('no-killable.js', {18 ipc: true,19 forceKillAfterDelay,20 ...options,21 });22 await pEvent(subprocess, 'message');23 return {subprocess};24};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2930test('kill("SIGKILL") should terminate cleanly', async t => {31 const {subprocess} = await spawnNoKillable();3233 subprocess.kill('SIGKILL');3435 const {isTerminated, signal} = await t.throwsAsync(subprocess);36 t.true(isTerminated);37 t.is(signal, 'SIGKILL');38});3940const testInvalidForceKill = async (t, forceKillAfterDelay) => {41 t.throws(() => {42 execa('empty.js', {forceKillAfterDelay});43 }, {instanceOf: TypeError, message: /non-negative integer/});44};4546test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);47test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4849// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).50// Therefore, this feature and those tests must be different on Windows.51if (isWindows) {52 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53 const {subprocess} = await spawnNoKillable(1);54 subprocess.kill();5556 const {isTerminated, signal} = await t.throwsAsync(subprocess);57 t.true(isTerminated);58 t.is(signal, 'SIGTERM');59 });60} else {61 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {62 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);6364 subprocess.kill(killArgument);6566 await setTimeout(6e3);67 t.true(isRunning(subprocess.pid));68 subprocess.kill('SIGKILL');6970 const {isTerminated, signal} = await t.throwsAsync(subprocess);71 t.true(isTerminated);72 t.is(signal, 'SIGKILL');73 };7475 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);76 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');77 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});78 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});7980 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {81 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8283 subprocess.kill(killArgument);8485 const {isTerminated, signal} = await t.throwsAsync(subprocess);86 t.true(isTerminated);87 t.is(signal, 'SIGKILL');88 };8990 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);91 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);92 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);93 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');94 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});95 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});96 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));97 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});9899 test('`forceKillAfterDelay` works with the "signal" option', async t => {100 const abortController = new AbortController();101 const subprocess = spawnNoKillableSimple({signal: abortController.signal});102 await once(subprocess, 'spawn');103 abortController.abort();104 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);105 t.true(isTerminated);106 t.is(signal, 'SIGKILL');107 t.true(isCanceled);108 });109110 test('`forceKillAfterDelay` works with the "timeout" option', async t => {111 const subprocess = spawnNoKillableSimple({timeout: 1});112 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);113 t.true(isTerminated);114 t.is(signal, 'SIGKILL');115 t.true(timedOut);116 });117118 test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {119 const subprocess = spawnNoKillableOutput({maxBuffer: 1});120 const {isTerminated, signal} = await t.throwsAsync(subprocess);121 t.true(isTerminated);122 t.is(signal, 'SIGKILL');123 });124125 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {126 const checkMaxListeners = assertMaxListeners(t);127128 const subprocess = spawnNoKillableSimple();129 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {130 subprocess.kill();131 }132133 const {isTerminated, signal} = await t.throwsAsync(subprocess);134 t.true(isTerminated);135 t.is(signal, 'SIGKILL');136137 checkMaxListeners();138 });139140 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {141 const subprocess = spawnNoKillableSimple();142 subprocess.kill();143 subprocess.kill();144145 const {isTerminated, signal} = await t.throwsAsync(subprocess);146 t.true(isTerminated);147 t.is(signal, 'SIGKILL');148 });149}150151test('Can call `.kill()` multiple times', async t => {152 const subprocess = execa('forever.js');153 subprocess.kill();154 subprocess.kill();155156 const {isTerminated, signal} = await t.throwsAsync(subprocess);157 t.true(isTerminated);158 t.is(signal, 'SIGTERM');159});160161test('execa() returns a promise with kill()', async t => {162 const subprocess = execa('noop.js', ['foo']);163 t.is(typeof subprocess.kill, 'function');164 await subprocess;165});166167test('timeout kills the process if it times out', async t => {168 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));169 t.true(isTerminated);170 t.is(signal, 'SIGTERM');171 t.true(timedOut);172 t.is(originalMessage, '');173 t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');174 t.is(message, shortMessage);175});176177test('timeout kills the process if it times out, in sync mode', async t => {178 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {179 execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});180 });181 t.true(isTerminated);182 t.is(signal, 'SIGTERM');183 t.true(timedOut);184 t.is(originalMessage, 'spawnSync node ETIMEDOUT');185 t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);186 t.is(message, shortMessage);187});188189test('timeout does not kill the process if it does not time out', async t => {190 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});191 t.false(timedOut);192});193194test('timeout uses killSignal', async t => {195 const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));196 t.true(isTerminated);197 t.is(signal, 'SIGINT');198 t.true(timedOut);199});200201const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;202203const testTimeoutValidation = (t, timeout, execaMethod) => {204 t.throws(() => {205 execaMethod('empty.js', {timeout});206 }, {message: INVALID_TIMEOUT_REGEXP});207};208209test('timeout must not be negative', testTimeoutValidation, -1, execa);210test('timeout must be an integer', testTimeoutValidation, false, execa);211test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);212test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);213214test('timedOut is false if timeout is undefined', async t => {215 const {timedOut} = await execa('noop.js');216 t.false(timedOut);217});218219test('timedOut is false if timeout is 0', async t => {220 const {timedOut} = await execa('noop.js', {timeout: 0});221 t.false(timedOut);222});223224test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {225 const {timedOut} = execaSync('noop.js');226 t.false(timedOut);227});228229test('timedOut is true if the timeout happened after a different error occurred', async t => {230 const childProcess = execa('forever.js', {timeout: 1e3});231 const error = new Error('test');232 childProcess.emit('error', error);233 t.is(await t.throwsAsync(childProcess), error);234 t.true(error.timedOut);235});236237// When child process exits before parent process238const spawnAndExit = async (t, cleanup, detached) => {239 await t.notThrowsAsync(execa('nested.js', [JSON.stringify({cleanup, detached}), 'noop.js']));240};241242test('spawnAndExit', spawnAndExit, false, false);243test('spawnAndExit cleanup', spawnAndExit, true, false);244test('spawnAndExit detached', spawnAndExit, false, true);245test('spawnAndExit cleanup detached', spawnAndExit, true, true);246247// When parent process exits before child process248const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {249 const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: 'ignore', ipc: true});250251 const pid = await pEvent(subprocess, 'message');252 t.true(Number.isInteger(pid));253 t.true(isRunning(pid));254255 process.kill(subprocess.pid, signal);256257 await t.throwsAsync(subprocess);258 t.false(isRunning(subprocess.pid));259260 if (isKilled) {261 await Promise.race([262 setTimeout(1e4, undefined, {ref: false}),263 pollForProcessExit(pid),264 ]);265 t.is(isRunning(pid), false);266 } else {267 t.is(isRunning(pid), true);268 process.kill(pid, 'SIGKILL');269 }270};271272const pollForProcessExit = async pid => {273 while (isRunning(pid)) {274 // eslint-disable-next-line no-await-in-loop275 await setTimeout(100);276 }277};278279// Without `options.cleanup`:280// - on Windows subprocesses are killed if `options.detached: false`, but not281// if `options.detached: true`282// - on Linux subprocesses are never killed regardless of `options.detached`283// With `options.cleanup`, subprocesses are always killed284// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled285test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);286test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);287test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);288test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);289test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);290test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);291test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);292test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);293294// See #128295test('removes exit handler on exit', async t => {296 // @todo this relies on `signal-exit` internals297 const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;298299 const subprocess = execa('noop.js');300 const listener = exitListeners.at(-1);301302 await subprocess;303 t.false(exitListeners.includes(listener));304});305306test('result.isCanceled is false when abort isn\'t called (success)', async t => {307 const {isCanceled} = await execa('noop.js');308 t.false(isCanceled);309});310311test('result.isCanceled is false when abort isn\'t called (failure)', async t => {312 const {isCanceled} = await t.throwsAsync(execa('fail.js'));313 t.false(isCanceled);314});315316test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {317 const {isCanceled} = execaSync('noop.js');318 t.false(isCanceled);319});320321test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {322 const {isCanceled} = t.throws(() => {323 execaSync('fail.js');324 });325 t.false(isCanceled);326});327328test('calling abort is considered a signal termination', async t => {329 const abortController = new AbortController();330 const subprocess = execa('forever.js', {signal: abortController.signal});331 await once(subprocess, 'spawn');332 abortController.abort();333 const {isTerminated, signal} = await t.throwsAsync(subprocess);334 t.true(isTerminated);335 t.is(signal, 'SIGTERM');336});337338test('error.isCanceled is true when abort is used', async t => {339 const abortController = new AbortController();340 const subprocess = execa('noop.js', {signal: abortController.signal});341 abortController.abort();342 const {isCanceled} = await t.throwsAsync(subprocess);343 t.true(isCanceled);344});345346test('error.isCanceled is false when kill method is used', async t => {347 const abortController = new AbortController();348 const subprocess = execa('noop.js', {signal: abortController.signal});349 subprocess.kill();350 const {isCanceled} = await t.throwsAsync(subprocess);351 t.false(isCanceled);352});353354test('calling abort throws an error with message "Command was canceled"', async t => {355 const abortController = new AbortController();356 const subprocess = execa('noop.js', {signal: abortController.signal});357 abortController.abort();358 await t.throwsAsync(subprocess, {message: /Command was canceled/});359});360361test('calling abort twice should show the same behaviour as calling it once', async t => {362 const abortController = new AbortController();363 const subprocess = execa('noop.js', {signal: abortController.signal});364 abortController.abort();365 abortController.abort();366 const {isCanceled} = await t.throwsAsync(subprocess);367 t.true(isCanceled);368});369370test('calling abort on a successfully completed process does not make result.isCanceled true', async t => {371 const abortController = new AbortController();372 const subprocess = execa('noop.js', {signal: abortController.signal});373 const result = await subprocess;374 abortController.abort();375 t.false(result.isCanceled);376});377378test('child process errors are handled before spawn', async t => {379 const subprocess = execa('forever.js');380 const error = new Error('test');381 subprocess.emit('error', error);382 subprocess.kill();383 const thrownError = await t.throwsAsync(subprocess);384 t.is(thrownError, error);385 t.is(thrownError.exitCode, undefined);386 t.is(thrownError.signal, undefined);387 t.false(thrownError.isTerminated);388});389390test('child process errors are handled after spawn', async t => {391 const subprocess = execa('forever.js');392 await once(subprocess, 'spawn');393 const error = new Error('test');394 subprocess.emit('error', error);395 subprocess.kill();396 const thrownError = await t.throwsAsync(subprocess);397 t.is(thrownError, error);398 t.is(thrownError.exitCode, undefined);399 t.is(thrownError.signal, 'SIGTERM');400 t.true(thrownError.isTerminated);401});402403test('child process double errors are handled after spawn', async t => {404 const abortController = new AbortController();405 const subprocess = execa('forever.js', {signal: abortController.signal});406 await once(subprocess, 'spawn');407 const error = new Error('test');408 subprocess.emit('error', error);409 await setImmediate();410 abortController.abort();411 const thrownError = await t.throwsAsync(subprocess);412 t.is(thrownError, error);413 t.is(thrownError.exitCode, undefined);414 t.is(thrownError.signal, 'SIGTERM');415 t.true(thrownError.isTerminated);416});417418test('child process errors use killSignal', async t => {419 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});420 await once(subprocess, 'spawn');421 const error = new Error('test');422 subprocess.emit('error', error);423 subprocess.kill();424 const thrownError = await t.throwsAsync(subprocess);425 t.is(thrownError, error);426 t.true(thrownError.isTerminated);427 t.is(thrownError.signal, 'SIGINT');428});429430const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {431 const subprocess = execa('empty.js');432 const message = secondKillArgument instanceof Error || secondKillArgument === undefined433 ? /error instance or a signal name/434 : /second argument is optional/;435 t.throws(() => {436 subprocess.kill(killArgument, secondKillArgument);437 }, {message});438 await subprocess;439};440441test('Cannot call .kill(null)', testInvalidKillArgument, null);442test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);443test('Cannot call .kill(true)', testInvalidKillArgument, true);444test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});445test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);446test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);447test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);448test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));449450test('.kill(error) propagates error', async t => {451 const subprocess = execa('forever.js');452 const originalMessage = 'test';453 const error = new Error(originalMessage);454 t.true(subprocess.kill(error));455 t.is(await t.throwsAsync(subprocess), error);456 t.is(error.exitCode, undefined);457 t.is(error.signal, 'SIGTERM');458 t.true(error.isTerminated);459 t.is(error.originalMessage, originalMessage);460 t.true(error.message.includes(originalMessage));461 t.true(error.message.includes('was killed with SIGTERM'));462 t.true(error.stack.includes(import.meta.url));463});464465test('.kill(error) uses killSignal', async t => {466 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});467 const error = new Error('test');468 subprocess.kill(error);469 t.is(await t.throwsAsync(subprocess), error);470 t.is(error.signal, 'SIGINT');471});472473test('.kill(signal, error) uses signal', async t => {474 const subprocess = execa('forever.js');475 const error = new Error('test');476 subprocess.kill('SIGINT', error);477 t.is(await t.throwsAsync(subprocess), error);478 t.is(error.signal, 'SIGINT');479});480481test('.kill(error) is a noop if process already exited', async t => {482 const subprocess = execa('empty.js');483 await subprocess;484 t.false(isRunning(subprocess.pid));485 t.false(subprocess.kill(new Error('test')));486});487488test('.kill(error) terminates but does not change the error if the process already errored but did not exit yet', async t => {489 const subprocess = execa('forever.js');490 const error = new Error('first');491 subprocess.stdout.destroy(error);492 await setImmediate();493 const secondError = new Error('second');494 t.true(subprocess.kill(secondError));495 t.is(await t.throwsAsync(subprocess), error);496 t.is(error.exitCode, undefined);497 t.is(error.signal, 'SIGTERM');498 t.true(error.isTerminated);499 t.false(error.message.includes(secondError.message));500});501502test('.kill(error) twice in a row', async t => {503 const subprocess = execa('forever.js');504 const error = new Error('first');505 subprocess.kill(error);506 const secondError = new Error('second');507 subprocess.kill(secondError);508 t.is(await t.throwsAsync(subprocess), error);509 t.false(error.message.includes(secondError.message));510});511512test('.kill(error) does not emit the "error" event', async t => {513 const subprocess = execa('forever.js');514 const error = new Error('test');515 subprocess.kill(error);516 t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);517});
deleted:test/node.js-249 removed
1import {dirname, relative} from 'node:path';2import process from 'node:process';3import {pathToFileURL} from 'node:url';4import test from 'ava';5import getNode from 'get-node';6import {pEvent} from 'p-event';7import {execa, execaSync, execaNode} from '../index.js';8import {FIXTURES_DIR} from './helpers/fixtures-dir.js';9import {identity, fullStdio} from './helpers/stdio.js';10import {foobarString} from './helpers/input.js';1112process.chdir(FIXTURES_DIR);1314const runWithNodeOption = (file, args, options) => Array.isArray(args)15 ? execa(file, args, {...options, node: true})16 : execa(file, {...options, node: true});17const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18 ? execaSync(file, args, {...options, node: true})19 : execaSync(file, {...options, node: true});20const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2122const testNodeSuccess = async (t, execaMethod) => {23 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);24 t.is(exitCode, 0);25 t.is(stdout, foobarString);26};2728test('execaNode() succeeds', testNodeSuccess, execaNode);29test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);3132test('execaNode() cannot set the "node" option to false', t => {33 t.throws(() => {34 execaNode('empty.js', {node: false});35 }, {message: /The "node" option cannot be false/});36});3738const testDoubleNode = (t, nodePath, execaMethod) => {39 t.throws(() => {40 execaMethod(nodePath, ['noop.js']);41 }, {message: /does not need to be "node"/});42};4344test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);45test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);46test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);47test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);48test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);49test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);5051const getNodePath = async () => {52 const {path} = await getNode(TEST_NODE_VERSION);53 return path;54};5556const TEST_NODE_VERSION = '16.0.0';5758const testNodePath = async (t, execaMethod, mapPath) => {59 const nodePath = mapPath(await getNodePath());60 const {stdout} = await execaMethod('--version', [], {nodePath});61 t.is(stdout, `v${TEST_NODE_VERSION}`);62};6364test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);7071const testNodePathDefault = async (t, execaMethod) => {72 const {stdout} = await execaMethod('--version');73 t.is(stdout, process.version);74};7576test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);7980const testNodePathInvalid = (t, execaMethod) => {81 t.throws(() => {82 execaMethod('noop.js', [], {nodePath: true});83 }, {message: /The "nodePath" option must be a string or a file URL/});84};8586test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);8990const testFormerNodePath = (t, execaMethod) => {91 t.throws(() => {92 execaMethod('noop.js', [], {execPath: process.execPath});93 }, {message: /The "execPath" option has been removed/});94};9596test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99100const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];101102const testChildNodePath = async (t, mapPath) => {103 const nodePath = mapPath(await getNodePath());104 const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath});105 t.true(stdout.includes(TEST_NODE_VERSION));106};107108test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);110111test('The "nodePath" option defaults to the current Node.js binary in the child process', async t => {112 const {stdout} = await execa(...nodePathArguments, {preferLocal: true});113 t.true(stdout.includes(dirname(process.execPath)));114});115116test.serial('The "nodePath" option requires "preferLocal: true" to impact the child process', async t => {117 const nodePath = await getNodePath();118 const {stdout} = await execa(...nodePathArguments, {nodePath});119 t.false(stdout.includes(TEST_NODE_VERSION));120});121122test.serial('The "nodePath" option is relative to "cwd" when used in the child process', async t => {123 const nodePath = await getNodePath();124 const cwd = dirname(dirname(nodePath));125 const relativeExecPath = relative(cwd, nodePath);126 const {stdout} = await execa(...nodePathArguments, {preferLocal: true, nodePath: relativeExecPath, cwd});127 t.true(stdout.includes(TEST_NODE_VERSION));128});129130const testCwdNodePath = async (t, execaMethod) => {131 const nodePath = await getNodePath();132 const cwd = dirname(dirname(nodePath));133 const relativeExecPath = relative(cwd, nodePath);134 const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});135 t.is(stdout, `v${TEST_NODE_VERSION}`);136};137138test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141142const testNodeOptions = async (t, execaMethod) => {143 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144 t.is(stdout, process.version);145};146147test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150151const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(152 'node',153 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],154 {...fullStdio, cwd: FIXTURES_DIR},155);156157const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {158 const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');159 t.is(stdout, foobarString);160 t.is(stdio[3], '');161};162163test('The "nodeOptions" option removes --inspect without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');164test('The "nodeOptions" option removes --inspect without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');165test('The "nodeOptions" option removes --inspect with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');166test('The "nodeOptions" option removes --inspect with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');167test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');168test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');169test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');170test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');171172const testInspectDifferentPort = async (t, execaMethod) => {173 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');174 t.is(stdout, foobarString);175 t.true(stdio[3].includes('Debugger listening'));176};177178test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - execaNode()', testInspectDifferentPort, 'execaNode');179test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - "node" option', testInspectDifferentPort, 'nodeOption');180181const testInspectSamePort = async (t, execaMethod) => {182 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');183 t.is(stdout, foobarString);184 t.true(stdio[3].includes('address already in use'));185};186187test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - execaNode()', testInspectSamePort, 'execaNode');188test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - "node" option', testInspectSamePort, 'nodeOption');189190const testIpc = async (t, execaMethod, options) => {191 const subprocess = execaMethod('send.js', [], options);192 await pEvent(subprocess, 'message');193 subprocess.send(foobarString);194 const {stdout, stdio} = await subprocess;195 t.is(stdout, foobarString);196 t.is(stdio.length, 4);197 t.is(stdio[3], undefined);198};199200test('execaNode() adds an ipc channel', testIpc, execaNode, {});201test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});202test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});203test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});204test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});205test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});206test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});207208test('No ipc channel is added by default', async t => {209 const {stdio} = await t.throwsAsync(execa('node', ['send.js']), {message: /process.send is not a function/});210 t.is(stdio.length, 3);211});212213const testDisableIpc = async (t, execaMethod) => {214 const {failed, message, stdio} = await execaMethod('send.js', [], {ipc: false, reject: false});215 t.true(failed);216 t.true(message.includes('process.send is not a function'));217 t.is(stdio.length, 3);218};219220test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);221test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);222test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);223224const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;225226const testNoIpcSync = (t, node) => {227 t.throws(() => {228 execaSync('node', ['send.js'], {ipc: true, node});229 }, {message: NO_IPC_MESSAGE});230};231232test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);233test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);234235test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {236 t.throws(() => {237 execaSync('send.js', {ipc: true, node: true});238 }, {message: NO_IPC_MESSAGE});239});240241const testNoShell = async (t, execaMethod) => {242 const {failed, message} = await execaMethod('node --version', [], {shell: true, reject: false});243 t.true(failed);244 t.true(message.includes('MODULE_NOT_FOUND'));245};246247test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);248test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);249test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);
deleted:test/stream.js-493 removed
1import {Buffer} from 'node:buffer';2import {once} from 'node:events';3import {platform} from 'node:process';4import {getDefaultHighWaterMark} from 'node:stream';5import {setTimeout} from 'node:timers/promises';6import test from 'ava';7import getStream from 'get-stream';8import {execa, execaSync} from '../index.js';9import {setFixtureDir} from './helpers/fixtures-dir.js';10import {fullStdio, getStdio, prematureClose} from './helpers/stdio.js';11import {foobarString} from './helpers/input.js';12import {infiniteGenerator} from './helpers/generator.js';1314setFixtureDir();1516const isWindows = platform === 'win32';1718test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {19 const {all} = await execa('noop-132.js', {all: true});20 t.is(all, '132');21});2223test('result.all is undefined unless opts.all is true', async t => {24 const {all} = await execa('noop.js');25 t.is(all, undefined);26});2728test('result.all is undefined if ignored', async t => {29 const {all} = await execa('noop.js', {stdio: 'ignore', all: true});30 t.is(all, undefined);31});3233const testAllProperties = async (t, options) => {34 const childProcess = execa('empty.js', {...options, all: true});35 t.is(childProcess.all.readableObjectMode, false);36 t.is(childProcess.all.readableHighWaterMark, getDefaultHighWaterMark(false));37 await childProcess;38};3940test('childProcess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});41test('childProcess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});42test('childProcess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});4344const testAllIgnore = async (t, streamName, otherStreamName) => {45 const childProcess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});46 t.is(childProcess[otherStreamName], null);47 t.not(childProcess[streamName], null);48 t.not(childProcess.all, null);49 t.is(childProcess.all.readableObjectMode, childProcess[streamName].readableObjectMode);50 t.is(childProcess.all.readableHighWaterMark, childProcess[streamName].readableHighWaterMark);5152 const result = await childProcess;53 t.is(result[otherStreamName], undefined);54 t.is(result[streamName], 'foobar');55 t.is(result.all, 'foobar');56};5758test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');59test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');6061test('can use all: true with stdout: ignore + stderr: ignore', async t => {62 const childProcess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});63 t.is(childProcess.stdout, null);64 t.is(childProcess.stderr, null);65 t.is(childProcess.all, undefined);6667 const {stdout, stderr, all} = await childProcess;68 t.is(stdout, undefined);69 t.is(stderr, undefined);70 t.is(all, undefined);71});7273const testIgnore = async (t, index, execaMethod) => {74 const result = await execaMethod('noop.js', getStdio(index, 'ignore'));75 t.is(result.stdio[index], undefined);76};7778test('stdout is undefined if ignored', testIgnore, 1, execa);79test('stderr is undefined if ignored', testIgnore, 2, execa);80test('stdio[*] is undefined if ignored', testIgnore, 3, execa);81test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);82test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);83test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);8485const getFirstDataEvent = async stream => {86 const [output] = await once(stream, 'data');87 return output.toString();88};8990const testLateStream = async (t, index, all) => {91 const subprocess = execa('noop-fd-ipc.js', [`${index}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});92 await once(subprocess, 'message');93 const [output, allOutput] = await Promise.all([94 getStream(subprocess.stdio[index]),95 all ? getStream(subprocess.all) : undefined,96 subprocess,97 ]);9899 t.is(output, '');100101 if (all) {102 t.is(allOutput, '');103 }104};105106test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);107test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);108test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);109test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);110111// eslint-disable-next-line max-params112const testIterationBuffer = async (t, index, buffer, useDataEvents, all) => {113 const subprocess = execa('noop-fd.js', [`${index}`, foobarString], {...fullStdio, buffer, all});114 const getOutput = useDataEvents ? getFirstDataEvent : getStream;115 const [result, output, allOutput] = await Promise.all([116 subprocess,117 getOutput(subprocess.stdio[index]),118 all ? getOutput(subprocess.all) : undefined,119 ]);120121 const expectedProcessResult = buffer ? foobarString : undefined;122 const expectedOutput = !buffer || useDataEvents ? foobarString : '';123124 t.is(result.stdio[index], expectedProcessResult);125 t.is(output, expectedOutput);126127 if (all) {128 t.is(result.all, expectedProcessResult);129 t.is(allOutput, expectedOutput);130 }131};132133test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);134test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);135test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);136test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);137test('Cannot iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);138test('Cannot iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);139test('Cannot iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);140test('Cannot iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);141test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);142test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);143test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);144test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);145test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);146test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);147test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);148test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);149150const testNoBufferStreamError = async (t, index, all) => {151 const subprocess = execa('noop-fd.js', [`${index}`], {...fullStdio, buffer: false, all});152 const stream = all ? subprocess.all : subprocess.stdio[index];153 const error = new Error('test');154 stream.destroy(error);155 t.is(await t.throwsAsync(subprocess), error);156};157158test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);159test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);160test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);161test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);162163const maxBuffer = 10;164165const testMaxBufferSuccess = async (t, index, all) => {166 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));167};168169test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);170test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);171test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);172test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);173174test('maxBuffer uses killSignal', async t => {175 const {isTerminated, signal} = await t.throwsAsync(176 execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),177 {message: /maxBuffer exceeded/},178 );179 t.true(isTerminated);180 t.is(signal, 'SIGINT');181});182183const testMaxBufferLimit = async (t, index, all) => {184 const length = all ? maxBuffer * 2 : maxBuffer;185 const result = await t.throwsAsync(186 execa('max-buffer.js', [`${index}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),187 {message: /maxBuffer exceeded/},188 );189 t.is(all ? result.all : result.stdio[index], '.'.repeat(length));190};191192test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);193test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);194test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);195test('maxBuffer affects all', testMaxBufferLimit, 1, true);196197const testMaxBufferEncoding = async (t, index) => {198 const result = await t.throwsAsync(199 execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'buffer'}),200 );201 const stream = result.stdio[index];202 t.true(stream instanceof Uint8Array);203 t.is(Buffer.from(stream).toString(), '.'.repeat(maxBuffer));204};205206test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);207test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);208test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);209210const testMaxBufferHex = async (t, index) => {211 const halfMaxBuffer = maxBuffer / 2;212 const {stdio} = await t.throwsAsync(213 execa('max-buffer.js', [`${index}`, `${halfMaxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'hex'}),214 );215 t.is(stdio[index], Buffer.from('.'.repeat(halfMaxBuffer)).toString('hex'));216};217218test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);219test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);220test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);221222const testNoMaxBuffer = async (t, index) => {223 const subprocess = execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, buffer: false});224 const [result, output] = await Promise.all([225 subprocess,226 getStream(subprocess.stdio[index]),227 ]);228 t.is(result.stdio[index], undefined);229 t.is(output, '.'.repeat(maxBuffer));230};231232test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);233test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);234test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);235236const testNoMaxBufferOption = async (t, index) => {237 const length = maxBuffer + 1;238 const subprocess = execa('max-buffer.js', [`${index}`, `${length}`], {...fullStdio, maxBuffer, buffer: false});239 const [result, output] = await Promise.all([240 subprocess,241 getStream(subprocess.stdio[index]),242 ]);243 t.is(result.stdio[index], undefined);244 t.is(output, '.'.repeat(length));245};246247test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);248test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);249test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);250251const testMaxBufferAbort = async (t, index) => {252 const childProcess = execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});253 await Promise.all([254 t.throwsAsync(childProcess, {message: /maxBuffer exceeded/}),255 t.throwsAsync(getStream(childProcess.stdio[index]), {code: 'ABORT_ERR'}),256 ]);257};258259test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);260test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);261test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);262263test('buffer: false > promise resolves', async t => {264 await t.notThrowsAsync(execa('noop.js', {buffer: false}));265});266267test('buffer: false > promise rejects when process returns non-zero', async t => {268 const {exitCode} = await t.throwsAsync(execa('fail.js', {buffer: false}));269 t.is(exitCode, 2);270});271272const testStreamEnd = async (t, index, buffer) => {273 const subprocess = execa('wrong command', {...fullStdio, buffer});274 await Promise.all([275 t.throwsAsync(subprocess, {message: /wrong command/}),276 once(subprocess.stdio[index], 'end'),277 ]);278};279280test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);281test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);282test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);283test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);284test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);285test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);286287const testBufferIgnore = async (t, index, all) => {288 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));289};290291test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);292test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);293test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);294295const testBufferNotRead = async (t, index, all) => {296 const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});297 await t.notThrowsAsync(subprocess);298};299300test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);301test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);302test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);303test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);304305const testBufferRead = async (t, index, all) => {306 const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});307 const stream = all ? subprocess.all : subprocess.stdio[index];308 stream.resume();309 await t.notThrowsAsync(subprocess);310};311312test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);313test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);314test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);315test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);316317test('Aborting stdout should not abort stderr nor all', async t => {318 const subprocess = execa('empty.js', {all: true});319320 subprocess.stdout.destroy();321 t.false(subprocess.stdout.readable);322 t.true(subprocess.stderr.readable);323 t.true(subprocess.all.readable);324325 await subprocess;326327 t.false(subprocess.stdout.readableEnded);328 t.is(subprocess.stdout.errored, null);329 t.true(subprocess.stdout.destroyed);330 t.true(subprocess.stderr.readableEnded);331 t.is(subprocess.stderr.errored, null);332 t.true(subprocess.stderr.destroyed);333 t.true(subprocess.all.readableEnded);334 t.is(subprocess.all.errored, null);335 t.true(subprocess.all.destroyed);336});337338const getStreamInputProcess = index => execa('stdin-fd.js', [`${index}`], index === 3339 ? getStdio(3, [new Uint8Array(), infiniteGenerator])340 : {});341const getStreamOutputProcess = index => execa('noop-repeat.js', [`${index}`], index === 3 ? fullStdio : {});342343const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {344 t.is(exitCode, 0);345 t.is(signal, undefined);346 t.false(isTerminated);347 t.true(failed);348};349350const assertStreamOutputError = (t, index, {exitCode, signal, isTerminated, failed, stderr}) => {351 if (index !== 3) {352 t.is(exitCode, 1);353 }354355 t.is(signal, undefined);356 t.false(isTerminated);357 t.true(failed);358359 if (index === 1 && !isWindows) {360 t.true(stderr.includes('EPIPE'));361 }362};363364const testStreamInputAbort = async (t, index) => {365 const childProcess = getStreamInputProcess(index);366 childProcess.stdio[index].destroy();367 const error = await t.throwsAsync(childProcess, prematureClose);368 assertStreamInputError(t, error);369};370371test('Aborting stdin should not make the process exit', testStreamInputAbort, 0);372test('Aborting input stdio[*] should not make the process exit', testStreamInputAbort, 3);373374const testStreamOutputAbort = async (t, index) => {375 const childProcess = getStreamOutputProcess(index);376 childProcess.stdio[index].destroy();377 const error = await t.throwsAsync(childProcess);378 assertStreamOutputError(t, index, error);379};380381test('Aborting stdout should not make the process exit', testStreamOutputAbort, 1);382test('Aborting stderr should not make the process exit', testStreamOutputAbort, 2);383test('Aborting output stdio[*] should not make the process exit', testStreamOutputAbort, 3);384385const testStreamInputDestroy = async (t, index) => {386 const childProcess = getStreamInputProcess(index);387 const error = new Error('test');388 childProcess.stdio[index].destroy(error);389 t.is(await t.throwsAsync(childProcess), error);390 assertStreamInputError(t, error);391};392393test('Destroying stdin should not make the process exit', testStreamInputDestroy, 0);394test('Destroying input stdio[*] should not make the process exit', testStreamInputDestroy, 3);395396const testStreamOutputDestroy = async (t, index) => {397 const childProcess = getStreamOutputProcess(index);398 const error = new Error('test');399 childProcess.stdio[index].destroy(error);400 t.is(await t.throwsAsync(childProcess), error);401 assertStreamOutputError(t, index, error);402};403404test('Destroying stdout should not make the process exit', testStreamOutputDestroy, 1);405test('Destroying stderr should not make the process exit', testStreamOutputDestroy, 2);406test('Destroying output stdio[*] should not make the process exit', testStreamOutputDestroy, 3);407408const testStreamInputError = async (t, index) => {409 const childProcess = getStreamInputProcess(index);410 const error = new Error('test');411 const stream = childProcess.stdio[index];412 stream.emit('error', error);413 stream.end();414 t.is(await t.throwsAsync(childProcess), error);415 assertStreamInputError(t, error);416};417418test('Errors on stdin should not make the process exit', testStreamInputError, 0);419test('Errors on input stdio[*] should not make the process exit', testStreamInputError, 3);420421const testStreamOutputError = async (t, index) => {422 const childProcess = getStreamOutputProcess(index);423 const error = new Error('test');424 const stream = childProcess.stdio[index];425 stream.emit('error', error);426 t.is(await t.throwsAsync(childProcess), error);427 assertStreamOutputError(t, index, error);428};429430test('Errors on stdout should not make the process exit', testStreamOutputError, 1);431test('Errors on stderr should not make the process exit', testStreamOutputError, 2);432test('Errors on output stdio[*] should not make the process exit', testStreamOutputError, 3);433434const testWaitOnStreamEnd = async (t, index) => {435 const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);436 await setTimeout(100);437 childProcess.stdio[index].end('foobar');438 const {stdout} = await childProcess;439 t.is(stdout, 'foobar');440};441442test('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);443test('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);444445const testBufferExit = async (t, index, fixtureName, reject) => {446 const childProcess = execa(fixtureName, [`${index}`], {...fullStdio, reject});447 await setTimeout(100);448 const {stdio} = await childProcess;449 t.is(stdio[index], 'foobar');450};451452test('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);453test('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);454test('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);455test('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);456test('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);457test('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);458test('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);459test('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);460test('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);461462const testBufferDirect = async (t, index) => {463 const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);464 const data = await once(childProcess.stdio[index], 'data');465 t.is(data.toString().trim(), 'foobar');466 const result = await childProcess;467 t.is(result.stdio[index], 'foobar');468};469470test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);471test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);472test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);473474const testBufferDestroyOnEnd = async (t, index) => {475 const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);476 const result = await childProcess;477 t.is(result.stdio[index], 'foobar');478 t.true(childProcess.stdio[index].destroyed);479};480481test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);482test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);483test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);484485const testProcessEventsCleanup = async (t, fixtureName) => {486 const childProcess = execa(fixtureName, {reject: false});487 t.deepEqual(childProcess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);488 await childProcess;489 t.deepEqual(childProcess.eventNames(), []);490};491492test('childProcess listeners are cleaned up on success', testProcessEventsCleanup, 'empty.js');493test('childProcess listeners are cleaned up on failure', testProcessEventsCleanup, 'fail.js');
deleted:test/test.js-300 removed
1import {delimiter, join, basename} from 'node:path';2import process from 'node:process';3import {fileURLToPath, pathToFileURL} from 'node:url';4import test from 'ava';5import isRunning from 'is-running';6import which from 'which';7import {execa, execaSync, execaNode, $} from '../index.js';8import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';9import {identity, fullStdio, getStdio} from './helpers/stdio.js';10import {noopGenerator} from './helpers/generator.js';1112setFixtureDir();13process.env.FOO = 'foo';1415const isWindows = process.platform === 'win32';16const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;1718const testOutput = async (t, index, execaMethod) => {19 const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar'], fullStdio);20 t.is(stdio[index], 'foobar');2122 if (index === 1) {23 t.is(stdio[index], stdout);24 } else if (index === 2) {25 t.is(stdio[index], stderr);26 }27};2829test('can return stdout', testOutput, 1, execa);30test('can return stderr', testOutput, 2, execa);31test('can return output stdio[*]', testOutput, 3, execa);32test('can return stdout - sync', testOutput, 1, execaSync);33test('can return stderr - sync', testOutput, 2, execaSync);34test('can return output stdio[*] - sync', testOutput, 3, execaSync);3536const testNoStdin = async (t, execaMethod) => {37 const {stdio} = await execaMethod('noop.js', ['foobar']);38 t.is(stdio[0], undefined);39};4041test('cannot return stdin', testNoStdin, execa);42test('cannot return stdin - sync', testNoStdin, execaSync);4344test('cannot return input stdio[*]', async t => {45 const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [['foobar']]));46 t.is(stdio[3], undefined);47});4849if (isWindows) {50 test('execa() - cmd file', async t => {51 const {stdout} = await execa('hello.cmd');52 t.is(stdout, 'Hello World');53 });5455 test('execa() - run cmd command', async t => {56 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);57 t.is(stdout, 'Hello World');58 });59}6061test('execaSync() throws error if ENOENT', t => {62 t.throws(() => {63 execaSync('foo');64 }, {message: ENOENT_REGEXP});65});6667test('skip throwing when using reject option', async t => {68 const {exitCode} = await execa('fail.js', {reject: false});69 t.is(exitCode, 2);70});7172test('skip throwing when using reject option in sync mode', t => {73 const {exitCode} = execaSync('fail.js', {reject: false});74 t.is(exitCode, 2);75});7677const testStripFinalNewline = async (t, index, stripFinalNewline, execaMethod) => {78 const {stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar\n'], {...fullStdio, stripFinalNewline});79 t.is(stdio[index], `foobar${stripFinalNewline === false ? '\n' : ''}`);80};8182test('stripFinalNewline: undefined with stdout', testStripFinalNewline, 1, undefined, execa);83test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, execa);84test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);85test('stripFinalNewline: undefined with stderr', testStripFinalNewline, 2, undefined, execa);86test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, execa);87test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);88test('stripFinalNewline: undefined with stdio[*]', testStripFinalNewline, 3, undefined, execa);89test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, execa);90test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);91test('stripFinalNewline: undefined with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);92test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, true, execaSync);93test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);94test('stripFinalNewline: undefined with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);95test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, true, execaSync);96test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);97test('stripFinalNewline: undefined with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);98test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, true, execaSync);99test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);100101test('stripFinalNewline is not used in objectMode', async t => {102 const {stdout} = await execa('noop-fd.js', ['1', 'foobar\n'], {stripFinalNewline: true, stdout: noopGenerator(true)});103 t.deepEqual(stdout, ['foobar\n']);104});105106const getPathWithoutLocalDir = () => {107 const newPath = process.env[PATH_KEY].split(delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(delimiter);108 return {[PATH_KEY]: newPath};109};110111const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;112113test('preferLocal: true', async t => {114 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: getPathWithoutLocalDir()}));115});116117test('preferLocal: false', async t => {118 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});119});120121test('preferLocal: undefined', async t => {122 await t.throwsAsync(execa('ava', ['--version'], {env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});123});124125test('preferLocal: undefined with $', async t => {126 await t.notThrowsAsync($({env: getPathWithoutLocalDir()})`ava --version`);127});128129test('preferLocal: undefined with $.sync', t => {130 t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);131});132133test('localDir option', async t => {134 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';135 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});136 const envPaths = stdout.split(delimiter);137 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));138});139140test('execa() returns a promise with pid', async t => {141 const subprocess = execa('noop.js', ['foo']);142 t.is(typeof subprocess.pid, 'number');143 await subprocess;144});145146const testEarlyErrorShape = async (t, reject) => {147 const subprocess = execa('', {reject});148 t.notThrows(() => {149 subprocess.catch(() => {});150 subprocess.unref();151 subprocess.on('error', () => {});152 });153};154155test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);156test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);157158test('child_process.spawn() early errors are propagated', async t => {159 const {failed} = await t.throwsAsync(execa(''));160 t.true(failed);161});162163test('child_process.spawn() early errors are returned', async t => {164 const {failed} = await execa('', {reject: false});165 t.true(failed);166});167168test('child_process.spawnSync() early errors are propagated with a correct shape', t => {169 const {failed} = t.throws(() => {170 execaSync('');171 });172 t.true(failed);173});174175test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {176 const {failed} = execaSync('', {reject: false});177 t.true(failed);178});179180test('do not try to consume streams twice', async t => {181 const subprocess = execa('noop.js', ['foo']);182 const {stdout} = await subprocess;183 const {stdout: stdout2} = await subprocess;184 t.is(stdout, 'foo');185 t.is(stdout2, 'foo');186});187188test('use relative path with \'..\' chars', async t => {189 const pathViaParentDir = join('..', basename(fileURLToPath(new URL('..', import.meta.url))), 'test', 'fixtures', 'noop.js');190 const {stdout} = await execa(pathViaParentDir, ['foo']);191 t.is(stdout, 'foo');192});193194if (!isWindows) {195 test('execa() rejects if running non-executable', async t => {196 await t.throwsAsync(execa('non-executable.js'));197 });198199 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {200 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});201 });202}203204if (!isWindows) {205 test('write to fast-exit process', async t => {206 // Try-catch here is necessary, because this test is not 100% accurate207 // Sometimes process can manage to accept input before exiting208 try {209 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});210 t.pass();211 } catch (error) {212 t.is(error.code, 'EPIPE');213 }214 });215}216217test('use environment variables by default', async t => {218 const {stdout} = await execa('environment.js');219 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);220});221222test('extend environment variables by default', async t => {223 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});224 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);225});226227test('do not extend environment with `extendEnv: false`', async t => {228 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});229 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);230});231232test('localDir option can be a URL', async t => {233 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';234 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});235 const envPaths = stdout.split(delimiter);236 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));237});238239test('can use `options.shell: true`', async t => {240 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});241 t.is(stdout, 'foo');242});243244const testShellPath = async (t, mapPath) => {245 const shellPath = isWindows ? 'cmd.exe' : 'bash';246 const shell = mapPath(await which(shellPath));247 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});248 t.is(stdout, 'foo');249};250251test('can use `options.shell: string`', testShellPath, identity);252test('can use `options.shell: file URL`', testShellPath, pathToFileURL);253254test('use extend environment with `extendEnv: true` and `shell: true`', async t => {255 process.env.TEST = 'test';256 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';257 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});258 t.is(stdout, 'test');259 delete process.env.TEST;260});261262test('detach child process', async t => {263 const {stdout} = await execa('detach.js');264 const pid = Number(stdout);265 t.true(Number.isInteger(pid));266 t.true(isRunning(pid));267268 process.kill(pid, 'SIGKILL');269});270271const testFileUrl = async (t, execaMethod) => {272 const command = new URL('noop.js', FIXTURES_DIR_URL);273 const {stdout} = await execaMethod(command, ['foobar']);274 t.is(stdout, 'foobar');275};276277test('execa()\'s command argument can be a file URL', testFileUrl, execa);278test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);279test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);280281const testInvalidFileUrl = async (t, execaMethod) => {282 const invalidUrl = new URL('https://invalid.com');283 t.throws(() => {284 execaMethod(invalidUrl);285 }, {code: 'ERR_INVALID_URL_SCHEME'});286};287288test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);289test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);290test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);291292const testInvalidCommand = async (t, execaMethod) => {293 t.throws(() => {294 execaMethod(['command', 'arg']);295 }, {message: /First argument must be a string or a file URL/});296};297298test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);299test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);300test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);
deleted:test/verbose.js-33 removed
1import test from 'ava';2import {execa} from '../index.js';3import {setFixtureDir} from './helpers/fixtures-dir.js';45setFixtureDir();67const normalizeTimestamp = output => output.replaceAll(/\d/g, '0');8const testTimestamp = '[00:00:00.000]';910test('Prints command when "verbose" is true', async t => {11 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'test'], {all: true});12 t.is(stdout, 'test');13 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);14});1516test('Prints command with NODE_DEBUG=execa', async t => {17 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({stdio: 'inherit'}), 'noop.js', 'test'], {all: true, env: {NODE_DEBUG: 'execa'}});18 t.is(stdout, 'test');19 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);20});2122test('Escape verbose command', async t => {23 const {stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'one two', '"'], {all: true});24 t.true(stderr.endsWith('"one two" "\\""'));25});2627test('Verbose option works with inherit', async t => {28 const {all} = await execa('verbose-script.js', {all: true, env: {NODE_DEBUG: 'execa'}});29 t.is(normalizeTimestamp(all), `${testTimestamp} node -e "console.error(\\"one\\")"30one31${testTimestamp} node -e "console.error(\\"two\\")"32two`);33});
modified:index.js+5 added-318 removed
1import {Buffer} from 'node:buffer';2import {setMaxListeners} from 'node:events';3import {basename} from 'node:path';4import childProcess from 'node:child_process';5import process from 'node:process';6import crossSpawn from 'cross-spawn';7import stripFinalNewline from 'strip-final-newline';8import {npmRunPathEnv} from 'npm-run-path';9import {makeError, makeEarlyError, makeSuccessResult} from './lib/error.js';10import {handleNodeOption} from './lib/node.js';11import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14import {pipeToProcess} from './lib/pipe/setup.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand} from './lib/escape.js';18import {parseCommand} from './lib/command.js';19import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';20import {parseTemplates} from './lib/script.js';21import {logCommand, verboseDefault} from './lib/verbose.js';22import {bufferToUint8Array} from './lib/stdio/utils.js';2324const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;2526const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {27 const env = extendEnv ? {...process.env, ...envOption} : envOption;2829 if (preferLocal) {30 return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});31 }3233 return env;34};3536const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {37 [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);38 const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);39 const options = handleAsyncOptions(normalizedOptions);40 return {file, args, command, escapedCommand, options};41};4243// Prevent passing the `timeout` option directly to `child_process.spawn()`44const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});4546const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {47 [rawArgs, rawOptions] = handleOptionalArguments(rawArgs, rawOptions);48 const syncOptions = normalizeSyncOptions(rawOptions);49 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);50 validateSyncOptions(options);51 return {file, args, command, escapedCommand, options};52};5354const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;5556const validateSyncOptions = ({ipc}) => {57 if (ipc) {58 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');59 }60};6162const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)63 ? [args, options]64 : [[], args];6566const handleArguments = (rawFile, rawArgs, rawOptions) => {67 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');68 const {command, escapedCommand} = joinCommand(filePath, rawArgs);6970 rawOptions.cwd = normalizeCwd(rawOptions.cwd);71 const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);7273 const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);7475 const options = addDefaultOptions(initialOptions);76 validateTimeout(options);77 options.shell = normalizeFileUrl(options.shell);78 options.env = getEnv(options);79 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);8081 if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {82 // #11683 args.unshift('/q');84 }8586 logCommand(escapedCommand, options);8788 return {file, args, command, escapedCommand, options};89};9091const addDefaultOptions = ({92 maxBuffer = DEFAULT_MAX_BUFFER,93 buffer = true,94 stripFinalNewline = true,95 extendEnv = true,96 preferLocal = false,97 cwd,98 localDir = cwd,99 encoding = 'utf8',100 reject = true,101 cleanup = true,102 all = false,103 windowsHide = true,104 verbose = verboseDefault,105 killSignal = 'SIGTERM',106 forceKillAfterDelay = true,107 lines = false,108 ipc = false,109 ...options110}) => ({111 ...options,112 maxBuffer,113 buffer,114 stripFinalNewline,115 extendEnv,116 preferLocal,117 cwd,118 localDir,119 encoding,120 reject,121 cleanup,122 all,123 windowsHide,124 verbose,125 killSignal,126 forceKillAfterDelay,127 lines,128 ipc,129});130131const handleOutput = (options, value) => {132 if (value === undefined || value === null) {133 return;134 }135136 if (Array.isArray(value)) {137 return value;138 }139140 if (Buffer.isBuffer(value)) {141 value = bufferToUint8Array(value);142 }143144 return options.stripFinalNewline ? stripFinalNewline(value) : value;145};146147export function execa(rawFile, rawArgs, rawOptions) {148 const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);149 const stdioStreamsGroups = handleInputAsync(options);150151 let spawned;152 try {153 spawned = childProcess.spawn(file, args, options);154 } catch (error) {155 cleanupStdioStreams(stdioStreamsGroups);156 // Ensure the returned error is always both a promise and a child process157 const dummySpawned = new childProcess.ChildProcess();158 const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});159 const errorPromise = options.reject ? Promise.reject(errorInstance) : Promise.resolve(errorInstance);160 mergePromise(dummySpawned, errorPromise);161 return dummySpawned;162 }163164 const controller = new AbortController();165 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);166167 const originalStreams = [...spawned.stdio];168 pipeOutputAsync(spawned, stdioStreamsGroups, controller);169 cleanupOnExit(spawned, options, controller);170171 spawned.kill = spawnedKill.bind(undefined, {kill: spawned.kill.bind(spawned), spawned, options, controller});172 spawned.all = makeAllStream(spawned, options);173 spawned.pipe = pipeToProcess.bind(undefined, {spawned, stdioStreamsGroups, options});174175 const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});176 mergePromise(spawned, promise);177 return spawned;178}179180const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {181 const context = {timedOut: false};182183 const [184 errorInfo,185 [exitCode, signal],186 stdioResults,187 allResult,188 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});189 controller.abort();190191 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));192 const all = handleOutput(options, allResult);193194 if ('error' in errorInfo) {195 const isCanceled = options.signal?.aborted === true;196 const returnedError = makeError({197 error: errorInfo.error,198 command,199 escapedCommand,200 timedOut: context.timedOut,201 isCanceled,202 exitCode,203 signal,204 stdio,205 all,206 options,207 });208209 if (!options.reject) {210 return returnedError;211 }212213 throw returnedError;214 }215216 return makeSuccessResult({command, escapedCommand, stdio, all, options});217};218219export function execaSync(rawFile, rawArgs, rawOptions) {220 const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);221 const stdioStreamsGroups = handleInputSync(options);222223 let result;224 try {225 result = childProcess.spawnSync(file, args, options);226 } catch (error) {227 const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});228229 if (!options.reject) {230 return errorInstance;231 }232233 throw errorInstance;234 }235236 pipeOutputSync(stdioStreamsGroups, result);237238 const output = result.output || Array.from({length: 3});239 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));240241 if (result.error !== undefined || isFailedExit(result.status, result.signal)) {242 const error = makeError({243 error: result.error,244 command,245 escapedCommand,246 timedOut: result.error && result.error.code === 'ETIMEDOUT',247 isCanceled: false,248 exitCode: result.status,249 signal: result.signal,250 stdio,251 options,252 });253254 if (!options.reject) {255 return error;256 }257258 throw error;259 }260261 return makeSuccessResult({command, escapedCommand, stdio, options});262}263264const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined265 ? {stdin: 'inherit'}266 : {};267268const normalizeScriptOptions = (options = {}) => ({269 preferLocal: true,270 ...normalizeScriptStdin(options),271 ...options,272});273274function create$(options) {275 function $(templatesOrOptions, ...expressions) {276 if (!Array.isArray(templatesOrOptions)) {277 return create$({...options, ...templatesOrOptions});278 }279280 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);281 return execa(file, args, normalizeScriptOptions(options));282 }283284 $.sync = (templates, ...expressions) => {285 if (!Array.isArray(templates)) {286 throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');287 }288289 const [file, ...args] = parseTemplates(templates, expressions);290 return execaSync(file, args, normalizeScriptOptions(options));291 };292293 $.s = $.sync;294295 return $;296}297298export const $ = create$();299300export function execaCommand(command, options) {301 const [file, ...args] = parseCommand(command);302 return execa(file, args, options);303}304305export function execaCommandSync(command, options) {306 const [file, ...args] = parseCommand(command);307 return execaSync(file, args, options);308}309310export function execaNode(file, args, options) {311 [args, options] = handleOptionalArguments(args, options);312313 if (options.node === false) {314 throw new TypeError('The "node" option cannot be false with `execaNode()`.');315 }316317 return execa(file, args, {...options, node: true});318}1export {execa} from './lib/async.js';2export {execaSync} from './lib/sync.js';3export {execaCommand, execaCommandSync} from './lib/command.js';4export {execaNode} from './lib/arguments/node.js';5export {$} from './lib/script.js';